BlocksInfo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. mmgen.node_tools.BlocksInfo: 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 decimal import Decimal
  25. from mmgen.common import *
  26. class BlocksInfo:
  27. total_bytes = 0
  28. total_weight = 0
  29. total_solve_time = 0
  30. bf = namedtuple('block_info_fields',['hdr1','hdr2','fs','bs_key','varname','deps','key'])
  31. # bs=getblockstats(), bh=getblockheader()
  32. # If 'bs_key' is set, it's included in self.bs_keys instead of 'key'
  33. fields = {
  34. 'block': bf('', 'Block', '{:<6}', None, 'height',[], None),
  35. 'hash': bf('', 'Hash', '{:<64}', None, 'H', [], None),
  36. 'date': bf('', 'Date', '{:<19}', None, 'df', [], None),
  37. 'interval': bf('Solve','Time ', '{:>8}', None, 'td', [], None),
  38. 'subsidy': bf('Sub-', 'sidy', '{:<5}', 'subsidy', 'su', ['bs'], None),
  39. 'totalfee': bf('', 'Total Fee','{:>10}', 'totalfee', 'tf', ['bs'], None),
  40. 'size': bf('', 'Size', '{:>7}', None, 'bs', [], 'total_size'),
  41. 'weight': bf('', 'Weight', '{:>7}', None, 'bs', [], 'total_weight'),
  42. 'fee90': bf('90%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 4),
  43. 'fee75': bf('75%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 3),
  44. 'fee50': bf('50%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 2),
  45. 'fee25': bf('25%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 1),
  46. 'fee10': bf('10%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'], 0),
  47. 'fee_max': bf('Max', 'Fee', '{:>5}', None, 'bs', [], 'maxfeerate'),
  48. 'fee_avg': bf('Avg', 'Fee', '{:>3}', None, 'bs', [], 'avgfeerate'),
  49. 'fee_min': bf('Min', 'Fee', '{:>3}', None, 'bs', [], 'minfeerate'),
  50. 'nTx': bf('', ' nTx ', '{:>5}', None, 'bh', [], 'nTx'),
  51. 'inputs': bf('In- ', 'puts', '{:>5}', None, 'bs', [], 'ins'),
  52. 'outputs': bf('Out-', 'puts', '{:>5}', None, 'bs', [], 'outs'),
  53. 'utxo_inc': bf(' UTXO',' Incr', '{:>5}', None, 'bs', [], 'utxo_increase'),
  54. 'version': bf('', 'Version', '{:<8}', None, 'bh', [], 'versionHex'),
  55. 'difficulty':bf('Diffi-','culty', '{:<8}', None, 'di', [], None),
  56. }
  57. dfl_fields = [
  58. 'block',
  59. 'date',
  60. 'interval',
  61. 'subsidy',
  62. 'totalfee',
  63. 'size',
  64. 'weight',
  65. 'fee50',
  66. 'fee25',
  67. 'fee10',
  68. 'fee_avg',
  69. 'fee_min',
  70. 'version',
  71. ]
  72. fixed_fields = [
  73. 'block', # until ≈ 09/01/2028 (block 1000000)
  74. 'hash',
  75. 'date',
  76. 'size', # until ≈ 6x block size increase
  77. 'weight', # until ≈ 2.5x block size increase
  78. 'version',
  79. 'subsidy', # until ≈ 01/04/2028 (increases by 1 digit per halving until 9th halving [max 10 digits])
  80. 'difficulty', # until 1.00e+100 (i.e. never)
  81. ]
  82. # column width adjustment data:
  83. fs_lsqueeze = ['totalfee','inputs','outputs','nTx']
  84. fs_rsqueeze = []
  85. fs_groups = [
  86. ('fee10','fee25','fee50','fee75','fee90','fee_avg','fee_min','fee_max'),
  87. ]
  88. fs_lsqueeze2 = ['interval']
  89. all_stats = ['range','diff']
  90. dfl_stats = ['range','diff']
  91. funcs = {
  92. 'df': lambda self,loc: strftime('%Y-%m-%d %X',gmtime(self.t_cur)),
  93. 'td': lambda self,loc: (
  94. '-{:02}:{:02}'.format(abs(self.t_diff)//60,abs(self.t_diff)%60) if self.t_diff < 0 else
  95. ' {:02}:{:02}'.format(self.t_diff//60,self.t_diff%60) ),
  96. 'tf': lambda self,loc: '{:.8f}'.format(loc.bs["totalfee"] * Decimal('0.00000001')),
  97. 'fp': lambda self,loc: loc.bs['feerate_percentiles'],
  98. 'su': lambda self,loc: str(loc.bs['subsidy'] * Decimal('0.00000001')).rstrip('0').rstrip('.'),
  99. 'di': lambda self,loc: '{:.2e}'.format(loc.bh['difficulty']),
  100. }
  101. range_data = namedtuple('parsed_range_data',['first','last','from_tip','nblocks','step'])
  102. t_fmt = lambda self,t: f'{t/86400:.2f} days' if t > 172800 else f'{t/3600:.2f} hrs'
  103. def __init__(self,cmd_args,opt,rpc):
  104. def parse_cslist(uarg,full_set,dfl_set,desc):
  105. usr_set = uarg.lstrip('+').split(',')
  106. for e in usr_set:
  107. if e not in full_set:
  108. die(1,f'{e!r}: unrecognized {desc}')
  109. res = dfl_set + usr_set if uarg[0] == '+' else usr_set
  110. # display elements in order:
  111. return [e for e in full_set if e in res]
  112. def get_fields():
  113. return parse_cslist(opt.fields,self.fields,self.dfl_fields,'field')
  114. def get_stats():
  115. arg = opt.stats.lower()
  116. return (
  117. self.all_stats if arg == 'all' else [] if arg == 'none' else
  118. parse_cslist(arg,self.all_stats,self.dfl_stats,'stat')
  119. )
  120. def gen_fs(fnames):
  121. for i in range(len(fnames)):
  122. name = fnames[i]
  123. ls = (' ','')[name in self.fs_lsqueeze + self.fs_lsqueeze2]
  124. rs = (' ','')[name in self.fs_rsqueeze]
  125. if i < len(fnames) - 1 and fnames[i+1] in self.fs_lsqueeze2:
  126. rs = ''
  127. if i:
  128. for group in self.fs_groups:
  129. if name in group and fnames[i-1] in group:
  130. ls = ''
  131. break
  132. yield ls + self.fields[name].fs + rs
  133. def parse_cmd_args():
  134. if not cmd_args:
  135. return (None,self.tip,self.tip)
  136. elif len(cmd_args) == 1:
  137. r = self.parse_rangespec(cmd_args[0])
  138. return (
  139. list(range(r.first,r.last+1,r.step)) if r.step else None,
  140. r.first,
  141. r.last
  142. )
  143. else:
  144. return ([self.conv_blkspec(a) for a in cmd_args],None,None)
  145. self.rpc = rpc
  146. self.opt = opt
  147. self.tip = rpc.blockcount
  148. self.block_list,self.first,self.last = parse_cmd_args()
  149. fnames = get_fields() if opt.fields else self.dfl_fields
  150. self.fvals = list(self.fields[name] for name in fnames)
  151. self.fs = ''.join(gen_fs(fnames)).strip()
  152. self.deps = set(' '.join(v.varname + ' ' + ' '.join(v.deps) for v in self.fvals).split())
  153. self.bs_keys = [(v.bs_key or v.key) for v in self.fvals if v.bs_key or v.varname == 'bs']
  154. self.bs_keys.extend(['total_size','total_weight'])
  155. self.ufuncs = {v.varname:self.funcs[v.varname] for v in self.fvals if v.varname in self.funcs}
  156. if opt.miner_info:
  157. fnames.append('miner')
  158. self.fs += ' {:<5}'
  159. self.miner_pats = [re.compile(pat) for pat in (
  160. rb'`/([_a-zA-Z0-9&. #/-]+)/',
  161. rb'[\xe3\xe4\xe5][\^/](.*?)\xfa',
  162. rb'([a-zA-Z0-9&. -]+/Mined by [a-zA-Z0-9. ]+)',
  163. rb'\x08/(.*Mined by [a-zA-Z0-9. ]+)',
  164. rb'Mined by ([a-zA-Z0-9. ]+)',
  165. rb'[`]([_a-zA-Z0-9&. #/-]+)[/\xfa]',
  166. rb'[/^]([a-zA-Z0-9&. #/-]{5,})',
  167. rb'[/^]([_a-zA-Z0-9&. #/-]+)/',
  168. )]
  169. else:
  170. self.miner_pats = None
  171. self.block_data = namedtuple('block_data',fnames)
  172. self.stats = get_stats() if opt.stats else self.dfl_stats
  173. def conv_blkspec(self,arg):
  174. if arg == 'cur':
  175. return self.tip
  176. elif is_int(arg):
  177. if int(arg) < 0:
  178. die(1,f'{arg}: block number must be non-negative')
  179. elif int(arg) > self.tip:
  180. die(1,f'{arg}: requested block height greater than current chain tip!')
  181. else:
  182. return int(arg)
  183. else:
  184. die(1,f'{arg}: invalid block specifier')
  185. def check_nblocks(self,arg):
  186. if arg <= 0:
  187. die(1,'nBlocks must be a positive integer')
  188. elif arg > self.tip:
  189. die(1, f"'{arg}': nBlocks must be less than current chain height")
  190. return arg
  191. def parse_rangespec(self,arg):
  192. class RangeParser:
  193. debug = False
  194. def __init__(rp,arg):
  195. rp.arg = rp.orig_arg = arg
  196. def parse(rp,target):
  197. ret = getattr(rp,'parse_'+target)()
  198. if rp.debug: msg(f'arg after parse({target}): {rp.arg}')
  199. return ret
  200. def finalize(rp):
  201. if rp.arg:
  202. die(1,f'{rp.orig_arg!r}: invalid range specifier')
  203. def parse_from_tip(rp):
  204. m = re.match(r'-([0-9]+)(.*)',rp.arg)
  205. if m:
  206. res,rp.arg = (m[1],m[2])
  207. return self.check_nblocks(int(res))
  208. def parse_abs_range(rp):
  209. m = re.match(r'([^+-]+)(-([^+-]+)){0,1}(.*)',rp.arg)
  210. if m:
  211. if rp.debug: msg(f'abs_range parse: first={m[1]}, last={m[3]}')
  212. rp.arg = m[4]
  213. return (
  214. self.conv_blkspec(m[1]),
  215. self.conv_blkspec(m[3]) if m[3] else None
  216. )
  217. return (None,None)
  218. def parse_add(rp):
  219. m = re.match(r'\+([0-9*]+)(.*)',rp.arg)
  220. if m:
  221. res,rp.arg = (m[1],m[2])
  222. if res.strip('*') != res:
  223. die(1,f"'+{res}': malformed nBlocks specifier")
  224. if len(res) > 30:
  225. die(1,f"'+{res}': overly long nBlocks specifier")
  226. return self.check_nblocks(eval(res)) # res is only digits plus '*', so eval safe
  227. p = RangeParser(arg)
  228. from_tip = p.parse('from_tip')
  229. first,last = (self.tip-from_tip,None) if from_tip else p.parse('abs_range')
  230. add1 = p.parse('add')
  231. add2 = p.parse('add')
  232. p.finalize()
  233. if add2 and last is not None:
  234. die(1,f'{arg!r}: invalid range specifier')
  235. nblocks,step = (add1,add2) if last is None else (None,add1)
  236. if p.debug: msg(repr(self.range_data(first,last,from_tip,nblocks,step)))
  237. if nblocks:
  238. if first == None:
  239. first = self.tip - nblocks + 1
  240. last = first + nblocks - 1
  241. first = self.conv_blkspec(first)
  242. last = self.conv_blkspec(last or first)
  243. if p.debug: msg(repr(self.range_data(first,last,from_tip,nblocks,step)))
  244. if first > last:
  245. die(1,f'{first}-{last}: invalid block range')
  246. return self.range_data(first,last,from_tip,nblocks,step)
  247. async def run(self):
  248. c = self.rpc
  249. heights = self.block_list or range(self.first,self.last+1)
  250. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  251. self.hdrs = await c.gathered_call('getblockheader',[(H,) for H in hashes])
  252. async def init(count):
  253. h0 = (
  254. self.hdrs[count] if heights[count] == 0 else
  255. await c.call('getblockheader',await c.call('getblockhash',heights[count]-1))
  256. )
  257. self.t_cur = h0['time']
  258. if count == 0:
  259. self.first_prev_hdr = h0
  260. if not self.block_list:
  261. await init(0)
  262. for n in range(len(heights)):
  263. if self.block_list:
  264. await init(n)
  265. ret = await self.process_block(heights[n],hashes[n],self.hdrs[n])
  266. if opt.stats_only:
  267. continue
  268. else:
  269. Msg(self.fs.format(*ret))
  270. async def process_block(self,height,H,hdr):
  271. class local_vars: pass
  272. loc = local_vars()
  273. loc.height = height
  274. loc.H = H
  275. loc.bh = hdr
  276. self.t_diff = hdr['time'] - self.t_cur
  277. self.t_cur = hdr['time']
  278. self.total_solve_time += self.t_diff
  279. if 'bs' in self.deps:
  280. loc.bs = self.genesis_stats if height == 0 else await self.rpc.call('getblockstats',H,self.bs_keys)
  281. self.total_bytes += loc.bs['total_size']
  282. self.total_weight += loc.bs['total_weight']
  283. for varname,func in self.ufuncs.items():
  284. setattr(loc,varname,func(self,loc))
  285. if self.opt.miner_info:
  286. miner_info = '-' if height == 0 else await self.get_miner_string(H)
  287. def gen():
  288. for v in self.fvals:
  289. if v.key is None:
  290. yield getattr(loc,v.varname)
  291. else:
  292. yield getattr(loc,v.varname)[v.key]
  293. if self.opt.miner_info:
  294. yield miner_info
  295. return self.block_data(*gen())
  296. async def get_miner_string(self,H):
  297. tx0 = (await self.rpc.call('getblock',H))['tx'][0]
  298. bd = await self.rpc.call('getrawtransaction',tx0,1)
  299. if type(bd) == tuple:
  300. return '---'
  301. else:
  302. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  303. if self.opt.raw_miner_info:
  304. return repr(cb)
  305. else:
  306. for pat in self.miner_pats:
  307. m = pat.search(cb)
  308. if m:
  309. return ''.join(chr(b) for b in m[1] if 31 < b < 127).strip('^').strip('/').replace('/',' ')
  310. return ''
  311. def print_header(self):
  312. hdr1 = [v.hdr1 for v in self.fvals]
  313. hdr2 = [v.hdr2 for v in self.fvals]
  314. if self.opt.miner_info:
  315. hdr1.append(' ')
  316. hdr2.append('Miner')
  317. if ''.join(hdr1).replace(' ',''):
  318. Msg(self.fs.format(*hdr1))
  319. Msg(self.fs.format(*hdr2))
  320. def print_stats(self,name):
  321. return getattr(self,f'print_{name}_stats')()
  322. async def print_range_stats(self):
  323. # These figures don’t include the Genesis Block:
  324. elapsed = self.hdrs[-1]['time'] - self.first_prev_hdr['time']
  325. nblocks = self.hdrs[-1]['height'] - self.first_prev_hdr['height']
  326. Msg('Range: {}-{} ({} blocks [{}])'.format(
  327. self.hdrs[0]['height'],
  328. self.hdrs[-1]['height'],
  329. self.hdrs[-1]['height'] - self.hdrs[0]['height'] + 1, # includes Genesis Block
  330. self.t_fmt(elapsed) ))
  331. if elapsed:
  332. avg_bdi = int(elapsed / nblocks)
  333. if 'bs' in self.deps:
  334. total_blocks = len(self.hdrs)
  335. rate = (self.total_bytes / 10000) / (self.total_solve_time / 36)
  336. Msg_r(fmt(f"""
  337. Avg size: {self.total_bytes//total_blocks} bytes
  338. Avg weight: {self.total_weight//total_blocks} bytes
  339. MB/hr: {rate:0.4f}
  340. """))
  341. Msg(f'Avg BDI: {avg_bdi/60:.2f} min')
  342. async def print_diff_stats(self):
  343. c = self.rpc
  344. rel = self.tip % 2016
  345. tip_hdr = (
  346. self.hdrs[-1] if self.hdrs[-1]['height'] == self.tip else
  347. await c.call('getblockheader',await c.call('getblockhash',self.tip))
  348. )
  349. bdi_avg_blks = 432 # ≈3 days
  350. bdi_avg_hdr = await c.call('getblockheader',await c.call('getblockhash',self.tip-bdi_avg_blks))
  351. bdi_avg = ( tip_hdr['time'] - bdi_avg_hdr['time'] ) / bdi_avg_blks
  352. if rel > bdi_avg_blks:
  353. rel_hdr = await c.call('getblockheader',await c.call('getblockhash',self.tip-rel))
  354. bdi = ( tip_hdr['time'] - rel_hdr['time'] ) / rel
  355. else:
  356. bdi_adj = float(tip_hdr['difficulty'] / bdi_avg_hdr['difficulty'])
  357. bdi = bdi_avg * ( (bdi_adj * (bdi_avg_blks-rel)) + rel ) / bdi_avg_blks
  358. rem = 2016 - rel
  359. Msg_r(fmt(f"""
  360. Current height: {self.tip}
  361. Next diff adjust: {self.tip+rem} (in {rem} block{suf(rem)} [{self.t_fmt((rem)*bdi_avg)}])
  362. BDI (cur period): {bdi/60:.2f} min
  363. Cur difficulty: {tip_hdr['difficulty']:.2e}
  364. Est. diff adjust: {((600 / bdi) - 1) * 100:+.2f}%
  365. """))
  366. # 'getblockstats' RPC raises exception on Genesis Block, so provide our own stats:
  367. genesis_stats = {
  368. 'avgfee': 0,
  369. 'avgfeerate': 0,
  370. 'avgtxsize': 0,
  371. 'feerate_percentiles': [ 0, 0, 0, 0, 0 ],
  372. 'height': 0,
  373. 'ins': 0,
  374. 'maxfee': 0,
  375. 'maxfeerate': 0,
  376. 'maxtxsize': 0,
  377. 'medianfee': 0,
  378. 'mediantxsize': 0,
  379. 'minfee': 0,
  380. 'minfeerate': 0,
  381. 'mintxsize': 0,
  382. 'outs': 1,
  383. 'subsidy': 5000000000,
  384. 'swtotal_size': 0,
  385. 'swtotal_weight': 0,
  386. 'swtxs': 0,
  387. 'total_out': 0,
  388. 'total_size': 0,
  389. 'total_weight': 0,
  390. 'totalfee': 0,
  391. 'txs': 1,
  392. 'utxo_increase': 1,
  393. 'utxo_size_inc': 117
  394. }