main_addrimport.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2018 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 mmgen.common import *
  23. from mmgen.addr import AddrList,KeyAddrList
  24. from mmgen.obj 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': """
  38. You must specify an {pnm} address file, a single address with the '--address'
  39. option, or a list of non-{pnm} addresses with the '--addrlist' option
  40. """.strip().format(pnm=g.proj_name)
  41. }[k]
  42. # In batch mode, daemon just rescans each address separately anyway, so make
  43. # --batch and --rescan incompatible.
  44. opts_data = lambda: {
  45. 'desc': """Import addresses into an {} tracking wallet""".format(g.proj_name),
  46. 'usage':'[opts] [mmgen address file]',
  47. 'options': """
  48. -h, --help Print this help message
  49. --, --longhelp Print help message for long options (common options)
  50. -a, --address=a Import the single coin address 'a'
  51. -b, --batch Import all addresses in one RPC call
  52. -l, --addrlist Address source is a flat list of non-MMGen coin addresses
  53. -k, --keyaddr-file Address source is a key-address file
  54. -q, --quiet Suppress warnings
  55. -r, --rescan Rescan the blockchain. Required if address to import is
  56. in the blockchain and has a balance. Rescanning is slow.
  57. """,
  58. 'notes': """\n
  59. This command can also be used to update the comment fields of addresses
  60. already in the tracking wallet.
  61. The --batch and --rescan options cannot be used together.
  62. """
  63. }
  64. cmd_args = opts.init(opts_data)
  65. def import_mmgen_list(infile):
  66. al = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](infile)
  67. if al.al_id.mmtype in ('S','B'):
  68. from mmgen.tx import segwit_is_active
  69. if not segwit_is_active():
  70. rdie(2,'Segwit is not active on this chain. Cannot import Segwit addresses')
  71. return al
  72. rpc_init()
  73. if len(cmd_args) == 1:
  74. infile = cmd_args[0]
  75. check_infile(infile)
  76. if opt.addrlist:
  77. al = AddrList(addrlist=get_lines_from_file(
  78. infile,
  79. 'non-{pnm} addresses'.format(pnm=g.proj_name),
  80. trim_comments=True))
  81. else:
  82. al = import_mmgen_list(infile)
  83. elif len(cmd_args) == 0 and opt.address:
  84. al = AddrList(addrlist=[opt.address])
  85. infile = 'command line'
  86. else:
  87. die(1,ai_msgs('bad_args'))
  88. m = ' from Seed ID {}'.format(al.al_id.sid) if hasattr(al.al_id,'sid') else ''
  89. qmsg('OK. {} addresses{}'.format(al.num_addrs,m))
  90. err_msg = None
  91. from mmgen.tw import TrackingWallet
  92. try:
  93. tw = TrackingWallet(mode='w')
  94. except UnrecognizedTokenSymbolError as e:
  95. m1 = "Note: when importing addresses for a new token, the token must be specified"
  96. m2 = "by address, not symbol."
  97. die(1,'{}\n{}\n{}'.format(e.message,m1,m2))
  98. if opt.rescan and not 'rescan' in tw.caps:
  99. msg("'--rescan' ignored: not supported by {}".format(type(tw).__name__))
  100. opt.rescan = False
  101. if opt.rescan and not opt.quiet:
  102. confirm_or_raise(ai_msgs('rescan'),'continue',expect='YES')
  103. if opt.batch and not 'batch' in tw.caps:
  104. msg("'--batch' ignored: not supported by {}".format(type(tw).__name__))
  105. opt.batch = False
  106. def import_address(addr,label,rescan):
  107. try: tw.import_address(addr,label,rescan)
  108. except Exception as e:
  109. global err_msg
  110. err_msg = e.message
  111. w_n_of_m = len(str(al.num_addrs)) * 2 + 2
  112. w_mmid = 1 if opt.addrlist or opt.address else len(str(max(al.idxs()))) + 13
  113. msg_fmt = '{{:{}}} {{:34}} {{:{}}}'.format(w_n_of_m,w_mmid)
  114. if opt.rescan: import threading
  115. fs = u'Importing {} address{} from {}{}'
  116. bm =' (batch mode)' if opt.batch else ''
  117. msg(fs.format(len(al.data),suf(al.data,'es'),infile,bm))
  118. if not al.data[0].addr.is_for_chain(g.chain):
  119. die(2,'Address{} not compatible with {} chain!'.format((' list','')[bool(opt.address)],g.chain))
  120. for n,e in enumerate(al.data):
  121. if e.idx:
  122. label = '{}:{}'.format(al.al_id,e.idx)
  123. if e.label: label += ' ' + e.label
  124. m = label
  125. else:
  126. label = '{}:{}'.format(g.proto.base_coin.lower(),e.addr)
  127. m = 'non-'+g.proj_name
  128. label = TwLabel(label)
  129. if opt.batch:
  130. if n == 0: arg_list = []
  131. arg_list.append((e.addr,label,False))
  132. continue
  133. msg_data = ('{}/{}:'.format(n+1,al.num_addrs),e.addr,'({})'.format(m))
  134. if opt.rescan:
  135. t = threading.Thread(target=import_address,args=[e.addr,label,True])
  136. t.daemon = True
  137. t.start()
  138. start = int(time.time())
  139. while True:
  140. if t.is_alive():
  141. elapsed = int(time.time()-start)
  142. msg_r(('\r{} '+msg_fmt).format(secs_to_hms(elapsed),*msg_data))
  143. time.sleep(0.5)
  144. else:
  145. if err_msg: die(2,'\nImport failed: {!r}'.format(err_msg))
  146. msg('\nOK')
  147. break
  148. else:
  149. import_address(e.addr,label,False)
  150. msg_r('\r'+msg_fmt.format(*msg_data))
  151. if err_msg: die(2,'\nImport failed: {!r}'.format(err_msg))
  152. msg(' - OK')
  153. if opt.batch:
  154. ret = tw.batch_import_address(arg_list)
  155. msg('OK: {} addresses imported'.format(len(ret)))
  156. tw.write()