halving-calculator.py 2.3 KB

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