mmnode-blocks-info 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. mmnode-blocks-info: Display information about a block or range of blocks
  20. """
  21. import time,re
  22. from collections import namedtuple
  23. from mmgen.common import *
  24. from decimal import Decimal
  25. opts_data = {
  26. 'sets': [
  27. ('raw_miner_info',True,'miner_info',True),
  28. ('summary',True,'raw_miner_info',False),
  29. ('summary',True,'miner_info',False)
  30. ],
  31. 'text': {
  32. 'desc': 'Display information about a range of blocks',
  33. 'usage': '[opts] +<last n blocks>|<block num>|<block num range>',
  34. 'options': """
  35. -h, --help Print this help message
  36. --, --longhelp Print help message for long options (common options)
  37. -H, --hashes Display only block numbers and hashes
  38. -m, --miner-info Display miner info in coinbase transaction
  39. -M, --raw-miner-info Display miner info in uninterpreted form
  40. -n, --no-header Don't print the column header
  41. -o, --fields= Display the specified fields
  42. -s, --summary Print the summary only
  43. -S, --no-summary Don't print the summary
  44. """,
  45. 'notes': """
  46. If no block number is specified, the current block is assumed.
  47. In addition to information about the requested range of blocks, an estimate
  48. of the next difficulty adjustment is also displayed based on the average
  49. Block Discovery Interval from the beginning of the current 2016-block period
  50. to the chain tip.
  51. Requires --txindex for correct operation.
  52. """
  53. }
  54. }
  55. class local_vars: pass
  56. class BlocksInfo:
  57. first = None
  58. last = None
  59. nblocks = None
  60. def __init__(self):
  61. self.get_block_range()
  62. self.post_init()
  63. def get_block_range(self):
  64. if not cmd_args:
  65. first = last = c.blockcount
  66. else:
  67. arg = cmd_args[0]
  68. if arg.startswith('+') and is_int(arg[1:]):
  69. last = c.blockcount
  70. first = last - int(arg[1:]) + 1
  71. elif is_int(arg):
  72. first = last = int(arg)
  73. else:
  74. try:
  75. first,last = [int(ep) for ep in arg.split('-')]
  76. except:
  77. opts.usage()
  78. if first > last:
  79. die(2,f'{first}-{last}: invalid block range')
  80. if last > c.blockcount:
  81. die(2,f'Requested block number ({last}) greater than current block height')
  82. self.first = first
  83. self.last = last
  84. self.nblocks = last - first + 1
  85. def post_init(self): pass
  86. async def run(self):
  87. heights = range(self.first,self.last+1)
  88. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  89. hdrs = await c.gathered_call('getblockheader',[(H,) for H in hashes])
  90. for height in heights:
  91. await self.process_block(height,hashes.pop(0),hdrs.pop(0))
  92. def print_header(self):
  93. hdr1 = [v.hdr1 for v in self.fvals]
  94. hdr2 = [v.hdr2 for v in self.fvals]
  95. if opt.miner_info:
  96. hdr1.append(' ')
  97. hdr2.append('Miner')
  98. Msg(self.fs.format(*hdr1))
  99. Msg(self.fs.format(*hdr2))
  100. async def print_summary(self):
  101. from mmgen.util import secs_to_hms
  102. tip = c.blockcount
  103. rel = tip % 2016
  104. if rel:
  105. H1,H2,HA,HB = await c.gathered_call('getblockhash',[[self.first],[self.last],[tip-rel],[tip]])
  106. h1,h2,hA,hB = await c.gathered_call('getblockheader',[[H1],[H2],[HA],[HB]])
  107. bdi = (hB['time']-hA['time']) / rel
  108. adj_pct = ((600 / bdi) - 1) * 100
  109. Msg_r(fmt(f"""
  110. Current height: {tip}
  111. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks [{((2016-rel)*bdi)/86400:.2f} days])
  112. BDI (cur period): {bdi/60:.2f} min
  113. Est. diff adjust: {adj_pct:+.2f}%
  114. """))
  115. else:
  116. H1,H2 = await c.gathered_call('getblockhash',[[self.first],[self.last]])
  117. h1,h2 = await c.gathered_call('getblockheader',[[H1],[H2]])
  118. Msg_r(fmt(f"""
  119. Current height: {tip}
  120. Next diff adjust: {tip-rel+2016} (in {2016-rel} blocks)
  121. """))
  122. Msg('\nRange: {}-{} ({} blocks [{}])'.format(
  123. self.first,
  124. self.last,
  125. self.nblocks,
  126. secs_to_hms(h2['time'] - h1['time']) ))
  127. class BlocksInfoOverview(BlocksInfo):
  128. total_bytes = 0
  129. total_weight = 0
  130. t_start = None
  131. t_prev = None
  132. t_cur = None
  133. bf = namedtuple('block_info_fields',['hdr1','hdr2','fs','bs_key','varname','deps','key'])
  134. # bs=getblockstats(), bh=getblockheader()
  135. # If 'bs_key' is set, it's included in self.bs_keys instead of 'key'
  136. fields = {
  137. 'block': bf('', 'Block', '{:<6}', None, 'height',[], None),
  138. 'hash': bf('', 'Hash', '{:<64}', None, 'H', [], None),
  139. 'date': bf('', 'Date', '{:<19}', None, 'df', ['bs'],None),
  140. 'interval': bf('Solve','Time ', '{:>6}', None, 'if', ['bs'],None),
  141. 'size': bf('', 'Size', '{:>7}', None, 'bs', [], 'total_size'),
  142. 'weight': bf('', 'Weight', '{:>7}', None, 'bs', [], 'total_weight'),
  143. 'utxo_inc': bf(' UTXO',' Incr', '{:>5}', None, 'bs', [], 'utxo_increase'),
  144. 'fee10': bf('10%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'],0),
  145. 'fee25': bf('25%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'],1),
  146. 'fee50': bf('50%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'],2),
  147. 'fee75': bf('75%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'],3),
  148. 'fee90': bf('90%', 'Fee', '{:>3}', 'feerate_percentiles','fp', ['bs'],4),
  149. 'fee_avg': bf('Avg', 'Fee', '{:>3}', None, 'bs', [], 'avgfeerate'),
  150. 'fee_min': bf('Min', 'Fee', '{:>3}', None, 'bs', [], 'minfeerate'),
  151. 'totalfee': bf('', 'Total Fee','{:>10}', 'totalfee', 'tf', ['bs'],None),
  152. 'outputs': bf('Out-', 'puts', '{:>5}', None, 'bs', [], 'outs'),
  153. 'inputs': bf('In- ', 'puts', '{:>5}', None, 'bs', [], 'ins'),
  154. 'version': bf('', 'Version', '{:8}', None, 'bh', [], 'versionHex'),
  155. 'nTx': bf('', 'nTx ', '{:>5}', None, 'bh', [], 'nTx'),
  156. 'subsidy': bf('', 'Subsidy', '{:7}', 'subsidy', 'su', ['bs'], None),
  157. }
  158. dfl_fields = ['block','date','interval','subsidy','totalfee','size','weight','fee50','fee25','fee10','version']
  159. funcs = {
  160. 'df': lambda self,loc: time.strftime('%Y-%m-%d %X',time.gmtime(self.t_cur)),
  161. 'if': lambda self,loc: (
  162. '-{:02}:{:02}'.format(abs(loc.t_diff)//60,abs(loc.t_diff)%60) if loc.t_diff < 0 else
  163. ' {:02}:{:02}'.format(loc.t_diff//60,loc.t_diff%60) ),
  164. 'tf': lambda self,loc: '{:.8f}'.format(loc.bs["totalfee"] * Decimal('0.00000001')),
  165. 'bh': lambda self,loc: loc.hdr,
  166. 'fp': lambda self,loc: loc.bs['feerate_percentiles'],
  167. 'su': lambda self,loc: str(loc.bs['subsidy'] * Decimal('0.00000001')).rstrip('0'),
  168. }
  169. def __init__(self):
  170. super().__init__()
  171. if opt.fields:
  172. fnames = opt.fields.split(',')
  173. for n in fnames:
  174. if n not in self.fields:
  175. die(1,f'{n!r}: unrecognized field')
  176. else:
  177. fnames = self.dfl_fields
  178. self.fvals = list(self.fields[k] for k in fnames if k in self.fields)
  179. self.fs = ' '.join( v.fs for v in self.fvals )
  180. self.deps = set(' '.join(v.varname + ' ' + ' '.join(v.deps) for v in self.fvals).split())
  181. self.bs_keys = [(v.bs_key or v.key) for v in self.fvals if v.bs_key or v.varname == 'bs']
  182. self.bs_keys.extend(['total_size','time'])
  183. self.ufuncs = {v.varname:self.funcs[v.varname] for v in self.fvals if v.varname in self.funcs}
  184. if opt.miner_info:
  185. self.fs += ' {}'
  186. self.miner_pats = [re.compile(pat) for pat in (
  187. rb'[\xe3\xe4\xe5][\^/](.*?)\xfa',
  188. rb'([a-zA-Z0-9&. -]+/Mined by [a-zA-Z0-9. ]+)',
  189. rb'\x08/(.*Mined by [a-zA-Z0-9. ]+)',
  190. rb'Mined by ([a-zA-Z0-9. ]+)',
  191. rb'[/^]([a-zA-Z0-9&. /-]{5,})',
  192. rb'[/^]([a-zA-Z0-9&. /-]+)/',
  193. )]
  194. else:
  195. self.miner_pats = None
  196. async def get_miner_string(self,H):
  197. tx0 = (await c.call('getblock',H))['tx'][0]
  198. bd = await c.call('getrawtransaction',tx0,1)
  199. if type(bd) == tuple:
  200. return '---'
  201. else:
  202. cb = bytes.fromhex(bd['vin'][0]['coinbase'])
  203. if opt.raw_miner_info:
  204. return repr(cb)
  205. else:
  206. for pat in self.miner_pats:
  207. m = pat.search(cb)
  208. if m:
  209. return ''.join(chr(b) for b in m[1] if 31 < b < 127).strip('^').strip('/').replace('/',' ')
  210. async def process_block(self,height,H,hdr):
  211. loc = local_vars()
  212. loc.height = height
  213. loc.H = H
  214. loc.hdr = hdr
  215. if 'bs' in self.deps:
  216. loc.bs = await c.call('getblockstats',H,self.bs_keys)
  217. self.total_bytes += loc.bs['total_size']
  218. self.total_weight += loc.bs['total_weight']
  219. self.t_cur = loc.bs['time']
  220. if self.t_prev == None:
  221. if height == 0:
  222. b_prev = loc.bs
  223. else:
  224. bH = await c.call('getblockhash',height-1)
  225. b_prev = await c.call('getblockstats',bH)
  226. self.t_start = self.t_prev = b_prev['time']
  227. loc.t_diff = self.t_cur - self.t_prev
  228. self.t_prev = self.t_cur
  229. if opt.summary:
  230. return
  231. for varname,func in self.ufuncs.items():
  232. ret = func(self,loc)
  233. if type(ret).__name__ == 'coroutine':
  234. ret = await ret
  235. setattr(loc,varname,ret)
  236. if opt.miner_info:
  237. miner_info = await self.get_miner_string(H)
  238. def gen():
  239. for v in self.fvals:
  240. if v.key is None:
  241. yield getattr(loc,v.varname)
  242. else:
  243. yield getattr(loc,v.varname)[v.key]
  244. if opt.miner_info:
  245. yield miner_info
  246. Msg(self.fs.format(*gen()))
  247. async def print_summary(self):
  248. if 'bs' in self.deps:
  249. await super().print_summary()
  250. if self.nblocks > 1:
  251. elapsed = self.t_cur - self.t_start
  252. ac = int(elapsed / self.nblocks)
  253. rate = (self.total_bytes / 10000) / (elapsed / 36)
  254. Msg_r (fmt(f"""
  255. Avg size: {self.total_bytes//self.nblocks} bytes
  256. Avg weight: {self.total_weight//self.nblocks} bytes
  257. MB/hr: {rate:0.4f}
  258. Avg BDI: {ac/60:.2f} min
  259. """))
  260. class BlocksInfoHashes(BlocksInfo):
  261. def print_header(self):
  262. Msg('{:<7} {}'.format('BLOCK','HASH'))
  263. async def run(self):
  264. heights = range(self.first,self.last+1)
  265. hashes = await c.gathered_call('getblockhash',[(height,) for height in heights])
  266. Msg('\n'.join('{:<7} {}'.format(height,H) for height,H in zip(heights,hashes)))
  267. cmd_args = opts.init(opts_data)
  268. if len(cmd_args) not in (0,1):
  269. opts.usage()
  270. async def main():
  271. from mmgen.protocol import init_proto_from_opts
  272. proto = init_proto_from_opts()
  273. from mmgen.rpc import rpc_init
  274. global c
  275. c = await rpc_init(proto)
  276. if opt.hashes:
  277. m = BlocksInfoHashes()
  278. else:
  279. m = BlocksInfoOverview()
  280. if not (opt.summary or opt.no_header):
  281. m.print_header()
  282. await m.run()
  283. if not opt.no_summary:
  284. if not opt.summary:
  285. Msg('')
  286. await m.print_summary()
  287. run_session(main())