Last Updated: February 25, 2016
·
702
· erebusbat

Shell Script to Time to Next Bitcoin Difficulty Adjustment

I recently needed a quick way to see when the next bitcoin difficuilty adjustment would occur. Surprisingly there is no (working) online resource to see this. I wrote this quick script to grab the relevent raw data from blockchain.info and parse it to show me a quick output of when it will happen.

Keep in mind that this is only an estimate and changes with time / network hash speed. If you don't know this then this script is probably not useful for you. This is ZSH specific as it uses the mathfun zsh module.

#!/bin/zsh
zmodload zsh/mathfunc
echo "Loading data from blockchain.info ..."
NEXT_RETARGET=$(curl -s http://blockchain.info/q/nextretarget)
CURRENT_BLOCK=$(curl -s http://blockchain.info/q/getblockcount)
AVG_BLOCK_TIME=$(curl -s http://blockchain.info/q/interval)
(( AVG_BLOCK_TIME=int(floor($AVG_BLOCK_TIME)) ))    # Convert AVG time to int
(( BLOCKS_LEFT=$NEXT_RETARGET - $CURRENT_BLOCK ))
(( TOTAL_SECS_LEFT=$AVG_BLOCK_TIME * $BLOCKS_LEFT ))

##########################
# Calculate Seconds Left
##########################
TIME_LEFT=""
DAYS_LEFT=0
HOURS_LEFT=0
MINS_LEFT=0
(( SECS_LEFT=int(rint($TOTAL_SECS_LEFT)) ))

# Days
if [ $SECS_LEFT -ge 86400 ]; then
    (( DAYS_LEFT=int(floor($SECS_LEFT / 86400)) ))
    (( SECS_LEFT=$SECS_LEFT-$DAYS_LEFT * 86400 ))
fi
# Hours
if [ $SECS_LEFT -ge 3600 ]; then
    (( HOURS_LEFT=int(floor($SECS_LEFT / 3600)) ))
    (( SECS_LEFT=$SECS_LEFT-$HOURS_LEFT * 3600 ))
fi
# Mins
if [ $SECS_LEFT -ge 60 ]; then
    (( MINS_LEFT=int(floor($SECS_LEFT / 60)) ))
    (( SECS_LEFT=$SECS_LEFT-$MINS_LEFT * 60 ))
fi

if [ $DAYS_LEFT -gt 0 ]; then TIME_LEFT="${TIME_LEFT}${DAYS_LEFT}d "; fi
if [ $HOURS_LEFT -gt 0 ]; then TIME_LEFT="${TIME_LEFT}${HOURS_LEFT}h "; fi
if [ $MINS_LEFT -gt 0 ]; then TIME_LEFT="${TIME_LEFT}${MINS_LEFT}m "; fi
if [ $SECS_LEFT -gt 0 ]; then TIME_LEFT="${TIME_LEFT}${SECS_LEFT}s"; fi

cat <<EOF
    Current Block Height: $CURRENT_BLOCK
           Next Retarget: $NEXT_RETARGET
             Blocks Left: $BLOCKS_LEFT
          Avg Time Solve: $AVG_BLOCK_TIME

         Total Secs Left: $TOTAL_SECS_LEFT
               Est. Left: $TIME_LEFT
EOF

The ouput looks like this:

Loading data from blockchain.info ...
    Current Block Height: 261304
           Next Retarget: 262079
             Blocks Left: 775
          Avg Time Solve: 496

         Total Secs Left: 384400
               Est. Left: 4d 10h 46m 40s