mmnode-blocks-info 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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-blocks-info: Display information about a block or range of blocks
  20. """
  21. import re
  22. from collections import namedtuple
  23. from time import strftime,gmtime
  24. from mmgen.common import *
  25. from mmgen.util import secs_to_hms
  26. from decimal import Decimal
  27. class local_vars: pass
  28. class BlocksInfo:
  29. total_bytes = 0
  30. total_weight = 0
  31. bf = namedtuple('block_info_fields',['hdr1','hdr2','fs','bs_key','varname','deps','key'])
  32. # bs=getblockstats(), bh=getblockheader()
  33. # 'getblockstats' raises exception on Genesis Block!
  34. # If 'bs_key' is set, it's included in self.bs_keys instead of 'key'
  35. fields = {
  36. 'block': bf('', 'Block', '{:<6}', None, 'height',[], None),
  37. 'hash': bf('', 'Hash', '{:<64}', None, 'H', [], None),
  38. 'date': bf('', 'Date', '{:<19}', None, 'df', [], None),
  39. 'interval': bf('Solve','Time ', '{:>6}', None, 'td', [], None),
  40. 'size': bf('', 'Size', '{:>7}', None, 'bs', [], 'total_size'),
  41. 'weight': bf('', 'Weight', '{:>7}', None, 'bs', [], 'total_weight'),
  42. 'utxo_inc': bf(' UTXO',' Incr', '{:>5}', None, 'bs', [], 'utxo_increase'),
  43. 'fee10': bf('10%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 0),
  44. 'fee25': bf('25%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 1),
  45. 'fee50': bf('50%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 2),
  46. 'fee75': bf('75%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 3),
  47. 'fee90': bf('90%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 4),
  48. 'fee_avg': bf('Avg', 'Fee', '{:>3}', None, 'bs', [], 'avgfeerate'),
  49. 'fee_min': bf('Min', 'Fee', '{:>3}', None, 'bs', [], 'minfeerate'),
  50. 'totalfee': bf('', 'Total Fee','{:>10}', 'totalfee', 'tf', ['bs'], None),
  51. 'outputs': bf('Out-', 'puts', '{:>5}', None, 'bs', [], 'outs'),
  52. 'inputs': bf('In- ', 'puts', '{:>5}', None, 'bs', [], 'ins'),
  53. 'version': bf('', 'Version', '{:8}', None, 'bh', [], 'versionHex'),
  54. 'nTx': bf('', 'nTx ', '{:>5}', None, 'bh', [], 'nTx'),
  55. 'subsidy': bf('', 'Subsidy', '{:7}', 'subsidy', 'su', ['bs'], None),
  56. }
  57. dfl_fields = ['block','date','interval','subsidy','totalfee','size','weight','fee50','fee25','fee10','version']
  58. funcs = {
  59. 'df': lambda self,loc: strftime('%Y-%m-%d %X',gmtime(self.t_cur)),
  60. 'td': lambda self,loc: (
  61. '-{:02}:{:02}'.format(abs(self.t_diff)//60,abs(self.t_diff)%60) if self.t_diff < 0 else
  62. ' {:02}:{:02}'.format(self.t_diff//60,self.t_diff%60) ),
  63. 'tf': lambda self,loc: '{:.8f}'.format(loc.bs["totalfee"] * Decimal('0.00000001')),
  64. 'fp': lambda self,loc: loc.bs['feerate_percentiles'],
  65. 'su': lambda self,loc: str(loc.bs['subsidy'] * Decimal('0.00000001')).rstrip('0').rstrip('.'),
  66. }
  67. def __init__(self):
  68. self.get_block_range()
  69. if opt.fields:
  70. fnames = opt.fields.split(',')
  71. for n in fnames:
  72. if n not in self.fields:
  73. die(1,f'{n!r}: unrecognized field')
  74. else:
  75. fnames = self.dfl_fields
  76. self.fvals = list(self.fields[k] for k in fnames if k in self.fields)
  77. self.fs = ' '.join( v.fs for v in self.fvals )
  78. self.deps = set(' '.join(v.varname + ' ' + ' '.join(v.deps) for v in self.fvals).split())
  79. self.bs_keys = [(v.bs_key or v.key) for v in self.fvals if v.bs_key or v.varname == 'bs']
  80. self.bs_keys.extend(['total_size','total_weight'])
  81. self.ufuncs = {v.varname:self.funcs[v.varname] for v in self.fvals if v.varname in self.funcs}
  82. if opt.miner_info:
  83. self.fs += ' {}'
  84. self.miner_pats = [re.compile(pat) for pat in (
  85. rb'[\xe3\xe4\xe5][\^/](.*?)\xfa',
  86. rb'([a-zA-Z0-9&. -]+/Mined by [a-zA-Z0-9. ]+)',
  87. rb'\x08/(.*Mined by [a-zA-Z0-9. ]+)',
  88. rb'Mined by ([a-zA-Z0-9. ]+)',
  89. rb'[/^]([a-zA-Z0-9&. /-]{5,})',
  90. rb'[/^]([a-zA-Z0-9&. /-]+)/',
  91. )]
  92. else:
  93. self.miner_pats = None
  94. def get_block_range(self):
  95. if not cmd_args:
  96. first = last = c.blockcount
  97. else:
  98. arg = cmd_args[0]
  99. if arg.startswith('+') and is_int(arg[1:]):
  100. last = c.blockcount
  101. first = last - int(arg[1:]) + 1
  102. elif is_int(arg):
  103. first = last = int(arg)
  104. else:
  105. try:
  106. first,last = [int(ep) for ep in arg.split('-')]
  107. except:
  108. opts.usage()
  109. if first > last:
  110. die(2,f'{first}-{last}: invalid block range')
  111. if last > c.blockcount:
  112. die(2,f'Requested block number ({last}) greater than current block height')
  113. self.first = first
  114. self.last = last
  115. async def run(self):
  116. heights = range(self.first,self.last+1)
  117. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  118. hdrs = await c.gathered_call('getblockheader',[(H,) for H in hashes])
  119. self.t_start = hdrs[0]['time']
  120. self.t_cur = (
  121. self.t_start if heights[0] == 0 else
  122. (await c.call('getblockheader',await c.call('getblockhash',heights[0]-1)))['time']
  123. )
  124. for height in heights:
  125. await self.process_block(height,hashes.pop(0),hdrs.pop(0))
  126. async def process_block(self,height,H,hdr):
  127. loc = local_vars()
  128. loc.height = height
  129. loc.H = H
  130. loc.bh = hdr
  131. self.t_diff = hdr['time'] - self.t_cur
  132. self.t_cur = hdr['time']
  133. if 'bs' in self.deps:
  134. loc.bs = await c.call('getblockstats',H,self.bs_keys)
  135. self.total_bytes += loc.bs['total_size']
  136. self.total_weight += loc.bs['total_weight']
  137. if opt.summary:
  138. return
  139. for varname,func in self.ufuncs.items():
  140. setattr(loc,varname,func(self,loc))
  141. if opt.miner_info:
  142. miner_info = await self.get_miner_string(H)
  143. def gen():
  144. for v in self.fvals:
  145. if v.key is None:
  146. yield getattr(loc,v.varname)
  147. else:
  148. yield getattr(loc,v.varname)[v.key]
  149. if opt.miner_info:
  150. yield miner_info
  151. Msg(self.fs.format(*gen()))
  152. async def get_miner_string(self,H):
  153. tx0 = (await c.call('getblock',H))['tx'][0]
  154. bd = await c.call('getrawtransaction',tx0,1)
  155. if type(bd) == tuple:
  156. return '---'
  157. else:
  158. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  159. if opt.raw_miner_info:
  160. return repr(cb)
  161. else:
  162. for pat in self.miner_pats:
  163. m = pat.search(cb)
  164. if m:
  165. return ''.join(chr(b) for b in m[1] if 31 < b < 127).strip('^').strip('/').replace('/',' ')
  166. def print_header(self):
  167. hdr1 = [v.hdr1 for v in self.fvals]
  168. hdr2 = [v.hdr2 for v in self.fvals]
  169. if opt.miner_info:
  170. hdr1.append(' ')
  171. hdr2.append('Miner')
  172. if ''.join(hdr1).replace(' ',''):
  173. Msg(self.fs.format(*hdr1))
  174. Msg(self.fs.format(*hdr2))
  175. async def print_summary(self):
  176. tip = c.blockcount
  177. if self.last == tip:
  178. rel = tip % 2016
  179. if rel:
  180. HA,HB = await c.gathered_call('getblockhash',([tip-rel],[tip]))
  181. hA,hB = await c.gathered_call('getblockheader',([HA],[HB]))
  182. bdi = (hB['time']-hA['time']) / rel
  183. adj_pct = ((600 / bdi) - 1) * 100
  184. Msg(fmt(f"""
  185. Current height: {tip}
  186. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks [{((2016-rel)*bdi)/86400:.2f} days])
  187. BDI (cur period): {bdi/60:.2f} min
  188. Est. diff adjust: {adj_pct:+.2f}%
  189. """))
  190. else:
  191. Msg(fmt(f"""
  192. Current height: {tip}
  193. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks)
  194. """))
  195. nblocks = self.last - self.first + 1
  196. Msg('Range: {}-{} ({} blocks [{}])'.format(
  197. self.first,
  198. self.last,
  199. nblocks,
  200. secs_to_hms(self.t_cur - self.t_start) ))
  201. if 'bs' in self.deps and nblocks > 1:
  202. elapsed = self.t_cur - self.t_start
  203. ac = int(elapsed / nblocks)
  204. rate = (self.total_bytes / 10000) / (elapsed / 36)
  205. Msg_r(fmt(f"""
  206. Avg size: {self.total_bytes//nblocks} bytes
  207. Avg weight: {self.total_weight//nblocks} bytes
  208. MB/hr: {rate:0.4f}
  209. Avg BDI: {ac/60:.2f} min
  210. """))
  211. opts_data = {
  212. 'sets': [
  213. ('raw_miner_info', True, 'miner_info', True),
  214. ('summary', True, 'raw_miner_info', False),
  215. ('summary', True, 'miner_info', False),
  216. ('hashes', True, 'fields', 'block,hash'),
  217. ('hashes', True, 'no_summary', True),
  218. ],
  219. 'text': {
  220. 'desc': 'Display information about a block or range of blocks',
  221. 'usage': '[opts] +<last N blocks>|<block num>[-<block num>]',
  222. 'options': """
  223. -h, --help Print this help message
  224. --, --longhelp Print help message for long options (common options)
  225. -H, --hashes Display only block numbers and hashes
  226. -m, --miner-info Display miner info in coinbase transaction
  227. -M, --raw-miner-info Display miner info in uninterpreted form
  228. -n, --no-header Don’t print the column header
  229. -o, --fields= Display the specified fields (comma-separated list)
  230. See AVAILABLE FIELDS below.
  231. -s, --summary Print the summary only
  232. -S, --no-summary Don’t print the summary
  233. """,
  234. 'notes': """
  235. If no block number is specified, the current block is assumed.
  236. If the requested range ends at the current chain tip, an estimate of the next
  237. difficulty adjustment is also displayed. The estimate is based on the average
  238. Block Discovery Interval from the beginning of the current 2016-block period.
  239. AVAILABLE FIELDS: {}
  240. This program requires a txindex-enabled daemon for correct operation.
  241. """.format(fmt_list(BlocksInfo.fields,fmt='bare'))
  242. }
  243. }
  244. cmd_args = opts.init(opts_data)
  245. if len(cmd_args) not in (0,1):
  246. opts.usage()
  247. async def main():
  248. from mmgen.protocol import init_proto_from_opts
  249. proto = init_proto_from_opts()
  250. from mmgen.rpc import rpc_init
  251. global c
  252. c = await rpc_init(proto)
  253. m = BlocksInfo()
  254. if not (opt.summary or opt.no_header):
  255. m.print_header()
  256. await m.run()
  257. if not opt.no_summary:
  258. if not opt.summary:
  259. Msg('')
  260. await m.print_summary()
  261. run_session(main())