main_addrimport.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmgen-addrimport: Import addresses into a MMGen coin daemon tracking wallet
  20. """
  21. import time
  22. from .common import *
  23. from .addrlist import AddrList,KeyAddrList
  24. from .tw.common import TwLabel
  25. ai_msgs = lambda k: {
  26. 'rescan': """
  27. WARNING: You've chosen the '--rescan' option. Rescanning the blockchain is
  28. necessary only if an address you're importing is already in the blockchain,
  29. has a balance and is not in your tracking wallet. Note that the rescanning
  30. process is very slow (>30 min. for each imported address on a low-powered
  31. computer).
  32. """.strip() if opt.rescan else """
  33. WARNING: If any of the addresses you're importing is already in the blockchain,
  34. has a balance and is not in your tracking wallet, you must exit the program now
  35. and rerun it using the '--rescan' option.
  36. """.strip(),
  37. 'bad_args': f"""
  38. You must specify an {g.proj_name} address file, a single address with the '--address'
  39. option, or a list of non-{g.proj_name} addresses with the '--addrlist' option
  40. """.strip()
  41. }[k]
  42. # In batch mode, daemon just rescans each address separately anyway, so make
  43. # --batch and --rescan incompatible.
  44. opts_data = {
  45. 'text': {
  46. 'desc': f'Import addresses into an {g.proj_name} tracking wallet',
  47. 'usage':'[opts] [mmgen address file]',
  48. 'options': """
  49. -h, --help Print this help message
  50. --, --longhelp Print help message for long options (common options)
  51. -a, --address=a Import the single coin address 'a'
  52. -b, --batch Import all addresses in one RPC call
  53. -l, --addrlist Address source is a flat list of non-MMGen coin addresses
  54. -k, --keyaddr-file Address source is a key-address file
  55. -q, --quiet Suppress warnings
  56. -r, --rescan Rescan the blockchain. Required if address to import is
  57. in the blockchain and has a balance. Rescanning is slow.
  58. -t, --token-addr=A Import addresses for ERC20 token with address 'A'
  59. """,
  60. 'notes': """\n
  61. This command can also be used to update the comment fields of addresses
  62. already in the tracking wallet.
  63. The --batch and --rescan options cannot be used together.
  64. """
  65. }
  66. }
  67. def parse_cmd_args(rpc,cmd_args):
  68. def import_mmgen_list(infile):
  69. al = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](proto,infile)
  70. if al.al_id.mmtype in ('S','B'):
  71. if not rpc.info('segwit_is_active'):
  72. die(2,'Segwit is not active on this chain. Cannot import Segwit addresses')
  73. return al
  74. if len(cmd_args) == 1:
  75. infile = cmd_args[0]
  76. from .fileutil import check_infile,get_lines_from_file
  77. check_infile(infile)
  78. if opt.addrlist:
  79. al = AddrList(
  80. proto = proto,
  81. addrlist = get_lines_from_file(infile,f'non-{g.proj_name} addresses',
  82. trim_comments = True) )
  83. else:
  84. al = import_mmgen_list(infile)
  85. elif len(cmd_args) == 0 and opt.address:
  86. al = AddrList(proto=proto,addrlist=[opt.address])
  87. infile = 'command line'
  88. else:
  89. die(1,ai_msgs('bad_args'))
  90. return al,infile
  91. def check_opts(tw):
  92. batch = bool(opt.batch)
  93. rescan = bool(opt.rescan)
  94. if rescan and not 'rescan' in tw.caps:
  95. msg(f"'--rescan' ignored: not supported by {type(tw).__name__}")
  96. rescan = False
  97. if rescan and not opt.quiet:
  98. confirm_or_raise(
  99. message = ai_msgs('rescan'),
  100. action = 'continue',
  101. expect = 'YES' )
  102. if batch and not 'batch' in tw.caps:
  103. msg(f"'--batch' ignored: not supported by {type(tw).__name__}")
  104. batch = False
  105. return batch,rescan
  106. async def import_addr(tw,addr,label,rescan,msg_fmt,msg_args):
  107. try:
  108. task = asyncio.create_task(tw.import_address(addr,label,rescan))
  109. if rescan:
  110. start = time.time()
  111. while True:
  112. if task.done():
  113. break
  114. msg_r(('\r{} '+msg_fmt).format(
  115. secs_to_hms(int(time.time()-start)),
  116. *msg_args ))
  117. await asyncio.sleep(0.5)
  118. await task
  119. msg('\nOK')
  120. else:
  121. await task
  122. qmsg(msg_fmt.format(*msg_args) + ' - OK')
  123. except Exception as e:
  124. die(2,f'\nImport of address {addr!r} failed: {e.args[0]!r}')
  125. def make_args_list(tw,al,batch,rescan):
  126. fs = '{:%s} {:34} {:%s}' % (
  127. len(str(al.num_addrs)) * 2 + 2,
  128. 1 if opt.addrlist or opt.address else len(str(max(al.idxs()))) + 13 )
  129. for num,e in enumerate(al.data,1):
  130. if e.idx:
  131. label = f'{al.al_id}:{e.idx}' + (' ' + e.label if e.label else '')
  132. add_msg = label
  133. else:
  134. label = f'{proto.base_coin.lower()}:{e.addr}'
  135. add_msg = 'non-'+g.proj_name
  136. if batch:
  137. yield (e.addr,TwLabel(proto,label),False)
  138. else:
  139. msg_args = ( f'{num}/{al.num_addrs}:', e.addr, '('+add_msg+')' )
  140. yield (tw,e.addr,TwLabel(proto,label),rescan,fs,msg_args)
  141. async def main():
  142. from .tw.ctl import TrackingWallet
  143. if opt.token_addr:
  144. proto.tokensym = 'foo' # hack to trigger 'Token' in base_proto_tw_subclass()
  145. tw = await TrackingWallet(
  146. proto = proto,
  147. token_addr = opt.token_addr,
  148. mode = 'i' )
  149. if opt.token or opt.token_addr:
  150. msg(f'Importing for token {tw.token.hl()} ({tw.token.hlc(proto.tokensym)})')
  151. from .rpc import rpc_init
  152. tw.rpc = await rpc_init(proto)
  153. al,infile = parse_cmd_args(tw.rpc,cmd_args)
  154. qmsg(
  155. f'OK. {al.num_addrs} addresses'
  156. + (f' from Seed ID {al.al_id.sid}' if hasattr(al.al_id,'sid') else '') )
  157. msg(
  158. f'Importing {len(al.data)} address{suf(al.data,"es")} from {infile}'
  159. + (' (batch mode)' if opt.batch else '') )
  160. batch,rescan = check_opts(tw)
  161. args_list = make_args_list(tw,al,batch,rescan)
  162. if batch:
  163. ret = await tw.batch_import_address(list(args_list))
  164. msg(f'OK: {len(ret)} addresses imported')
  165. elif rescan:
  166. for arg_list in args_list:
  167. await import_addr(*arg_list)
  168. else:
  169. tasks = [import_addr(*arg_list) for arg_list in args_list]
  170. await asyncio.gather(*tasks)
  171. msg('OK')
  172. del tw
  173. cmd_args = opts.init(opts_data)
  174. from .protocol import init_proto_from_opts
  175. proto = init_proto_from_opts()
  176. import asyncio
  177. run_session(main())