mmnode-blocks-info 11 KB

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