BlocksInfo.py 24 KB

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