mmnode-blocks-info 11 KB

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