halving-calculator.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 block subsidy 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 coin daemon
  19. Specify coin with --coin=btc (default)/--coin=bch/--coin=ltc
  20. If necessary, invoke with --rpc-host/--rpc-port/--rpc-user/--rpc-password
  21. Specify aiohttp backend with --rpc-backend=aiohttp (Linux only)
  22. A more full-featured version of this program can be found in the
  23. mmgen-node-tools repository.
  24. """
  25. }
  26. })
  27. def date(t):
  28. return '{}-{:02}-{:02} {:02}:{:02}:{:02}'.format(*time.gmtime(t)[:6])
  29. def dhms(t):
  30. t,neg = (-t,'-') if t < 0 else (t,' ')
  31. return f'{neg}{t//60//60//24} days, {t//60//60%24:02}:{t//60%60:02}:{t%60:02} h/m/s'
  32. def time_diff_warning(t_diff):
  33. if abs(t_diff) > 60*60:
  34. print('Warning: block tip time is {} {} clock time!'.format(
  35. dhms(abs(t_diff)),
  36. ('behind','ahead of')[t_diff<0]))
  37. async def main():
  38. from mmgen.protocol import init_proto_from_opts
  39. proto = init_proto_from_opts()
  40. from mmgen.rpc import rpc_init
  41. c = await rpc_init(proto)
  42. tip = await c.call('getblockcount')
  43. assert tip > 1, 'block tip must be > 1'
  44. remaining = proto.halving_interval - tip % proto.halving_interval
  45. sample_size = int(opt.sample_size) if opt.sample_size else min(tip-1,max(remaining,144))
  46. # aiohttp backend will perform these two calls concurrently:
  47. cur,old = await c.gathered_call('getblockstats',((tip,),(tip - sample_size,)))
  48. clock_time = int(time.time())
  49. time_diff_warning(clock_time - cur['time'])
  50. bdr = (cur['time'] - old['time']) / sample_size
  51. t_rem = remaining * int(bdr)
  52. sub = cur['subsidy'] * proto.coin_amt.satoshi
  53. print(
  54. f'Current block: {tip}\n'
  55. f'Next halving block: {tip + remaining}\n'
  56. f'Blocks until halving: {remaining}\n'
  57. f'Current block subsidy: {str(sub).rstrip("0")} {proto.coin}\n'
  58. f'Current block discovery rate (over last {sample_size} blocks): {bdr/60:0.1f} minutes\n'
  59. f'Current clock time (UTC): {date(clock_time)}\n'
  60. f'Est. halving date (UTC): {date(cur["time"] + t_rem)}\n'
  61. f'Est. time until halving: {dhms(cur["time"] + t_rem - clock_time)}\n'
  62. )
  63. run_session(main())