Skip to content

Instantly share code, notes, and snippets.

@dskvr
Last active September 5, 2024 23:54
Show Gist options
  • Save dskvr/18252c16cf85c06c1ee6cb5ae04a3197 to your computer and use it in GitHub Desktop.
Save dskvr/18252c16cf85c06c1ee6cb5ae04a3197 to your computer and use it in GitHub Desktop.
find bitcoin block number with a provided timestamp
#!/bin/bash
# USAGE:
# fjb.sh <timestamp>
# returns: <blocknum>
TIMESTAMP=$1
LOWER=0
UPPER=$(bitcoin-cli getblockcount)
while (( LOWER <= UPPER )); do
MID=$(( (LOWER + UPPER) / 2 ))
BLOCKHASH=$(bitcoin-cli getblockhash $MID)
BLOCKTIME=$(bitcoin-cli getblockheader $BLOCKHASH | jq .time)
if (( BLOCKTIME < TIMESTAMP )); then
LOWER=$(( MID + 1 ))
elif (( BLOCKTIME > TIMESTAMP )); then
UPPER=$(( MID - 1 ))
else
echo "$BLOCKTIME"
exit 0
fi
done
echo "$UPPER"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment