BlocksInfo.py 24 KB

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