BlocksInfo.py 24 KB

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