main_halving_calculator.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU General Public License as published by the Free Software
  8. # Foundation, either version 3 of the License, or (at your option) any later
  9. # version.
  10. #
  11. # This program is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU General Public License along with
  17. # this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmnode-halving-calculator: Estimate date(s) of future block subsidy halving(s)
  20. """
  21. import time
  22. from decimal import Decimal
  23. from mmgen.cfg import Config
  24. from mmgen.util import async_run
  25. bdr_proj = 9.95
  26. opts_data = {
  27. 'sets': [('mined',True,'list',True)],
  28. 'text': {
  29. 'desc': 'Estimate date(s) of future block subsidy halving(s)',
  30. 'usage':'[opts]',
  31. 'options': f"""
  32. -h, --help Print this help message
  33. --, --longhelp Print help message for long options (common options)
  34. -l, --list List historical and projected halvings
  35. -m, --mined Same as above, plus list coins mined
  36. -r, --bdr-proj=I Block discovery interval for projected halvings (default:
  37. {bdr_proj:.5f} min)
  38. -s, --sample-size=N Block range to calculate block discovery interval for next
  39. halving estimate (default: dynamically calculated)
  40. """ }
  41. }
  42. cfg = Config(opts_data=opts_data)
  43. if cfg.bdr_proj:
  44. bdr_proj = float(cfg.bdr_proj)
  45. def date(t):
  46. return '{}-{:02}-{:02} {:02}:{:02}:{:02}'.format(*time.gmtime(t)[:6])
  47. def dhms(t):
  48. t,neg = (-t,'-') if t < 0 else (t,' ')
  49. return f'{neg}{t//60//60//24} days, {t//60//60%24:02}:{t//60%60:02}:{t%60:02} h/m/s'
  50. def time_diff_warning(t_diff):
  51. if abs(t_diff) > 60*60:
  52. print('Warning: block tip time is {} {} clock time!'.format(
  53. dhms(abs(t_diff)),
  54. ('behind','ahead of')[t_diff<0]))
  55. async def main():
  56. proto = cfg._proto
  57. from mmgen.rpc import rpc_init
  58. c = await rpc_init( cfg, proto, ignore_wallet=True )
  59. tip = await c.call('getblockcount')
  60. assert tip > 1, 'block tip must be > 1'
  61. remaining = proto.halving_interval - tip % proto.halving_interval
  62. sample_size = int(cfg.sample_size) if cfg.sample_size else min(tip-1,max(remaining,144))
  63. cur,old = await c.gathered_call('getblockstats',((tip,),(tip - sample_size,)))
  64. clock_time = int(time.time())
  65. time_diff_warning(clock_time - cur['time'])
  66. bdr = (cur['time'] - old['time']) / sample_size
  67. t_rem = remaining * int(bdr)
  68. t_next = cur['time'] + t_rem
  69. if proto.name == 'BitcoinCash':
  70. sub = proto.coin_amt(str(cur['subsidy']))
  71. else:
  72. sub = cur['subsidy'] * proto.coin_amt.satoshi
  73. def print_current_stats():
  74. print(
  75. f'Current block: {tip:>7}\n'
  76. f'Next halving block: {tip + remaining:>7}\n'
  77. f'Halving interval: {proto.halving_interval:>7}\n'
  78. f'Blocks since last halving: {proto.halving_interval - remaining:>7}\n'
  79. f'Blocks until next halving: {remaining:>7}\n\n'
  80. f'Current block subsidy: {str(sub).rstrip("0")} {proto.coin}\n'
  81. f'Current block discovery interval (over last {sample_size} blocks): {bdr/60:0.2f} min\n\n'
  82. f'Current clock time (UTC): {date(clock_time)}\n'
  83. f'Est. halving date (UTC): {date(t_next)}\n'
  84. f'Est. time until halving: {dhms(cur["time"] + t_rem - clock_time)}'
  85. )
  86. async def print_halvings():
  87. halving_blocknums = [i*proto.halving_interval for i in range(proto.max_halvings+1)][1:]
  88. hist_halvings = await c.gathered_call('getblockstats',([(n,) for n in halving_blocknums if n <= tip]))
  89. halving_secs = bdr_proj * 60 * proto.halving_interval
  90. nhist = len(hist_halvings)
  91. nSubsidy = int(proto.start_subsidy / proto.coin_amt.satoshi)
  92. block0_hash = await c.call('getblockhash',0)
  93. block0_date = (await c.call('getblock',block0_hash))['time']
  94. def gen_data():
  95. total_mined = 0
  96. date = block0_date
  97. for n,blk in enumerate(halving_blocknums):
  98. mined = (nSubsidy >> n) * proto.halving_interval
  99. if n == 0:
  100. mined -= nSubsidy # subtract unspendable genesis block subsidy
  101. total_mined += mined
  102. sub = nSubsidy >> n+1 if n+1 < proto.max_halvings else 0
  103. bdi = (
  104. (hist_halvings[n]['time'] - date) / (proto.halving_interval * 60) if n < nhist
  105. else bdr/60 if n == nhist
  106. else bdr_proj
  107. )
  108. date = (
  109. hist_halvings[n]['time'] if n < nhist
  110. else t_next + int((n - nhist) * halving_secs)
  111. )
  112. yield ( n, sub, blk, mined, total_mined, bdi, date )
  113. if sub == 0:
  114. break
  115. fs = (
  116. ' {a:<7} {b:>8} {c:19}{d:2} {e:10} {f}',
  117. ' {a:<7} {b:>8} {c:19}{d:2} {e:10} {f:17} {g:17} {h}'
  118. )[bool(cfg.mined)]
  119. print(
  120. f'Historical/Estimated/Projected Halvings ({proto.coin}):\n\n'
  121. + f' Sample size for next halving estimate (E): {sample_size} blocks\n'
  122. + f' Block discovery interval for projected halvings (P): {bdr_proj:.5f} minutes\n\n'
  123. + fs.format(
  124. a = 'HALVING',
  125. b = 'BLOCK',
  126. c = 'DATE',
  127. d = '',
  128. e = f'BDI (mins)',
  129. f = f'SUBSIDY ({proto.coin})',
  130. g = f'MINED ({proto.coin})',
  131. h = f'TOTAL MINED ({proto.coin})'
  132. )
  133. + '\n'
  134. + fs.format(
  135. a = '-' * 7,
  136. b = '-' * 8,
  137. c = '-' * 19,
  138. d = '-' * 2,
  139. e = '-' * 10,
  140. f = '-' * 13,
  141. g = '-' * 17,
  142. h = '-' * 17
  143. )
  144. + '\n'
  145. + '\n'.join(fs.format(
  146. a = n + 1,
  147. b = blk,
  148. c = date(t),
  149. d = ' P' if n > nhist else '' if n < nhist else ' E',
  150. e = f'{bdr:8.5f}',
  151. f = proto.coin_amt(sub,from_unit='satoshi').fmt(iwidth=2,prec=8),
  152. g = proto.coin_amt(mined,from_unit='satoshi').fmt(iwidth=8,prec=8),
  153. h = proto.coin_amt(total_mined,from_unit='satoshi').fmt(iwidth=8,prec=8)
  154. ) for n,sub,blk,mined,total_mined,bdr,t in gen_data())
  155. )
  156. if cfg.list:
  157. await print_halvings()
  158. else:
  159. print_current_stats()
  160. async_run(main())