mmnode-blocks-info 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. total_solve_time = 0
  32. step = None
  33. bf = namedtuple('block_info_fields',['hdr1','hdr2','fs','bs_key','varname','deps','key'])
  34. # bs=getblockstats(), bh=getblockheader()
  35. # If 'bs_key' is set, it's included in self.bs_keys instead of 'key'
  36. fields = {
  37. 'block': bf('', 'Block', '{:<6}', None, 'height',[], None),
  38. 'hash': bf('', 'Hash', '{:<64}', None, 'H', [], None),
  39. 'date': bf('', 'Date', '{:<19}', None, 'df', [], None),
  40. 'interval': bf('Solve','Time ', '{:>8}', None, 'td', [], None),
  41. 'size': bf('', 'Size', '{:>7}', None, 'bs', [], 'total_size'),
  42. 'weight': bf('', 'Weight', '{:>7}', None, 'bs', [], 'total_weight'),
  43. 'utxo_inc': bf(' UTXO',' Incr', '{:>5}', None, 'bs', [], 'utxo_increase'),
  44. 'fee10': bf('10%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 0),
  45. 'fee25': bf('25%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 1),
  46. 'fee50': bf('50%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 2),
  47. 'fee75': bf('75%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 3),
  48. 'fee90': bf('90%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 4),
  49. 'fee_avg': bf('Avg', 'Fee', '{:>3}', None, 'bs', [], 'avgfeerate'),
  50. 'fee_min': bf('Min', 'Fee', '{:>3}', None, 'bs', [], 'minfeerate'),
  51. 'fee_max': bf('Max', 'Fee', '{:>5}', None, 'bs', [], 'maxfeerate'),
  52. 'totalfee': bf('', 'Total Fee','{:>10}', 'totalfee', 'tf', ['bs'], None),
  53. 'outputs': bf('Out-', 'puts', '{:>5}', None, 'bs', [], 'outs'),
  54. 'inputs': bf('In- ', 'puts', '{:>5}', None, 'bs', [], 'ins'),
  55. 'version': bf('', 'Version', '{:8}', None, 'bh', [], 'versionHex'),
  56. 'nTx': bf('', ' nTx ', '{:>5}', None, 'bh', [], 'nTx'),
  57. 'subsidy': bf('Sub-', 'sidy', '{:5}', 'subsidy', 'su', ['bs'], None),
  58. 'difficulty':bf('Diffi-','culty', '{:8}', None, 'di', [], None),
  59. }
  60. dfl_fields = [
  61. 'block',
  62. 'date',
  63. 'interval',
  64. 'subsidy',
  65. 'totalfee',
  66. 'size',
  67. 'weight',
  68. 'fee50',
  69. 'fee25',
  70. 'fee10',
  71. 'fee_avg',
  72. 'fee_min',
  73. 'version',
  74. ]
  75. fixed_fields = [
  76. 'block', # until ≈ 09/01/2028 (block 1000000)
  77. 'hash',
  78. 'date',
  79. 'size', # until ≈ 6x block size increase
  80. 'weight', # until ≈ 2.5x block size increase
  81. 'version',
  82. 'subsidy', # until ≈ 01/04/2028 (increases by 1 digit per halving until 9th halving [max 10 digits])
  83. 'difficulty', # until 1.00e+100 (i.e. never)
  84. ]
  85. # column width adjustment data:
  86. fs_lsqueeze = ['totalfee','inputs','outputs','nTx']
  87. fs_rsqueeze = []
  88. fs_groups = [
  89. ('fee10','fee25','fee50','fee75','fee90','fee_avg','fee_min','fee_max'),
  90. ]
  91. fs_lsqueeze2 = ['interval']
  92. funcs = {
  93. 'df': lambda self,loc: strftime('%Y-%m-%d %X',gmtime(self.t_cur)),
  94. 'td': lambda self,loc: (
  95. '-{:02}:{:02}'.format(abs(self.t_diff)//60,abs(self.t_diff)%60) if self.t_diff < 0 else
  96. ' {:02}:{:02}'.format(self.t_diff//60,self.t_diff%60) ),
  97. 'tf': lambda self,loc: '{:.8f}'.format(loc.bs["totalfee"] * Decimal('0.00000001')),
  98. 'fp': lambda self,loc: loc.bs['feerate_percentiles'],
  99. 'su': lambda self,loc: str(loc.bs['subsidy'] * Decimal('0.00000001')).rstrip('0').rstrip('.'),
  100. 'di': lambda self,loc: '{:.2e}'.format(loc.bh['difficulty']),
  101. }
  102. def __init__(self):
  103. def get_fields():
  104. if opt.fields:
  105. ufields = opt.fields.lstrip('+').split(',')
  106. for field in ufields:
  107. if field not in self.fields:
  108. die(1,f'{field!r}: unrecognized field')
  109. return self.dfl_fields + ufields if opt.fields[0] == '+' else ufields
  110. else:
  111. return self.dfl_fields
  112. def gen_fs(fnames):
  113. for i in range(len(fnames)):
  114. name = fnames[i]
  115. ls = (' ','')[name in self.fs_lsqueeze + self.fs_lsqueeze2]
  116. rs = (' ','')[name in self.fs_rsqueeze]
  117. if i < len(fnames) - 1 and fnames[i+1] in self.fs_lsqueeze2:
  118. rs = ''
  119. if i:
  120. for group in self.fs_groups:
  121. if name in group and fnames[i-1] in group:
  122. ls = ''
  123. break
  124. yield ls + self.fields[name].fs + rs
  125. self.block_list,self.first,self.last = self.parse_block_range(cmd_args)
  126. fnames = get_fields()
  127. self.fvals = list(self.fields[name] for name in fnames)
  128. self.fs = ''.join(gen_fs(fnames)).strip()
  129. self.deps = set(' '.join(v.varname + ' ' + ' '.join(v.deps) for v in self.fvals).split())
  130. self.bs_keys = [(v.bs_key or v.key) for v in self.fvals if v.bs_key or v.varname == 'bs']
  131. self.bs_keys.extend(['total_size','total_weight'])
  132. self.ufuncs = {v.varname:self.funcs[v.varname] for v in self.fvals if v.varname in self.funcs}
  133. if opt.miner_info:
  134. self.fs += ' {}'
  135. self.miner_pats = [re.compile(pat) for pat in (
  136. rb'[\xe3\xe4\xe5][\^/](.*?)\xfa',
  137. rb'([a-zA-Z0-9&. -]+/Mined by [a-zA-Z0-9. ]+)',
  138. rb'\x08/(.*Mined by [a-zA-Z0-9. ]+)',
  139. rb'Mined by ([a-zA-Z0-9. ]+)',
  140. rb'[`]([_a-zA-Z0-9&. #/-]+)[/\xfa]',
  141. rb'[/^]([a-zA-Z0-9&. #/-]{5,})',
  142. rb'[/^]([_a-zA-Z0-9&. #/-]+)/',
  143. )]
  144. else:
  145. self.miner_pats = None
  146. def parse_block_range(self,args):
  147. def conv_blkspec(arg):
  148. if arg == 'cur':
  149. return c.blockcount
  150. elif is_int(arg) and int(arg) >= 0:
  151. return int(arg)
  152. else:
  153. die(1,f'{arg}: invalid block specifier')
  154. def parse_rangespec(arg):
  155. class RangeParser:
  156. def __init__(self,arg):
  157. self.arg = arg
  158. def parse(self,target):
  159. ret = getattr(self,'parse_'+target)()
  160. if debug: print(f'after parse({target}): {self.arg}')
  161. return ret
  162. def parse_from_tip(self):
  163. m = re.match(r'-(\d+)(.*)',self.arg)
  164. if m:
  165. self.arg = m[2]
  166. assert int(m[1]) > 0, 'block count cannot be zero'
  167. return int(m[1])
  168. def parse_range(self):
  169. if self.arg and self.arg[0] == '-':
  170. opts.usage()
  171. else:
  172. m = re.match(r'([^+-]+)(-([^+-]+))*(.*)',self.arg)
  173. if m:
  174. if debug: print(m.groups())
  175. self.arg = m[4]
  176. return (
  177. conv_blkspec(m[1]),
  178. conv_blkspec(m[3]) if m[3] else None
  179. )
  180. return (None,None)
  181. def parse_add(self):
  182. m = re.match(r'\+([0-9*]+)(.*)',self.arg)
  183. if m:
  184. self.arg = m[2]
  185. assert m[1].strip('*') == m[1], f"'+{m[1]}': malformed nBlocks specifier"
  186. assert len(m[1]) <= 30, f"'+{m[1]}': overly long nBlocks specifier"
  187. res = eval(m[1]) # m[1] is only digits plus '*', so safe
  188. assert res > 0, "'+0' not allowed"
  189. assert res <= c.blockcount, f"'+{m[1]}': nBlocks must be less than current chain height"
  190. return res
  191. debug = False
  192. range_spec = namedtuple('parsed_range_spec',['first','last','from_tip','nblocks','step'])
  193. p = RangeParser(arg)
  194. # parsing order must be preserved!
  195. from_tip = p.parse('from_tip')
  196. first,last = p.parse('range')
  197. add1 = p.parse('add')
  198. add2 = p.parse('add')
  199. if p.arg or (from_tip and first):
  200. opts.usage()
  201. if last:
  202. nblocks,step = (None,add1)
  203. if add2:
  204. opts.usage()
  205. else:
  206. nblocks,step = (add1,add2)
  207. if debug: print(range_spec(first,last,from_tip,nblocks,step))
  208. if from_tip:
  209. first = c.blockcount - from_tip
  210. if nblocks:
  211. if not first:
  212. first = c.blockcount - nblocks + 1
  213. last = first + nblocks - 1
  214. if not last:
  215. last = first
  216. if debug: print(range_spec(first,last,from_tip,nblocks,step))
  217. if first > last:
  218. die(1,f'{first}-{last}: invalid block range')
  219. if last > c.blockcount:
  220. die(1,f'Requested block number {last} greater than current chain height')
  221. block_list = list(range(first,last+1,step)) if step else None
  222. return (block_list, first, last)
  223. def parse_blocklist(args):
  224. for arg in args:
  225. if arg != 'cur':
  226. if not is_int(arg):
  227. die(1,f'{arg!r}: invalid block number (not an integer)')
  228. if int(arg) > c.blockcount:
  229. die(1,f'Requested block number {arg} greater than current chain height')
  230. return [conv_blkspec(a) for a in args]
  231. # return (block_list,first,last)
  232. if not args:
  233. return (None,c.blockcount,c.blockcount)
  234. elif len(args) == 1:
  235. return parse_rangespec(args[0])
  236. else:
  237. return (parse_blocklist(args),None,None)
  238. async def run(self):
  239. heights = self.block_list or range(self.first,self.last+1)
  240. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  241. self.hdrs = await c.gathered_call('getblockheader',[(H,) for H in hashes])
  242. async def init(count):
  243. h0 = (
  244. self.hdrs[count] if heights[count] == 0 else
  245. await c.call('getblockheader',await c.call('getblockhash',heights[count]-1))
  246. )
  247. self.t_cur = h0['time']
  248. if count == 0:
  249. self.first_prev_hdr = h0
  250. if not self.block_list:
  251. await init(0)
  252. for n in range(len(heights)):
  253. if self.block_list:
  254. await init(n)
  255. await self.process_block(heights[n],hashes[n],self.hdrs[n])
  256. async def process_block(self,height,H,hdr):
  257. loc = local_vars()
  258. loc.height = height
  259. loc.H = H
  260. loc.bh = hdr
  261. self.t_diff = hdr['time'] - self.t_cur
  262. self.t_cur = hdr['time']
  263. self.total_solve_time += self.t_diff
  264. if 'bs' in self.deps:
  265. loc.bs = genesis_stats if height == 0 else await c.call('getblockstats',H,self.bs_keys)
  266. self.total_bytes += loc.bs['total_size']
  267. self.total_weight += loc.bs['total_weight']
  268. if opt.summary:
  269. return
  270. for varname,func in self.ufuncs.items():
  271. setattr(loc,varname,func(self,loc))
  272. if opt.miner_info:
  273. miner_info = '-' if height == 0 else await self.get_miner_string(H)
  274. def gen():
  275. for v in self.fvals:
  276. if v.key is None:
  277. yield getattr(loc,v.varname)
  278. else:
  279. yield getattr(loc,v.varname)[v.key]
  280. if opt.miner_info:
  281. yield miner_info
  282. Msg(self.fs.format(*gen()))
  283. async def get_miner_string(self,H):
  284. tx0 = (await c.call('getblock',H))['tx'][0]
  285. bd = await c.call('getrawtransaction',tx0,1)
  286. if type(bd) == tuple:
  287. return '---'
  288. else:
  289. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  290. if opt.raw_miner_info:
  291. return repr(cb)
  292. else:
  293. for pat in self.miner_pats:
  294. m = pat.search(cb)
  295. if m:
  296. return ''.join(chr(b) for b in m[1] if 31 < b < 127).strip('^').strip('/').replace('/',' ')
  297. def print_header(self):
  298. hdr1 = [v.hdr1 for v in self.fvals]
  299. hdr2 = [v.hdr2 for v in self.fvals]
  300. if opt.miner_info:
  301. hdr1.append(' ')
  302. hdr2.append('Miner')
  303. if ''.join(hdr1).replace(' ',''):
  304. Msg(self.fs.format(*hdr1))
  305. Msg(self.fs.format(*hdr2))
  306. async def print_range_stats(self):
  307. # These figures don’t include the Genesis Block:
  308. elapsed = self.hdrs[-1]['time'] - self.first_prev_hdr['time']
  309. nblocks = self.hdrs[-1]['height'] - self.first_prev_hdr['height']
  310. Msg('Range: {}-{} ({} blocks [{}])'.format(
  311. self.hdrs[0]['height'],
  312. self.hdrs[-1]['height'],
  313. self.hdrs[-1]['height'] - self.hdrs[0]['height'] + 1, # includes Genesis Block
  314. secs_to_hms(elapsed) ))
  315. if elapsed:
  316. avg_bdi = int(elapsed / nblocks)
  317. if 'bs' in self.deps:
  318. total_blocks = len(self.hdrs)
  319. rate = (self.total_bytes / 10000) / (self.total_solve_time / 36)
  320. Msg_r(fmt(f"""
  321. Avg size: {self.total_bytes//total_blocks} bytes
  322. Avg weight: {self.total_weight//total_blocks} bytes
  323. MB/hr: {rate:0.4f}
  324. """))
  325. Msg(f'Avg BDI: {avg_bdi/60:.2f} min')
  326. async def print_diff_stats(self):
  327. tip = c.blockcount
  328. # Only display stats if user-requested range ends with chain tip
  329. if self.last != tip:
  330. return
  331. cur_diff_disp = 'Cur difficulty: {:.2e}'.format(self.hdrs[-1]['difficulty'])
  332. rel = tip % 2016
  333. if rel:
  334. rel_hdr = await c.call('getblockheader',await c.call('getblockhash',tip-rel))
  335. tip_time = (
  336. self.hdrs[-1]['time'] if self.hdrs[-1]['height'] == tip else
  337. (await c.call('getblockheader',await c.call('getblockhash',tip)))['time']
  338. )
  339. tdiff = tip_time - rel_hdr['time']
  340. if tdiff: # if the 2 timestamps are equal (very unlikely), skip display to avoid div-by-zero error
  341. bdi = tdiff / rel
  342. adj_pct = ((600 / bdi) - 1) * 100
  343. Msg_r(fmt(f"""
  344. Current height: {tip}
  345. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks [{((2016-rel)*bdi)/86400:.2f} days])
  346. BDI (cur period): {bdi/60:.2f} min
  347. {cur_diff_disp}
  348. Est. diff adjust: {adj_pct:+.2f}%
  349. """))
  350. else:
  351. Msg_r(fmt(f"""
  352. Current height: {tip}
  353. {cur_diff_disp}
  354. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks)
  355. """))
  356. opts_data = {
  357. 'sets': [
  358. ('raw_miner_info', True, 'miner_info', True),
  359. ('summary', True, 'raw_miner_info', False),
  360. ('summary', True, 'miner_info', False),
  361. ('hashes', True, 'fields', 'block,hash'),
  362. ('hashes', True, 'no_summary', True),
  363. ],
  364. 'text': {
  365. 'desc': 'Display information about a block or range of blocks',
  366. 'usage': '[opts] blocknum [blocknum ...] | blocknum-blocknum[+step] | [blocknum|-nBlocks]+nBlocks[+step]',
  367. 'usage2': [
  368. '[opts] blocknum [blocknum ...]',
  369. '[opts] blocknum-blocknum[+step]',
  370. '[opts] [blocknum|-nBlocks]+nBlocks[+step]',
  371. ],
  372. 'options': """
  373. -h, --help Print this help message
  374. --, --longhelp Print help message for long options (common options)
  375. -D, --no-diff-stats Omit difficulty adjustment stats from summary
  376. -H, --hashes Display only block numbers and hashes
  377. -m, --miner-info Display miner info in coinbase transaction
  378. -M, --raw-miner-info Display miner info in uninterpreted form
  379. -n, --no-header Don’t print the column header
  380. -o, --fields= Display the specified fields (comma-separated list)
  381. See AVAILABLE FIELDS below. If the first character
  382. is '+', fields are appended to the defaults.
  383. -s, --summary Print the summary only
  384. -S, --no-summary Don’t print the summary
  385. """,
  386. 'notes': """
  387. If no block number is specified, the current block is assumed. The string
  388. 'cur' can be used in place of the current block number.
  389. If the requested range ends at the current chain tip, an estimate of the next
  390. difficulty adjustment is also displayed. The estimate is based on the average
  391. Block Discovery Interval from the beginning of the current 2016-block period.
  392. All fee fields except for 'totalfee' are in satoshis per virtual byte.
  393. AVAILABLE FIELDS: {f}
  394. EXAMPLES:
  395. # Display info for current block:
  396. {p}
  397. # Display info for the Genesis Block:
  398. {p} 0
  399. # Display info for the last 20 blocks:
  400. {p} +20
  401. # Display specified fields for blocks 165-190
  402. {p} -o block,date,size,inputs,nTx 165-190
  403. # Display info for 10 blocks beginning at block 600000:
  404. {p} 600000+10
  405. # Display info for every 5th block of 50-block range beginning at 1000
  406. # blocks from chain tip:
  407. {p} -- -1000+50+5
  408. # Display info for block 152817, adding miner field:
  409. {p} --miner-info 152817
  410. # Display specified fields for listed blocks:
  411. {p} -o block,date,hash 245798 170 624044
  412. # Display every difficulty adjustment from Genesis Block to chain tip:
  413. {p} -o +difficulty 0-cur+2016
  414. # Display roughly a block a day over the last two weeks. Note that
  415. # multiplication is allowed in the nBlocks spec:
  416. {p} +144*14+144
  417. This program requires a txindex-enabled daemon for correct operation.
  418. """.format(
  419. f = fmt_list(BlocksInfo.fields,fmt='bare'),
  420. p = g.prog_name )
  421. }
  422. }
  423. cmd_args = opts.init(opts_data)
  424. # 'getblockstats' RPC raises exception on Genesis Block, so provide our own stats:
  425. genesis_stats = {
  426. 'avgfee': 0,
  427. 'avgfeerate': 0,
  428. 'avgtxsize': 0,
  429. 'feerate_percentiles': [ 0, 0, 0, 0, 0 ],
  430. 'height': 0,
  431. 'ins': 0,
  432. 'maxfee': 0,
  433. 'maxfeerate': 0,
  434. 'maxtxsize': 0,
  435. 'medianfee': 0,
  436. 'mediantxsize': 0,
  437. 'minfee': 0,
  438. 'minfeerate': 0,
  439. 'mintxsize': 0,
  440. 'outs': 1,
  441. 'subsidy': 5000000000,
  442. 'swtotal_size': 0,
  443. 'swtotal_weight': 0,
  444. 'swtxs': 0,
  445. 'total_out': 0,
  446. 'total_size': 0,
  447. 'total_weight': 0,
  448. 'totalfee': 0,
  449. 'txs': 1,
  450. 'utxo_increase': 1,
  451. 'utxo_size_inc': 117
  452. }
  453. async def main():
  454. from mmgen.protocol import init_proto_from_opts
  455. proto = init_proto_from_opts()
  456. from mmgen.rpc import rpc_init
  457. global c
  458. c = await rpc_init(proto)
  459. m = BlocksInfo()
  460. if not (opt.summary or opt.no_header):
  461. m.print_header()
  462. await m.run()
  463. if m.last and not opt.no_summary:
  464. Msg('')
  465. await m.print_range_stats()
  466. if not opt.no_diff_stats:
  467. Msg('')
  468. await m.print_diff_stats()
  469. run_session(main())