halving-calculator.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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()
  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.protocol import init_proto_from_opts
  23. proto = init_proto_from_opts()
  24. from mmgen.rpc import rpc_init
  25. c = await rpc_init(proto)
  26. tip = await c.call('getblockcount')
  27. remaining = HalvingInterval - tip % HalvingInterval
  28. sample_size = max(remaining,144)
  29. # aiohttp backend will perform these two calls concurrently:
  30. cur,old = await c.gathered_call('getblockstats',((tip,),(tip - sample_size,)))
  31. clock_time = int(time.time())
  32. time_diff_warning(clock_time - cur['time'])
  33. bdr = (cur['time'] - old['time']) / sample_size
  34. t_rem = remaining * int(bdr)
  35. sub = cur['subsidy'] * Decimal('0.00000001')
  36. print(f'Current block: {tip}')
  37. print(f'Next halving block: {tip + remaining}')
  38. print(f'Blocks until halving: {remaining}')
  39. print('Current block subsidy: {} BTC'.format(str(sub).rstrip('0')))
  40. print(f'Current block discovery rate (over last {sample_size} blocks): {bdr/60:0.1f} minutes')
  41. print(f'Current clock time (UTC): {date(clock_time)}')
  42. print(f'Est. halving date (UTC): {date(cur["time"] + t_rem)}')
  43. print(f'Est. time until halving: {dhms(cur["time"] + t_rem - clock_time)}')
  44. run_session(main())