mmnode-blocks-info 13 KB

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