main_addrimport.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2016 Philemon <mmgen-py@yandex.com>
  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 bitcoind tracking wallet
  20. """
  21. import time
  22. from mmgen.common import *
  23. from mmgen.addr import AddrList,KeyAddrList
  24. # In batch mode, bitcoind just rescans each address separately anyway, so make
  25. # --batch and --rescan incompatible.
  26. opts_data = {
  27. 'desc': """Import addresses (both {pnm} and non-{pnm}) into an {pnm}
  28. tracking wallet""".format(pnm=g.proj_name),
  29. 'usage':'[opts] [mmgen address file]',
  30. 'options': """
  31. -h, --help Print this help message
  32. -b, --batch Import all addresses in one RPC call.
  33. -l, --addrlist Address source is a flat list of (non-MMGen) Bitcoin addresses
  34. -k, --keyaddr-file Address source is a key-address file
  35. -q, --quiet Suppress warnings
  36. -r, --rescan Rescan the blockchain. Required if address to import is
  37. on the blockchain and has a balance. Rescanning is slow.
  38. -t, --test Simulate operation; don't actually import addresses
  39. """,
  40. 'notes': """\n
  41. This command can also be used to update the comment fields of addresses already
  42. in the tracking wallet.
  43. The --batch option cannot be used with the --rescan option.
  44. """
  45. }
  46. cmd_args = opts.init(opts_data)
  47. if len(cmd_args) == 1:
  48. infile = cmd_args[0]
  49. check_infile(infile)
  50. if opt.addrlist:
  51. lines = get_lines_from_file(
  52. infile,'non-{pnm} addresses'.format(pnm=g.proj_name),trim_comments=True)
  53. ai = AddrList(addrlist=lines)
  54. else:
  55. ai = (AddrList,KeyAddrList)[bool(opt.keyaddr_file)](infile)
  56. else:
  57. die(1,"""
  58. You must specify an {pnm} address file (or a list of non-{pnm} addresses
  59. with the '--addrlist' option)
  60. """.strip().format(pnm=g.proj_name))
  61. from mmgen.bitcoin import verify_addr
  62. qmsg_r('Validating addresses...')
  63. for e in ai.data:
  64. if not verify_addr(e.addr,verbose=True):
  65. die(2,'%s: invalid address' % e.addr)
  66. m = (' from Seed ID %s' % ai.seed_id) if ai.seed_id else ''
  67. qmsg('OK. %s addresses%s' % (ai.num_addrs,m))
  68. if not opt.test:
  69. c = bitcoin_connection()
  70. m = """
  71. WARNING: You've chosen the '--rescan' option. Rescanning the blockchain is
  72. necessary only if an address you're importing is already on the blockchain,
  73. has a balance and is not already in your tracking wallet. Note that the
  74. rescanning process is very slow (>30 min. for each imported address on a
  75. low-powered computer).
  76. """.strip() if opt.rescan else """
  77. WARNING: If any of the addresses you're importing is already on the blockchain,
  78. has a balance and is not already in your tracking wallet, you must exit the
  79. program now and rerun it using the '--rescan' option. Otherwise you may ignore
  80. this message and continue.
  81. """.strip()
  82. if not opt.quiet: confirm_or_exit(m, 'continue', expect='YES')
  83. err_flag = False
  84. def import_address(addr,label,rescan):
  85. try:
  86. if not opt.test:
  87. c.importaddress(addr,label,rescan,timeout=(False,3600)[rescan])
  88. except:
  89. global err_flag
  90. err_flag = True
  91. w_n_of_m = len(str(ai.num_addrs)) * 2 + 2
  92. w_mmid = '' if opt.addrlist else len(str(max(ai.idxs()))) + 12
  93. if opt.rescan:
  94. import threading
  95. msg_fmt = '\r%s %-{}s %-34s %s'.format(w_n_of_m)
  96. else:
  97. msg_fmt = '\r%-{}s %-34s %s'.format(w_n_of_m, w_mmid)
  98. msg("Importing %s addresses from '%s'%s" %
  99. (len(ai.data),infile,('',' (batch mode)')[bool(opt.batch)]))
  100. arg_list = []
  101. for n,e in enumerate(ai.data):
  102. if e.idx:
  103. label = '%s:%s' % (ai.seed_id,e.idx)
  104. if e.label: label += ' ' + e.label
  105. m = label
  106. else:
  107. label = 'btc:{}'.format(e.addr)
  108. m = 'non-'+g.proj_name
  109. if opt.batch:
  110. arg_list.append((e.addr,label,False))
  111. elif opt.rescan:
  112. t = threading.Thread(target=import_address,args=[e.addr,label,True])
  113. t.daemon = True
  114. t.start()
  115. start = int(time.time())
  116. while True:
  117. if t.is_alive():
  118. elapsed = int(time.time() - start)
  119. count = '%s/%s:' % (n+1, ai.num_addrs)
  120. msg_r(msg_fmt % (secs_to_hms(elapsed),count,e.addr,'(%s)' % m))
  121. time.sleep(1)
  122. else:
  123. if err_flag: die(2,'\nImport failed')
  124. msg('\nOK')
  125. break
  126. else:
  127. import_address(e.addr,label,False)
  128. count = '%s/%s:' % (n+1, ai.num_addrs)
  129. msg_r(msg_fmt % (count, e.addr, '(%s)' % m))
  130. if err_flag: die(2,'\nImport failed')
  131. msg(' - OK')
  132. if opt.batch:
  133. ret = c.importaddress(arg_list,batch=True)
  134. msg('OK: %s addresses imported' % len(ret))