mmnode-blocks-info 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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):
  151. if int(arg) < 0:
  152. die(1,f'{arg}: block number must be non-negative')
  153. elif int(arg) > c.blockcount:
  154. die(1,f'{arg}: requested block greater than current chain tip!')
  155. else:
  156. return int(arg)
  157. else:
  158. die(1,f'{arg}: invalid block specifier')
  159. def parse_rangespec(arg):
  160. class RangeParser:
  161. def __init__(self,arg):
  162. self.arg = arg
  163. def parse(self,target):
  164. ret = getattr(self,'parse_'+target)()
  165. if debug: print(f'after parse({target}): {self.arg}')
  166. return ret
  167. def parse_from_tip(self):
  168. m = re.match(r'-([0-9]+)(.*)',self.arg)
  169. if m:
  170. self.arg = m[2]
  171. res = int(m[1])
  172. assert res > 0, 'block count cannot be zero'
  173. assert res <= c.blockcount, f"'+{m[1]}': block count must be less than current chain height"
  174. return res
  175. def parse_range(self):
  176. m = re.match(r'([^+-]+)(-([^+-]+))*(.*)',self.arg)
  177. if m:
  178. if debug: print(m.groups())
  179. self.arg = m[4]
  180. return (
  181. conv_blkspec(m[1]),
  182. conv_blkspec(m[3]) if m[3] else None
  183. )
  184. return (None,None)
  185. def parse_add(self):
  186. m = re.match(r'\+([0-9*]+)(.*)',self.arg)
  187. if m:
  188. self.arg = m[2]
  189. assert m[1].strip('*') == m[1], f"'+{m[1]}': malformed nBlocks specifier"
  190. assert len(m[1]) <= 30, f"'+{m[1]}': overly long nBlocks specifier"
  191. res = eval(m[1]) # m[1] is only digits plus '*', so safe
  192. assert res > 0, "'+0' not allowed"
  193. assert res <= c.blockcount, f"'+{m[1]}': nBlocks must be less than current chain height"
  194. return res
  195. debug = False
  196. range_spec = namedtuple('parsed_range_spec',['first','last','from_tip','nblocks','step'])
  197. p = RangeParser(arg)
  198. # parsing order must be preserved!
  199. from_tip = p.parse('from_tip')
  200. if p.arg.startswith('-'):
  201. opts.usage()
  202. first,last = p.parse('range')
  203. add1 = p.parse('add')
  204. add2 = p.parse('add')
  205. if p.arg or (from_tip and first):
  206. opts.usage()
  207. if last:
  208. nblocks,step = (None,add1)
  209. if add2:
  210. opts.usage()
  211. else:
  212. nblocks,step = (add1,add2)
  213. if debug: print(range_spec(first,last,from_tip,nblocks,step))
  214. if from_tip:
  215. first = c.blockcount - from_tip
  216. if nblocks:
  217. if not first:
  218. first = c.blockcount - nblocks + 1
  219. last = first + nblocks - 1
  220. if not last:
  221. last = first
  222. if debug: print(range_spec(first,last,from_tip,nblocks,step))
  223. first = conv_blkspec(first)
  224. last = conv_blkspec(last)
  225. if first > last:
  226. die(1,f'{first}-{last}: invalid block range')
  227. block_list = list(range(first,last+1,step)) if step else None
  228. return (block_list, first, last)
  229. # return (block_list,first,last)
  230. if not args:
  231. return (None,c.blockcount,c.blockcount)
  232. elif len(args) == 1:
  233. return parse_rangespec(args[0])
  234. else:
  235. return ([conv_blkspec(a) for a in args],None,None)
  236. async def run(self):
  237. heights = self.block_list or range(self.first,self.last+1)
  238. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  239. self.hdrs = await c.gathered_call('getblockheader',[(H,) for H in hashes])
  240. async def init(count):
  241. h0 = (
  242. self.hdrs[count] if heights[count] == 0 else
  243. await c.call('getblockheader',await c.call('getblockhash',heights[count]-1))
  244. )
  245. self.t_cur = h0['time']
  246. if count == 0:
  247. self.first_prev_hdr = h0
  248. if not self.block_list:
  249. await init(0)
  250. for n in range(len(heights)):
  251. if self.block_list:
  252. await init(n)
  253. await self.process_block(heights[n],hashes[n],self.hdrs[n])
  254. async def process_block(self,height,H,hdr):
  255. loc = local_vars()
  256. loc.height = height
  257. loc.H = H
  258. loc.bh = hdr
  259. self.t_diff = hdr['time'] - self.t_cur
  260. self.t_cur = hdr['time']
  261. self.total_solve_time += self.t_diff
  262. if 'bs' in self.deps:
  263. loc.bs = genesis_stats if height == 0 else await c.call('getblockstats',H,self.bs_keys)
  264. self.total_bytes += loc.bs['total_size']
  265. self.total_weight += loc.bs['total_weight']
  266. if opt.summary:
  267. return
  268. for varname,func in self.ufuncs.items():
  269. setattr(loc,varname,func(self,loc))
  270. if opt.miner_info:
  271. miner_info = '-' if height == 0 else await self.get_miner_string(H)
  272. def gen():
  273. for v in self.fvals:
  274. if v.key is None:
  275. yield getattr(loc,v.varname)
  276. else:
  277. yield getattr(loc,v.varname)[v.key]
  278. if opt.miner_info:
  279. yield miner_info
  280. Msg(self.fs.format(*gen()))
  281. async def get_miner_string(self,H):
  282. tx0 = (await c.call('getblock',H))['tx'][0]
  283. bd = await c.call('getrawtransaction',tx0,1)
  284. if type(bd) == tuple:
  285. return '---'
  286. else:
  287. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  288. if opt.raw_miner_info:
  289. return repr(cb)
  290. else:
  291. for pat in self.miner_pats:
  292. m = pat.search(cb)
  293. if m:
  294. return ''.join(chr(b) for b in m[1] if 31 < b < 127).strip('^').strip('/').replace('/',' ')
  295. def print_header(self):
  296. hdr1 = [v.hdr1 for v in self.fvals]
  297. hdr2 = [v.hdr2 for v in self.fvals]
  298. if opt.miner_info:
  299. hdr1.append(' ')
  300. hdr2.append('Miner')
  301. if ''.join(hdr1).replace(' ',''):
  302. Msg(self.fs.format(*hdr1))
  303. Msg(self.fs.format(*hdr2))
  304. async def print_range_stats(self):
  305. # These figures don’t include the Genesis Block:
  306. elapsed = self.hdrs[-1]['time'] - self.first_prev_hdr['time']
  307. nblocks = self.hdrs[-1]['height'] - self.first_prev_hdr['height']
  308. Msg('Range: {}-{} ({} blocks [{}])'.format(
  309. self.hdrs[0]['height'],
  310. self.hdrs[-1]['height'],
  311. self.hdrs[-1]['height'] - self.hdrs[0]['height'] + 1, # includes Genesis Block
  312. secs_to_hms(elapsed) ))
  313. if elapsed:
  314. avg_bdi = int(elapsed / nblocks)
  315. if 'bs' in self.deps:
  316. total_blocks = len(self.hdrs)
  317. rate = (self.total_bytes / 10000) / (self.total_solve_time / 36)
  318. Msg_r(fmt(f"""
  319. Avg size: {self.total_bytes//total_blocks} bytes
  320. Avg weight: {self.total_weight//total_blocks} bytes
  321. MB/hr: {rate:0.4f}
  322. """))
  323. Msg(f'Avg BDI: {avg_bdi/60:.2f} min')
  324. async def print_diff_stats(self):
  325. tip = c.blockcount
  326. # Only display stats if user-requested range ends with chain tip
  327. if self.last != tip:
  328. return
  329. cur_diff_disp = 'Cur difficulty: {:.2e}'.format(self.hdrs[-1]['difficulty'])
  330. rel = tip % 2016
  331. if rel:
  332. rel_hdr = await c.call('getblockheader',await c.call('getblockhash',tip-rel))
  333. tip_time = (
  334. self.hdrs[-1]['time'] if self.hdrs[-1]['height'] == tip else
  335. (await c.call('getblockheader',await c.call('getblockhash',tip)))['time']
  336. )
  337. tdiff = tip_time - rel_hdr['time']
  338. if tdiff: # if the 2 timestamps are equal (very unlikely), skip display to avoid div-by-zero error
  339. bdi = tdiff / rel
  340. adj_pct = ((600 / bdi) - 1) * 100
  341. Msg_r(fmt(f"""
  342. Current height: {tip}
  343. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks [{((2016-rel)*bdi)/86400:.2f} days])
  344. BDI (cur period): {bdi/60:.2f} min
  345. {cur_diff_disp}
  346. Est. diff adjust: {adj_pct:+.2f}%
  347. """))
  348. else:
  349. Msg_r(fmt(f"""
  350. Current height: {tip}
  351. {cur_diff_disp}
  352. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks)
  353. """))
  354. opts_data = {
  355. 'sets': [
  356. ('raw_miner_info', True, 'miner_info', True),
  357. ('summary', True, 'raw_miner_info', False),
  358. ('summary', True, 'miner_info', False),
  359. ('hashes', True, 'fields', 'block,hash'),
  360. ('hashes', True, 'no_summary', True),
  361. ],
  362. 'text': {
  363. 'desc': 'Display information about a block or range of blocks',
  364. 'usage': '[opts] blocknum [blocknum ...] | blocknum-blocknum[+step] | [blocknum|-nBlocks]+nBlocks[+step]',
  365. 'usage2': [
  366. '[opts] blocknum [blocknum ...]',
  367. '[opts] blocknum-blocknum[+step]',
  368. '[opts] [blocknum|-nBlocks]+nBlocks[+step]',
  369. ],
  370. 'options': """
  371. -h, --help Print this help message
  372. --, --longhelp Print help message for long options (common options)
  373. -D, --no-diff-stats Omit difficulty adjustment stats from summary
  374. -H, --hashes Display only block numbers and hashes
  375. -m, --miner-info Display miner info in coinbase transaction
  376. -M, --raw-miner-info Display miner info in uninterpreted form
  377. -n, --no-header Don’t print the column header
  378. -o, --fields= Display the specified fields (comma-separated list)
  379. See AVAILABLE FIELDS below. If the first character
  380. is '+', fields are appended to the defaults.
  381. -s, --summary Print the summary only
  382. -S, --no-summary Don’t print the summary
  383. """,
  384. 'notes': """
  385. If no block number is specified, the current block is assumed. The string
  386. 'cur' can be used in place of the current block number.
  387. If the requested range ends at the current chain tip, an estimate of the next
  388. difficulty adjustment is also displayed. The estimate is based on the average
  389. Block Discovery Interval from the beginning of the current 2016-block period.
  390. All fee fields except for 'totalfee' are in satoshis per virtual byte.
  391. AVAILABLE FIELDS: {f}
  392. EXAMPLES:
  393. # Display info for current block:
  394. {p}
  395. # Display info for the Genesis Block:
  396. {p} 0
  397. # Display info for the last 20 blocks:
  398. {p} +20
  399. # Display specified fields for blocks 165-190
  400. {p} -o block,date,size,inputs,nTx 165-190
  401. # Display info for 10 blocks beginning at block 600000:
  402. {p} 600000+10
  403. # Display info for every 5th block of 50-block range beginning at 1000
  404. # blocks from chain tip:
  405. {p} -- -1000+50+5
  406. # Display info for block 152817, adding miner field:
  407. {p} --miner-info 152817
  408. # Display specified fields for listed blocks:
  409. {p} -o block,date,hash 245798 170 624044
  410. # Display every difficulty adjustment from Genesis Block to chain tip:
  411. {p} -o +difficulty 0-cur+2016
  412. # Display roughly a block a day over the last two weeks. Note that
  413. # multiplication is allowed in the nBlocks spec:
  414. {p} +144*14+144
  415. This program requires a txindex-enabled daemon for correct operation.
  416. """.format(
  417. f = fmt_list(BlocksInfo.fields,fmt='bare'),
  418. p = g.prog_name )
  419. }
  420. }
  421. cmd_args = opts.init(opts_data)
  422. # 'getblockstats' RPC raises exception on Genesis Block, so provide our own stats:
  423. genesis_stats = {
  424. 'avgfee': 0,
  425. 'avgfeerate': 0,
  426. 'avgtxsize': 0,
  427. 'feerate_percentiles': [ 0, 0, 0, 0, 0 ],
  428. 'height': 0,
  429. 'ins': 0,
  430. 'maxfee': 0,
  431. 'maxfeerate': 0,
  432. 'maxtxsize': 0,
  433. 'medianfee': 0,
  434. 'mediantxsize': 0,
  435. 'minfee': 0,
  436. 'minfeerate': 0,
  437. 'mintxsize': 0,
  438. 'outs': 1,
  439. 'subsidy': 5000000000,
  440. 'swtotal_size': 0,
  441. 'swtotal_weight': 0,
  442. 'swtxs': 0,
  443. 'total_out': 0,
  444. 'total_size': 0,
  445. 'total_weight': 0,
  446. 'totalfee': 0,
  447. 'txs': 1,
  448. 'utxo_increase': 1,
  449. 'utxo_size_inc': 117
  450. }
  451. async def main():
  452. from mmgen.protocol import init_proto_from_opts
  453. proto = init_proto_from_opts()
  454. from mmgen.rpc import rpc_init
  455. global c
  456. c = await rpc_init(proto)
  457. m = BlocksInfo()
  458. if not (opt.summary or opt.no_header):
  459. m.print_header()
  460. await m.run()
  461. if m.last and not opt.no_summary:
  462. Msg('')
  463. await m.print_range_stats()
  464. if not opt.no_diff_stats:
  465. Msg('')
  466. await m.print_diff_stats()
  467. run_session(main())