halving-calculator.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. # Demonstrates use of the MMGen asyncio/aiohttp JSON-RPC interface
  3. # https://github.com/mmgen/mmgen
  4. # Requires a running Bitcoin Core node
  5. # If necessary, invoke with --rpc-host/--rpc-port/--rpc-user/--rpc-password
  6. # Specify aiohttp backend with --rpc-backend=aiohttp (Linux only)
  7. import time
  8. from decimal import Decimal
  9. from mmgen.common import *
  10. opts.init({ 'text': { 'desc':'', 'usage':'', 'options':'' }})
  11. HalvingInterval = 210000 # src/chainparams.cpp
  12. def date(t):
  13. return '{}-{:02}-{:02} {:02}:{:02}:{:02}'.format(*time.gmtime(t)[:6])
  14. def dhms(t):
  15. return f'{t//60//60//24} days, {t//60//60%24:02}:{t//60%60:02}:{t%60:02} h/m/s'
  16. def time_diff_warning(t_diff):
  17. if abs(t_diff) > 60*60:
  18. print('Warning: block tip time is {} {} clock time!'.format(
  19. dhms(abs(t_diff)),
  20. ('behind','ahead of')[t_diff<0]))
  21. async def main():
  22. from mmgen.rpc import rpc_init
  23. c = await rpc_init()
  24. tip = await c.call('getblockcount')
  25. remaining = HalvingInterval - tip % HalvingInterval
  26. sample_size = max(remaining,144)
  27. # aiohttp backend will perform these two calls concurrently:
  28. cur,old = await c.gathered_call('getblockstats',((tip,),(tip - sample_size,)))
  29. clock_time = int(time.time())
  30. time_diff_warning(clock_time - cur['time'])
  31. bdr = (cur['time'] - old['time']) / sample_size
  32. t_rem = remaining * int(bdr)
  33. sub = cur['subsidy'] * Decimal('0.00000001')
  34. print(f'Current block: {tip}')
  35. print(f'Next halving block: {tip + remaining}')
  36. print(f'Blocks until halving: {remaining}')
  37. print('Current block subsidy: {} BTC'.format(str(sub).rstrip('0')))
  38. print(f'Current block discovery rate (over last {sample_size} blocks): {bdr/60:0.1f} minutes')
  39. print(f'Current clock time (UTC): {date(clock_time)}')
  40. print(f'Est. halving date (UTC): {date(cur["time"] + t_rem)}')
  41. print(f'Est. time until halving: {dhms(cur["time"] + t_rem - clock_time)}')
  42. run_session(main(),do_rpc_init=False)