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