BlocksInfo.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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,json
  22. from collections import namedtuple
  23. from time import strftime,gmtime
  24. from decimal import Decimal
  25. from mmgen.common import *
  26. from mmgen.rpc import json_encoder
  27. class BlocksInfo:
  28. total_bytes = 0
  29. total_weight = 0
  30. total_solve_time = 0
  31. header_printed = False
  32. bf = namedtuple('block_info_fields',['fmt_func','src','fs','hdr1','hdr2','key1','key2'])
  33. # bh=getblockheader, bs=getblockstats, lo=local
  34. fields = {
  35. 'block': bf( None, 'bh', '{:<6}', '', 'Block', 'height', None ),
  36. 'hash': bf( None, 'bh', '{:<64}', '', 'Hash', 'hash', None ),
  37. 'date': bf( 'da', 'bh', '{:<19}', '', 'Date', 'time', None ),
  38. 'interval': bf( 'td', 'lo', '{:>8}', 'Solve', 'Time ', 'interval', None ),
  39. 'subsidy': bf( 'su', 'bs', '{:<5}', 'Sub-', 'sidy', 'subsidy', None ),
  40. 'totalfee': bf( 'tf', 'bs', '{:>10}', '', 'Total Fee', 'totalfee', None ),
  41. 'size': bf( None, 'bs', '{:>7}', '', 'Size', 'total_size', None ),
  42. 'weight': bf( None, 'bs', '{:>7}', '', 'Weight', 'total_weight', None ),
  43. 'fee90': bf( None, 'bs', '{:>3}', '90%', 'Fee', 'feerate_percentiles', 4 ),
  44. 'fee75': bf( None, 'bs', '{:>3}', '75%', 'Fee', 'feerate_percentiles', 3 ),
  45. 'fee50': bf( None, 'bs', '{:>3}', '50%', 'Fee', 'feerate_percentiles', 2 ),
  46. 'fee25': bf( None, 'bs', '{:>3}', '25%', 'Fee', 'feerate_percentiles', 1 ),
  47. 'fee10': bf( None, 'bs', '{:>3}', '10%', 'Fee', 'feerate_percentiles', 0 ),
  48. 'fee_max': bf( None, 'bs', '{:>5}', 'Max', 'Fee', 'maxfeerate', None ),
  49. 'fee_avg': bf( None, 'bs', '{:>3}', 'Avg', 'Fee', 'avgfeerate', None ),
  50. 'fee_min': bf( None, 'bs', '{:>3}', 'Min', 'Fee', 'minfeerate', None ),
  51. 'nTx': bf( None, 'bh', '{:>5}', '', ' nTx ', 'nTx', None ),
  52. 'inputs': bf( None, 'bs', '{:>5}', 'In- ', 'puts', 'ins', None ),
  53. 'outputs': bf( None, 'bs', '{:>5}', 'Out-', 'puts', 'outs', None ),
  54. 'utxo_inc': bf( None, 'bs', '{:>6}', ' UTXO', ' Incr', 'utxo_increase', None ),
  55. 'version': bf( None, 'bh', '{:<8}', '', 'Version', 'versionHex', None ),
  56. 'difficulty': bf( 'di', 'bh', '{:<8}', 'Diffi-','culty', 'difficulty', None ),
  57. 'miner': bf( None, 'lo', '{:<5}', '', 'Miner', 'miner', None ),
  58. }
  59. dfl_fields = (
  60. 'block',
  61. 'date',
  62. 'interval',
  63. 'subsidy',
  64. 'totalfee',
  65. 'size',
  66. 'weight',
  67. 'fee50',
  68. 'fee25',
  69. 'fee10',
  70. 'fee_avg',
  71. 'fee_min',
  72. 'version',
  73. )
  74. fixed_fields = (
  75. 'block', # until ≈ 09/01/2028 (block 1000000)
  76. 'hash',
  77. 'date',
  78. 'size', # until ≈ 6x block size increase
  79. 'weight', # until ≈ 2.5x block size increase
  80. 'version',
  81. 'subsidy', # until ≈ 01/04/2028 (increases by 1 digit per halving until 9th halving [max 10 digits])
  82. 'difficulty', # until 1.00e+100 (i.e. never)
  83. )
  84. # column width adjustment data:
  85. fs_lsqueeze = ('totalfee','inputs','outputs','nTx')
  86. fs_rsqueeze = ()
  87. fs_groups = (
  88. ('fee10','fee25','fee50','fee75','fee90','fee_avg','fee_min','fee_max'),
  89. )
  90. fs_lsqueeze2 = ('interval',)
  91. all_stats = ['col_avg','range','avg','mini_avg','total','diff']
  92. dfl_stats = ['range','mini_avg','diff']
  93. noindent_stats = ['col_avg']
  94. avg_stats_skip = {'block', 'hash', 'date', 'version','miner'}
  95. stats_deps = {
  96. 'avg': set(fields) - avg_stats_skip,
  97. 'col_avg':set(fields) - avg_stats_skip,
  98. 'mini_avg':{'interval','size','weight'},
  99. 'total': {'interval','subsidy','totalfee','nTx','inputs','outputs','utxo_inc'},
  100. 'range': {},
  101. 'diff': {},
  102. }
  103. fmt_funcs = {
  104. 'da': lambda arg: strftime('%Y-%m-%d %X',gmtime(arg)),
  105. 'td': lambda arg: (
  106. '-{:02}:{:02}'.format(abs(arg)//60,abs(arg)%60) if arg < 0 else
  107. ' {:02}:{:02}'.format(arg//60,arg%60) ),
  108. 'tf': lambda arg: '{:.8f}'.format(arg * Decimal('0.00000001')),
  109. 'su': lambda arg: str(arg * Decimal('0.00000001')).rstrip('0').rstrip('.'),
  110. 'di': lambda arg: '{:.2e}'.format(arg),
  111. }
  112. range_data = namedtuple('parsed_range_data',['first','last','from_tip','nblocks','step'])
  113. t_fmt = lambda self,t: f'{t/86400:.2f} days' if t > 172800 else f'{t/3600:.2f} hrs'
  114. @classmethod
  115. def parse_cslist(cls,uarg,full_set,dfl_set,desc):
  116. def make_list(m,func):
  117. groups_lc = [set(e.lower() for e in g.split(',')) for g in m.groups()]
  118. for group in groups_lc:
  119. for e in group:
  120. if e not in full_set_lc:
  121. die(1,f'{e!r}: unrecognized {desc}')
  122. # display elements in order:
  123. return [e for e in full_set if e.lower() in func(groups_lc)]
  124. full_set_lc = set(e.lower() for e in full_set)
  125. dfl_set_lc = set(e.lower() for e in dfl_set)
  126. cspat = r'(\w+(?:,\w+)*)'
  127. for pat,func in (
  128. ( rf'{cspat}$', lambda g: g[0] ),
  129. ( rf'\+{cspat}$', lambda g: dfl_set_lc | g[0] ),
  130. ( rf'\-{cspat}$', lambda g: dfl_set_lc - g[0] ),
  131. ( rf'\+{cspat}\-{cspat}$', lambda g: ( dfl_set_lc | g[0] ) - g[1] ),
  132. ( rf'\-{cspat}\+{cspat}$', lambda g: ( dfl_set_lc - g[0] ) | g[1] ),
  133. ( rf'all\-{cspat}$', lambda g: full_set_lc - g[0] )
  134. ):
  135. m = re.match(pat,uarg,re.ASCII|re.IGNORECASE)
  136. if m:
  137. return make_list(m,func)
  138. else:
  139. die(1,f'{uarg}: invalid parameter')
  140. def __init__(self,cmd_args,opt,rpc):
  141. def parse_cs_uarg(uarg,full_set,dfl_set,desc):
  142. return (
  143. full_set if uarg == 'all' else [] if uarg == 'none' else
  144. self.parse_cslist(uarg,full_set,dfl_set,desc)
  145. )
  146. def get_fields():
  147. return parse_cs_uarg(opt.fields,list(self.fields),self.dfl_fields,'field')
  148. def get_stats():
  149. return parse_cs_uarg(opt.stats.lower(),self.all_stats,self.dfl_stats,'stat')
  150. def parse_cmd_args(): # => (block_list, first, last, step)
  151. if not cmd_args:
  152. return (None,self.tip,self.tip,None)
  153. elif len(cmd_args) == 1:
  154. r = self.parse_rangespec(cmd_args[0])
  155. return (
  156. list(range(r.first,r.last+1,r.step)) if r.step else None,
  157. r.first,
  158. r.last,
  159. r.step
  160. )
  161. else:
  162. return ([self.conv_blkspec(a) for a in cmd_args],None,None,None)
  163. self.rpc = rpc
  164. self.opt = opt
  165. self.tip = rpc.blockcount
  166. self.block_list,self.first,self.last,self.step = parse_cmd_args()
  167. self.fnames = tuple(
  168. [f for f in self.fields if self.fields[f].src == 'bh' or f == 'interval'] if opt.header_info else
  169. get_fields() if opt.fields else
  170. self.dfl_fields
  171. )
  172. if opt.miner_info and 'miner' not in self.fnames:
  173. self.fnames += ('miner',)
  174. self.stats = get_stats() if opt.stats else self.dfl_stats
  175. # Display diff stats by default only if user-requested range ends with chain tip
  176. if 'diff' in self.stats and not opt.stats and self.last != self.tip:
  177. self.stats.remove('diff')
  178. if {'avg','col_avg'} <= set(self.stats) and opt.stats_only:
  179. self.stats.remove('col_avg')
  180. if {'avg','mini_avg'} <= set(self.stats):
  181. self.stats.remove('mini_avg')
  182. if opt.full_stats:
  183. add_fnames = {fname for sname in self.stats for fname in self.stats_deps[sname]}
  184. self.fnames = tuple(f for f in self.fields if f in {'block'} | set(self.fnames) | add_fnames )
  185. else:
  186. if 'col_avg' in self.stats and not self.fnames:
  187. self.stats.remove('col_avg')
  188. # self.fnames is now finalized
  189. self.fvals = [self.fields[name] for name in self.fnames]
  190. self.fs = ''.join(self.gen_fs(self.fnames)).strip()
  191. self.bs_keys = set(
  192. [v.key1 for v in self.fvals if v.src == 'bs'] +
  193. ['total_size','total_weight']
  194. )
  195. if 'miner' in self.fnames:
  196. # capturing parens must contain only ASCII chars!
  197. self.miner_pats = [re.compile(pat) for pat in (
  198. rb'`/([_a-zA-Z0-9&. #/-]+)/',
  199. rb'[\xe3\xe4\xe5][\^/]([\x20-\x7e]+?)\xfa',
  200. rb'([a-zA-Z0-9&. -]+/Mined by [a-zA-Z0-9. ]+)',
  201. rb'\x08/(.*Mined by [a-zA-Z0-9. ]+)',
  202. rb'Mined by ([a-zA-Z0-9. ]+)',
  203. rb'[`]([_a-zA-Z0-9&. #/-]+)[/\xfa]',
  204. rb'([\x20-\x7e]{9,})',
  205. rb'[/^]([a-zA-Z0-9&. #/-]{5,})',
  206. rb'[/^]([_a-zA-Z0-9&. #/-]+)/',
  207. rb'^\x03...\W{0,5}([\\_a-zA-Z0-9&. #/-]+)[/\\]',
  208. )]
  209. self.block_data = namedtuple('block_data',self.fnames)
  210. self.deps = { v.src for v in self.fvals }
  211. def gen_fs(self,fnames,fill=[],fill_char='-',add_name=False):
  212. for i in range(len(fnames)):
  213. name = fnames[i]
  214. ls = (' ','')[name in self.fs_lsqueeze + self.fs_lsqueeze2]
  215. rs = (' ','')[name in self.fs_rsqueeze]
  216. if i < len(fnames) - 1 and fnames[i+1] in self.fs_lsqueeze2:
  217. rs = ''
  218. if i:
  219. for group in self.fs_groups:
  220. if name in group and fnames[i-1] in group:
  221. ls = ''
  222. break
  223. repl = (name if add_name else '') + ':' + (fill_char if name in fill else '')
  224. yield (ls + self.fields[name].fs.replace(':',repl) + rs)
  225. def conv_blkspec(self,arg):
  226. if str(arg).lower() == 'cur':
  227. return self.tip
  228. elif is_int(arg):
  229. if int(arg) < 0:
  230. die(1,f'{arg}: block number must be non-negative')
  231. elif int(arg) > self.tip:
  232. die(1,f'{arg}: requested block height greater than current chain tip!')
  233. else:
  234. return int(arg)
  235. else:
  236. die(1,f'{arg}: invalid block specifier')
  237. def check_nblocks(self,arg):
  238. if arg <= 0:
  239. die(1,'nBlocks must be a positive integer')
  240. elif arg > self.tip:
  241. die(1, f"'{arg}': nBlocks must be less than current chain height")
  242. return arg
  243. def parse_rangespec(self,arg):
  244. class RangeParser:
  245. debug = False
  246. def __init__(rp,arg):
  247. rp.arg = rp.orig_arg = arg
  248. def parse(rp,target):
  249. ret = getattr(rp,'parse_'+target)()
  250. if rp.debug: msg(f'arg after parse({target}): {rp.arg}')
  251. return ret
  252. def finalize(rp):
  253. if rp.arg:
  254. die(1,f'{rp.orig_arg!r}: invalid range specifier')
  255. def parse_from_tip(rp):
  256. m = re.match(r'-([0-9]+)(.*)',rp.arg)
  257. if m:
  258. res,rp.arg = (m[1],m[2])
  259. return self.check_nblocks(int(res))
  260. def parse_abs_range(rp):
  261. m = re.match(r'([^+-]+)(-([^+-]+)){0,1}(.*)',rp.arg)
  262. if m:
  263. if rp.debug: msg(f'abs_range parse: first={m[1]}, last={m[3]}')
  264. rp.arg = m[4]
  265. return (
  266. self.conv_blkspec(m[1]),
  267. self.conv_blkspec(m[3]) if m[3] else None
  268. )
  269. return (None,None)
  270. def parse_add(rp):
  271. m = re.match(r'\+([0-9*]+)(.*)',rp.arg)
  272. if m:
  273. res,rp.arg = (m[1],m[2])
  274. if res.strip('*') != res:
  275. die(1,f"'+{res}': malformed nBlocks specifier")
  276. if len(res) > 30:
  277. die(1,f"'+{res}': overly long nBlocks specifier")
  278. return self.check_nblocks(eval(res)) # res is only digits plus '*', so eval safe
  279. p = RangeParser(arg)
  280. from_tip = p.parse('from_tip')
  281. first,last = (self.tip-from_tip,None) if from_tip else p.parse('abs_range')
  282. add1 = p.parse('add')
  283. add2 = p.parse('add')
  284. p.finalize()
  285. if add2 and last is not None:
  286. die(1,f'{arg!r}: invalid range specifier')
  287. nblocks,step = (add1,add2) if last is None else (None,add1)
  288. if p.debug: msg(repr(self.range_data(first,last,from_tip,nblocks,step)))
  289. if nblocks:
  290. if first == None:
  291. first = self.tip - nblocks + 1
  292. last = first + nblocks - 1
  293. first = self.conv_blkspec(first)
  294. last = self.conv_blkspec(last or first)
  295. if p.debug: msg(repr(self.range_data(first,last,from_tip,nblocks,step)))
  296. if first > last:
  297. die(1,f'{first}-{last}: invalid block range')
  298. return self.range_data(first,last,from_tip,nblocks,step)
  299. async def process_blocks(self):
  300. async def get_hdrs(heights):
  301. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  302. return await c.gathered_call('getblockheader',[(H,) for H in hashes])
  303. c = self.rpc
  304. heights = self.block_list or range(self.first,self.last+1)
  305. self.hdrs = await get_hdrs(heights)
  306. if self.block_list:
  307. self.prev_hdrs = await get_hdrs([(n-1 if n else 0) for n in self.block_list])
  308. self.first_prev_hdr = self.prev_hdrs[0]
  309. else:
  310. self.first_prev_hdr = (
  311. self.hdrs[0] if heights[0] == 0 else
  312. await c.call('getblockheader',await c.call('getblockhash',heights[0]-1))
  313. )
  314. self.t_cur = self.first_prev_hdr['time']
  315. self.res = []
  316. for n in range(len(heights)):
  317. if self.block_list:
  318. self.t_cur = self.prev_hdrs[n]['time']
  319. ret = await self.process_block(self.hdrs[n])
  320. self.res.append(ret)
  321. if self.fnames and not self.opt.stats_only:
  322. self.output_block(ret,n)
  323. def output_block(self,data,n):
  324. def gen():
  325. for k,v in data._asdict().items():
  326. func = self.fields[k].fmt_func
  327. yield self.fmt_funcs[func](v) if func else v
  328. Msg(self.fs.format(*gen()))
  329. async def process_block(self,hdr):
  330. self.t_diff = hdr['time'] - self.t_cur
  331. self.t_cur = hdr['time']
  332. self.total_solve_time += self.t_diff
  333. blk_data = {
  334. 'bh': hdr,
  335. 'lo': { 'interval': self.t_diff }
  336. }
  337. if 'bs' in self.deps:
  338. bs = (
  339. self.genesis_stats if hdr['height'] == 0 else
  340. await self.rpc.call('getblockstats',hdr['hash'],list(self.bs_keys))
  341. )
  342. self.total_bytes += bs['total_size']
  343. self.total_weight += bs['total_weight']
  344. blk_data['bs'] = bs
  345. if 'miner' in self.fnames:
  346. blk_data['lo']['miner'] = '-' if hdr['height'] == 0 else await self.get_miner_string(hdr['hash'])
  347. def gen():
  348. for v in self.fvals:
  349. yield (
  350. blk_data[v.src][v.key1] if v.key2 is None else
  351. blk_data[v.src][v.key1][v.key2]
  352. )
  353. return self.block_data(*gen())
  354. async def get_miner_string(self,H):
  355. tx0 = (await self.rpc.call('getblock',H))['tx'][0]
  356. bd = await self.rpc.call('getrawtransaction',tx0,1)
  357. if type(bd) == tuple:
  358. return '---'
  359. else:
  360. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  361. if self.opt.raw_miner_info:
  362. return repr(cb)
  363. else:
  364. trmap_in = {
  365. '\\': ' ',
  366. '/': ' ',
  367. ',': ' ',
  368. }
  369. trmap = { ord(a):b for a,b in trmap_in.items() }
  370. for pat in self.miner_pats:
  371. m = pat.search(cb)
  372. if m:
  373. return re.sub( r'\s+', ' ', m[1].decode().strip('^').translate(trmap).strip() )
  374. return ''
  375. def print_header(self):
  376. Msg('\n'.join(self.gen_header()))
  377. self.header_printed = True
  378. def gen_header(self):
  379. hdr1 = [v.hdr1 for v in self.fvals]
  380. hdr2 = [v.hdr2 for v in self.fvals]
  381. if ''.join(hdr1):
  382. yield self.fs.format(*hdr1)
  383. yield self.fs.format(*hdr2)
  384. def process_stats(self,sname):
  385. method = getattr(self,f'create_{sname}_stats',None)
  386. return self.output_stats(method() if method else self.create_stats(sname),sname)
  387. def fmt_stat_item(self,fs,s):
  388. return fs.format(s) if type(fs) == str else fs(s)
  389. async def output_stats(self,res,sname):
  390. def gen(data):
  391. for d in data:
  392. if len(d) == 2:
  393. yield (indent+d[0]).format(**{k:self.fmt_stat_item(*v) for k,v in d[1].items()})
  394. elif len(d) == 4:
  395. yield (indent+d[0]).format(self.fmt_stat_item(d[2],d[3]))
  396. elif type(d) == str:
  397. yield d
  398. else:
  399. assert False, f'{d}: invalid stats data'
  400. foo,data = await res
  401. indent = '' if sname in self.noindent_stats else ' '
  402. Msg('\n'.join(gen(data)))
  403. async def create_range_stats(self):
  404. # These figures don’t include the Genesis Block:
  405. elapsed = self.hdrs[-1]['time'] - self.first_prev_hdr['time']
  406. nblocks = self.hdrs[-1]['height'] - self.first_prev_hdr['height']
  407. total_blks = len(self.hdrs)
  408. step_disp = f', nBlocks={total_blks}, step={self.step}' if self.step else ''
  409. def gen():
  410. yield 'Range Statistics:'
  411. yield (
  412. 'Range: {start}-{end} ({range} blocks [{elapsed}]%s)' % step_disp, {
  413. 'start': ('{}', self.hdrs[0]['height']),
  414. 'end': ('{}', self.hdrs[-1]['height']),
  415. 'range': ('{}', self.hdrs[-1]['height'] - self.hdrs[0]['height'] + 1),
  416. 'elapsed': (self.t_fmt, elapsed),
  417. 'nBlocks': ('{}', total_blks),
  418. 'step': ('{}', self.step),
  419. }
  420. )
  421. if elapsed:
  422. yield ( 'Start: {}', 'start_date', self.fmt_funcs['da'], self.hdrs[0]['time'] )
  423. yield ( 'End: {}', 'end_date', self.fmt_funcs['da'], self.hdrs[-1]['time'] )
  424. yield ( 'Avg BDI: {} min', 'avg_bdi', '{:.2f}', elapsed / nblocks / 60 )
  425. return ( 'range', gen() )
  426. async def create_diff_stats(self):
  427. c = self.rpc
  428. rel = self.tip % 2016
  429. tip_hdr = (
  430. self.hdrs[-1] if self.hdrs[-1]['height'] == self.tip else
  431. await c.call('getblockheader',await c.call('getblockhash',self.tip))
  432. )
  433. min_sample_blks = 432 # ≈3 days
  434. rel_hdr = await c.call('getblockheader',await c.call('getblockhash',self.tip-rel))
  435. if rel >= min_sample_blks:
  436. sample_blks = rel
  437. bdi = ( tip_hdr['time'] - rel_hdr['time'] ) / rel
  438. else:
  439. sample_blks = min_sample_blks
  440. start_hdr = await c.call('getblockheader',await c.call('getblockhash',self.tip-sample_blks))
  441. diff_adj = float(tip_hdr['difficulty'] / start_hdr['difficulty'])
  442. time1 = rel_hdr['time'] - start_hdr['time']
  443. time2 = tip_hdr['time'] - rel_hdr['time']
  444. bdi = ((time1 * diff_adj) + time2) / sample_blks
  445. rem = 2016 - rel
  446. return ( 'difficulty', (
  447. 'Difficulty Statistics:',
  448. ('Current height: {}', 'chain_tip', '{}', self.tip),
  449. ('Next diff adjust: {next_diff_adjust} (in {blks_remaining} block%s [{time_remaining}])' % suf(rem),
  450. {
  451. 'next_diff_adjust': ('{}', self.tip + rem),
  452. 'blks_remaining': ('{}', rem),
  453. 'time_remaining': (self.t_fmt, rem * bdi)
  454. }
  455. ),
  456. ('Avg BDI: {avg_bdi} min (over {sample_blks}-block period)',
  457. {
  458. 'avg_bdi': ('{:.2f}', bdi/60),
  459. 'sample_blks': ('{}', sample_blks)
  460. }
  461. ),
  462. ('Cur difficulty: {}', 'cur_diff', '{:.2e}', tip_hdr['difficulty']),
  463. ('Est. diff adjust: {}%', 'est_diff_adjust_pct', '{:+.2f}', ((600 / bdi) - 1) * 100),
  464. ))
  465. async def create_col_avg_stats(self):
  466. def gen():
  467. for field in self.fnames:
  468. if field in self.avg_stats_skip:
  469. yield ( field, ('{}','') )
  470. else:
  471. ret = sum(getattr(block,field) for block in self.res) // len(self.res)
  472. func = self.fields[field].fmt_func
  473. yield ( field, ( (self.fmt_funcs[func] if func else '{}'), ret ))
  474. if not self.header_printed:
  475. self.print_header()
  476. fs = ''.join(self.gen_fs(self.fnames,fill=self.avg_stats_skip,add_name=True)).strip()
  477. return ('column_averages', ('Column averages:', (fs, dict(gen())) ))
  478. def avg_stats_data(self,data,spec_conv,spec_val):
  479. coin = self.rpc.proto.coin
  480. return data(
  481. hdr = 'Averages for processed blocks:',
  482. func = lambda field: sum(getattr(block,field) for block in self.res) // len(self.res),
  483. spec_sufs = { 'subsidy': f' {coin}', 'totalfee': f' {coin}' },
  484. spec_convs = {
  485. 'interval': spec_conv(0, lambda arg: secs_to_ms(arg)),
  486. 'utxo_inc': spec_conv(-1, '{:<+}'),
  487. 'mb_per_hour': spec_conv(0, '{:.4f}'),
  488. },
  489. spec_vals = (
  490. spec_val(
  491. 'mb_per_hour', 'MB/hr', 'interval',
  492. lambda values: 'bs' in self.deps,
  493. lambda values: (self.total_bytes / 10000) / (self.total_solve_time / 36)
  494. ),
  495. )
  496. )
  497. mini_avg_stats_data = avg_stats_data
  498. def total_stats_data(self,data,spec_conv,spec_val):
  499. coin = self.rpc.proto.coin
  500. return data(
  501. hdr = 'Totals for processed blocks:',
  502. func = lambda field: sum(getattr(block,field) for block in self.res),
  503. spec_sufs = { 'subsidy': f' {coin}', 'totalfee': f' {coin}', 'reward': f' {coin}' },
  504. spec_convs = {
  505. 'interval': spec_conv(0, lambda arg: secs_to_dhms(arg)),
  506. 'utxo_inc': spec_conv(-1, '{:<+}'),
  507. 'reward': spec_conv(0, self.fmt_funcs['tf']),
  508. },
  509. spec_vals = (
  510. spec_val(
  511. 'reward', 'Reward', 'totalfee',
  512. lambda values: {'subsidy','totalfee'} <= set(values),
  513. lambda values: values['subsidy'] + values['totalfee']
  514. ),
  515. )
  516. )
  517. async def create_stats(self,sname):
  518. def convert_stats_hdr(field):
  519. v = self.fields[field]
  520. return '{} {}'.format(v.hdr1.strip(), v.hdr2.strip()).replace('- ','') if v.hdr1 else v.hdr2.strip()
  521. d = getattr(self,f'{sname}_stats_data')(
  522. namedtuple('stats_data',['hdr','func','spec_sufs','spec_convs','spec_vals']),
  523. namedtuple('spec_conv',['width_adj','conv']),
  524. namedtuple('spec_val',['name','lbl','insert_after','condition','code'])
  525. )
  526. fnames = [n for n in self.fnames if n in self.stats_deps[sname]]
  527. lbls = {n:convert_stats_hdr(n) for n in fnames}
  528. values = {n:d.func(n) for n in fnames}
  529. col1_w = max((len(l) for l in lbls.values()),default=0) + 2
  530. for v in d.spec_vals:
  531. if v.condition(values):
  532. try: idx = fnames.index(v.insert_after) + 1
  533. except: idx = 0
  534. fnames.insert(idx,v.name)
  535. lbls[v.name] = v.lbl
  536. values[v.name] = v.code(values)
  537. def gen():
  538. for n,fname in enumerate(fnames):
  539. spec_conv = d.spec_convs.get(fname)
  540. yield (
  541. '{lbl:{wid}} {{}}{suf}'.format(
  542. lbl = lbls[fname] + ':',
  543. wid = col1_w + (spec_conv.width_adj if spec_conv else 0),
  544. suf = d.spec_sufs.get(fname) or ''
  545. ),
  546. fname,
  547. spec_conv.conv if spec_conv else (
  548. (lambda x: self.fmt_funcs[x] if x else '{}')(self.fields[fname].fmt_func)
  549. ),
  550. values[fname]
  551. )
  552. return ( sname, (d.hdr,) + tuple(gen()) )
  553. def process_stats_pre(self,i):
  554. if (self.fnames and not self.opt.stats_only) or i != 0:
  555. Msg('')
  556. def finalize_output(self): pass
  557. # 'getblockstats' RPC raises exception on Genesis Block, so provide our own stats:
  558. genesis_stats = {
  559. 'avgfee': 0,
  560. 'avgfeerate': 0,
  561. 'avgtxsize': 0,
  562. 'feerate_percentiles': [ 0, 0, 0, 0, 0 ],
  563. 'height': 0,
  564. 'ins': 0,
  565. 'maxfee': 0,
  566. 'maxfeerate': 0,
  567. 'maxtxsize': 0,
  568. 'medianfee': 0,
  569. 'mediantxsize': 0,
  570. 'minfee': 0,
  571. 'minfeerate': 0,
  572. 'mintxsize': 0,
  573. 'outs': 1,
  574. 'subsidy': 5000000000,
  575. 'swtotal_size': 0,
  576. 'swtotal_weight': 0,
  577. 'swtxs': 0,
  578. 'total_out': 0,
  579. 'total_size': 0,
  580. 'total_weight': 0,
  581. 'totalfee': 0,
  582. 'txs': 1,
  583. 'utxo_increase': 1,
  584. 'utxo_size_inc': 117
  585. }
  586. class JSONBlocksInfo(BlocksInfo):
  587. def __init__(self,cmd_args,opt,rpc):
  588. super().__init__(cmd_args,opt,rpc)
  589. if opt.json_raw:
  590. self.output_block = self.output_block_raw
  591. self.fmt_stat_item = self.fmt_stat_item_raw
  592. Msg_r('{')
  593. async def process_blocks(self):
  594. Msg_r('"block_data": [')
  595. await super().process_blocks()
  596. Msg_r(']')
  597. def output_block_raw(self,data,n):
  598. Msg_r( (', ','')[n==0] + json.dumps(data._asdict(),cls=json_encoder) )
  599. def output_block(self,data,n):
  600. def gen():
  601. for k,v in data._asdict().items():
  602. func = self.fields[k].fmt_func
  603. yield ( k, (self.fmt_funcs[func](v) if func else v) )
  604. Msg_r( (', ','')[n==0] + json.dumps(dict(gen()),cls=json_encoder) )
  605. def print_header(self): pass
  606. def fmt_stat_item_raw(self,fs,s):
  607. return s
  608. async def output_stats(self,res,sname):
  609. def gen(data):
  610. for d in data:
  611. if len(d) == 2:
  612. for k,v in d[1].items():
  613. yield (k,self.fmt_stat_item(*v))
  614. elif len(d) == 4:
  615. yield (d[1],self.fmt_stat_item(d[2],d[3]))
  616. elif type(d) != str:
  617. assert False, f'{d}: invalid stats data'
  618. varname,data = await res
  619. Msg_r(', "{}_data": {}'.format( varname, json.dumps(dict(gen(data)),cls=json_encoder) ))
  620. def process_stats_pre(self,i): pass
  621. def finalize_output(self):
  622. Msg('}')