Skip to content

Instantly share code, notes, and snippets.

@mutatrum
Last active September 14, 2022 20:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutatrum/015d0022bc048d6c9ee07f36ab650c31 to your computer and use it in GitHub Desktop.
Save mutatrum/015d0022bc048d6c9ee07f36ab650c31 to your computer and use it in GitHub Desktop.
Calculate block height based on a timestamp
#!/bin/bash
TIME=$(date -d "$1" +"%s")
function getBlockTime {
echo $(bitcoin-cli getblockheader $(bitcoin-cli getblockhash $1) | jq -r .time)
}
function binarySearch {
L=$1
R=$2
if ((R >= L));
then
BLOCK=$((L + (R - L) / 2))
BLOCKTIME=$(getBlockTime $BLOCK)
if ((BLOCKTIME == TIME));
then
echo $BLOCK
elif ((BLOCKTIME > TIME));
then
echo $(binarySearch $L $((BLOCK - 1)))
else
echo $(binarySearch $((BLOCK + 1)) $R)
fi
else
echo $R
fi
}
BLOCKS=$(bitcoin-cli getblockchaininfo | jq -r .blocks)
BLOCK=$(binarySearch 0 $BLOCKS)
if ((BLOCK >= 0));
then
BLOCKTIME=$(getBlockTime $BLOCK)
echo "Block $BLOCK: $(date -d @$BLOCKTIME -Iseconds) $((BLOCKTIME - TIME)) seconds"
fi
if ((BLOCKTIME != TIME)) && ((BLOCK < BLOCKS));
then
NEXTBLOCK=$((BLOCK + 1))
NEXTBLOCKTIME=$(getBlockTime $NEXTBLOCK)
echo "Block $NEXTBLOCK: $(date -d @$NEXTBLOCKTIME -Iseconds) $((NEXTBLOCKTIME - TIME)) seconds"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment