mmnode-blocks-info 10.0 KB

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