main_addrbal.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen https://github.com/mmgen/mmgen-node-tools
  9. # https://gitlab.com/mmgen/mmgen https://gitlab.com/mmgen/mmgen-node-tools
  10. """
  11. mmnode-addrbal: Get balances for arbitrary addresses in the blockchain
  12. """
  13. from mmgen.obj import CoinTxID,Int
  14. from mmgen.cfg import Config
  15. from mmgen.util import msg,Msg,die,suf,make_timestr,async_run
  16. from mmgen.color import red
  17. opts_data = {
  18. 'text': {
  19. 'desc': 'Get balances for arbitrary addresses in the blockchain',
  20. 'usage': '[opts] address [address..]',
  21. 'options': """
  22. -h, --help Print this help message
  23. --, --longhelp Print help message for long options (common options)
  24. -f, --first-block With tabular output, additionally display first block info
  25. -t, --tabular Produce compact tabular output
  26. """
  27. }
  28. }
  29. def do_output(proto,addr_data,blk_hdrs):
  30. col1w = len(str(len(addr_data)))
  31. indent = ' ' * (col1w + 2)
  32. for n,(addr,unspents) in enumerate(addr_data.items(),1):
  33. Msg(f'\n{n:{col1w}}) Address: {addr.hl()}')
  34. if unspents:
  35. heights = { u['height'] for u in unspents }
  36. Msg('{}Balance: {}'.format(
  37. indent,
  38. proto.coin_amt(sum(u['amount'] for u in unspents)).hl2(unit=True,fs='{:,}') )),
  39. Msg('{}{} unspent output{} in {} block{}'.format(
  40. indent,
  41. red(str(len(unspents))),
  42. suf(unspents),
  43. red(str(len(heights))),
  44. suf(heights) ))
  45. blk_w = len(str(unspents[-1]['height']))
  46. fs = '%s{:%s} {:19} {:64} {:4} {}' % (indent,max(5,blk_w))
  47. Msg(fs.format('Block','Date','TxID','Vout',' Amount'))
  48. for u in unspents:
  49. Msg(fs.format(
  50. u['height'],
  51. make_timestr( blk_hdrs[u['height']]['time'] ),
  52. CoinTxID(u['txid']).hl(),
  53. red(str(u['vout']).rjust(4)),
  54. proto.coin_amt(u['amount']).fmt(color=True,iwidth=6,prec=8)
  55. ))
  56. else:
  57. Msg(f'{indent}No balance')
  58. def do_output_tabular(proto,addr_data,blk_hdrs):
  59. col1w = len(str(len(addr_data))) + 1
  60. max_addrw = max(len(addr) for addr in addr_data)
  61. fb_heights = [str(unspents[0]['height']) if unspents else '' for unspents in addr_data.values()]
  62. lb_heights = [str(unspents[-1]['height']) if unspents else '' for unspents in addr_data.values()]
  63. fb_w = max(len(h) for h in fb_heights)
  64. lb_w = max(len(h) for h in lb_heights)
  65. fs = (
  66. ' {n:>%s} {a} {u} {b:>%s} {t:19} {B:>%s} {T:19} {A}' % (col1w,max(5,fb_w),max(4,lb_w))
  67. if cfg.first_block else
  68. ' {n:>%s} {a} {u} {B:>%s} {T:19} {A}' % (col1w,max(4,lb_w)) )
  69. Msg('\n' + fs.format(
  70. n = '',
  71. a = 'Address'.ljust(max_addrw),
  72. u = 'UTXOs',
  73. b = 'First',
  74. t = 'Block',
  75. B = 'Last',
  76. T = 'Block',
  77. A = ' Amount' ))
  78. for n,(addr,unspents) in enumerate(addr_data.items(),1):
  79. if unspents:
  80. Msg(fs.format(
  81. n = str(n) + ')',
  82. a = addr.fmt(width=max_addrw,color=True),
  83. u = red(str(len(unspents)).rjust(5)),
  84. b = unspents[0]['height'],
  85. t = make_timestr( blk_hdrs[unspents[0]['height']]['time'] ),
  86. B = unspents[-1]['height'],
  87. T = make_timestr( blk_hdrs[unspents[-1]['height']]['time'] ),
  88. A = proto.coin_amt(sum(u['amount'] for u in unspents)).fmt(color=True,iwidth=7,prec=8)
  89. ))
  90. else:
  91. Msg(fs.format(
  92. n = str(n) + ')',
  93. a = addr.fmt(width=max_addrw,color=True),
  94. u = ' -',
  95. b = '-',
  96. t = '',
  97. B = '-',
  98. T = '',
  99. A = ' -' ))
  100. async def main(req_addrs):
  101. proto = cfg._proto
  102. from mmgen.addr import CoinAddr
  103. addrs = [CoinAddr(proto,addr) for addr in req_addrs]
  104. from mmgen.rpc import rpc_init
  105. rpc = await rpc_init(cfg,ignore_wallet=True)
  106. height = await rpc.call('getblockcount')
  107. Msg(f'{proto.coin} {proto.network.upper()} [height {height}]')
  108. from mmgen.proto.btc.misc import scantxoutset
  109. res = await scantxoutset( cfg, rpc, [f'addr({addr})' for addr in addrs] )
  110. if not res['success']:
  111. die(1,'UTXO scanning failed or was interrupted')
  112. elif not res['unspents']:
  113. msg('Address has no balance' if len(addrs) == 1 else
  114. 'Addresses have no balances' )
  115. else:
  116. addr_data = {k:[] for k in addrs}
  117. if 'desc' in res['unspents'][0]:
  118. import re
  119. for unspent in sorted(res['unspents'],key=lambda x: x['height']):
  120. addr = re.match('addr\((.*?)\)',unspent['desc'])[1]
  121. addr_data[addr].append(unspent)
  122. else:
  123. from mmgen.proto.btc.tx.base import scriptPubKey2addr
  124. for unspent in sorted(res['unspents'],key=lambda x: x['height']):
  125. addr = scriptPubKey2addr( proto, unspent['scriptPubKey'] )[0]
  126. addr_data[addr].append(unspent)
  127. good_addrs = len([v for v in addr_data.values() if v])
  128. Msg('Total: {} in {} address{}'.format(
  129. proto.coin_amt(res['total_amount']).hl2(unit=True,fs='{:,}'),
  130. red(str(good_addrs)),
  131. suf(good_addrs,'es')
  132. ))
  133. blk_heights = {i['height'] for i in res['unspents']}
  134. blk_hashes = await rpc.batch_call('getblockhash', [(h,) for h in blk_heights])
  135. blk_hdrs = await rpc.batch_call('getblockheader', [(H,) for H in blk_hashes])
  136. (do_output_tabular if cfg.tabular else do_output)( proto, addr_data, dict(zip(blk_heights,blk_hdrs)) )
  137. cfg = Config( opts_data=opts_data, init_opts={'rpc_backend':'aiohttp'} )
  138. if len(cfg._args) < 1:
  139. die(1,'This command requires at least one coin address argument')
  140. try:
  141. async_run(main(cfg._args))
  142. except KeyboardInterrupt:
  143. sys.stderr.write('\n')