Skip to content

Instantly share code, notes, and snippets.

@meeDamian
Last active July 22, 2018 03:08
Show Gist options
  • Save meeDamian/ef87d8ca3443ddf1b3c05d2d4a591066 to your computer and use it in GitHub Desktop.
Save meeDamian/ef87d8ca3443ddf1b3c05d2d4a591066 to your computer and use it in GitHub Desktop.
#!/usr/bin/env zsh
# NOTE:
# Running this script requires:
# * bitcoind - full archival node,
# * jq - `sudo apt install jq`,
# * zsh - `sudo apt install zsh`.
FILE=~/block_data.txt
MAX=$(bitcoin-cli getblockcount)
STEP=100
COUNTER=0
if [ -f "${FILE}" ]; then
COUNTER=$(tail -n 1 "${FILE}" | cut -d ' ' -f 2)
fi
if [ "${MAX}" != "${COUNTER}" ]; then
COUNTER=$(expr ${COUNTER} + 1)
echo "Fetching block timestamps starting from ${COUNTER}…"
batch=""
until [ ${COUNTER} -ge ${MAX} ]; do
batch="${batch}$(bitcoin-cli getblockheader $(bitcoin-cli getblockhash ${COUNTER}) | jq '.time') ${COUNTER}\n"
if [ $(expr ${COUNTER} % ${STEP}) -eq 0 ]; then
echo -n "${batch}" >> ${FILE}
echo "Blocks $(expr ${COUNTER} - ${STEP} + 1) to ${COUNTER} processed"
batch=""
fi
COUNTER=$(expr ${COUNTER} + 1)
done
if [ ! -z "${batch}" ]; then
echo -n "${batch}" >> ${FILE}
fi
echo "Fetching timestamps done"
else
echo "Block timestamps are up-to-date"
fi
# make sure there's no gaps in block data
gaps="$(awk 'NR==1{p=$2;next}{print $2-p; p=$2}END{}' block_data.txt | sort | uniq | wc -l)"
if [ ${gaps} != 1 ]; then
echo "Some blocks are missing!"
exit 1
else
echo "No gaps in the set"
fi
# calculate time difference between each two concurrent blocks
echo -n "Calculating differences… "
awk 'NR==1{p=$1;next}{print $1-p; p=$1}END{}' block_data.txt > block_diffs.txt
echo "done"
# sort all differences
echo -n "Sorting differences… "
cat block_diffs.txt | sort -n > block_diffs_sorted.txt
echo "done"
BOLD=$(tput bold)
RESET_STYLE=$(tput sgr0)
# calculate median time between blocks
echo -n "Calculating median time between blocks… "
median="$(awk '{count[NR]=$1;}END{if(NR%2){print count[(NR+1)/2];}else{print (count[(NR/2)] + count[(NR/2)+1])/2.0;}}' block_diffs_sorted.txt)"
echo "done: ${BOLD}$(expr ${median} / 60)m $(expr ${median} % 60)s${RESET_STYLE}"
# calculate average time between blocks
echo -n "Calculating average time between blocks… "
average="$(awk '{total+=$1;count++}END{print int(total/count)}' block_diffs_sorted.txt)"
echo "done: ${BOLD}$(expr ${average} / 60)m $(expr ${average} % 60)s${RESET_STYLE}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment