main_wallet.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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/main_wallet: Entry point for MMGen wallet-related scripts
  20. """
  21. import os,re
  22. from mmgen.common import *
  23. from mmgen.seed import SeedSource,Wallet
  24. from mmgen.filename import find_file_in_dir
  25. from mmgen.obj import MMGenWalletLabel
  26. bn = os.path.basename(sys.argv[0])
  27. invoked_as = re.sub(r'^wallet','',bn.split('-')[-1])
  28. usage = '[opts] [infile]'
  29. nargs = 1
  30. iaction = 'convert'
  31. oaction = 'convert'
  32. bw_note = opts.bw_note
  33. pw_note = opts.pw_note
  34. # full: defhHiJkKlLmoOpPqrSvz-
  35. if invoked_as == 'gen':
  36. desc = 'Generate an {pnm} wallet from a random seed'
  37. opt_filter = 'ehdoJlLpPqrSvz-'
  38. usage = '[opts]'
  39. oaction = 'output'
  40. nargs = 0
  41. elif invoked_as == 'conv':
  42. desc = 'Convert an {pnm} wallet from one format to another'
  43. opt_filter = 'dehHiJkKlLmoOpPqrSvz-'
  44. elif invoked_as == 'chk':
  45. desc = 'Check validity of an {pnm} wallet'
  46. opt_filter = 'ehiHOlpPqrvz-'
  47. iaction = 'input'
  48. elif invoked_as == 'passchg':
  49. desc = 'Change the passphrase, hash preset or label of an {pnm} wallet'
  50. opt_filter = 'efhdiHkKOlLmpPqrSvz-'
  51. iaction = 'input'
  52. bw_note = ''
  53. else:
  54. die(1,"'%s': unrecognized invocation" % bn)
  55. opts_data = {
  56. # Can't use: share/Opts doesn't know anything about fmt codes
  57. # 'sets': [('hidden_incog_output_params',bool,'out_fmt','hi')],
  58. 'desc': desc.format(pnm=g.proj_name),
  59. 'usage': usage,
  60. 'options': """
  61. -h, --help Print this help message
  62. --, --longhelp Print help message for long options (common options)
  63. -d, --outdir= d Output files to directory 'd' instead of working dir
  64. -e, --echo-passphrase Echo passphrases and other user input to screen
  65. -f, --force-update Force update of wallet even if nothing has changed
  66. -i, --in-fmt= f {iaction} from wallet format 'f' (see FMT CODES below)
  67. -o, --out-fmt= f {oaction} to wallet format 'f' (see FMT CODES below)
  68. -H, --hidden-incog-input-params=f,o Read hidden incognito data from file
  69. 'f' at offset 'o' (comma-separated)
  70. -J, --hidden-incog-output-params=f,o Write hidden incognito data to file 'f'
  71. at offset 'o' (comma-separated). File 'f' will be cre-
  72. ated and filled with random data if it doesn't exist.
  73. -O, --old-incog-fmt Specify old-format incognito input
  74. -k, --keep-passphrase Reuse passphrase of input wallet for output wallet
  75. -K, --keep-hash-preset Reuse hash preset of input wallet for output wallet
  76. -l, --seed-len= l Specify wallet seed length of 'l' bits. This option
  77. is required only for brainwallet and incognito inputs
  78. with non-standard (< {g.seed_len}-bit) seed lengths.
  79. -L, --label= l Specify a label 'l' for output wallet
  80. -m, --keep-label Reuse label of input wallet for output wallet
  81. -p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
  82. for password hashing (default: '{g.hash_preset}')
  83. -z, --show-hash-presets Show information on available hash presets
  84. -P, --passwd-file= f Get wallet passphrase from file 'f'
  85. -q, --quiet Produce quieter output; suppress some warnings
  86. -r, --usr-randchars=n Get 'n' characters of additional randomness from user
  87. (min={g.min_urandchars}, max={g.max_urandchars}, default={g.usr_randchars})
  88. -S, --stdout Write wallet data to stdout instead of file
  89. -v, --verbose Produce more verbose output
  90. """.format(
  91. g=g,
  92. iaction=capfirst(iaction),
  93. oaction=capfirst(oaction),
  94. ),
  95. 'notes': """
  96. {pw_note}{bw_note}
  97. FMT CODES:
  98. {f}
  99. """.format(
  100. f='\n '.join(SeedSource.format_fmt_codes().splitlines()),
  101. pw_note=pw_note,
  102. bw_note=('','\n\n' + bw_note)[bool(bw_note)]
  103. )
  104. }
  105. cmd_args = opts.init(opts_data,opt_filter=opt_filter)
  106. if opt.label:
  107. opt.label = MMGenWalletLabel(opt.label,msg="Error in option '--label'")
  108. sf = get_seed_file(cmd_args,nargs,invoked_as=invoked_as)
  109. if not invoked_as == 'chk': do_license_msg()
  110. dw_msg = ('',yellow(' (default wallet)'))[bool(sf and os.path.dirname(sf)==g.data_dir)]
  111. if invoked_as in ('conv','passchg'):
  112. msg(green('Processing input wallet')+dw_msg)
  113. ss_in = None if invoked_as == 'gen' else SeedSource(sf,passchg=(invoked_as=='passchg'))
  114. if invoked_as == 'chk': sys.exit()
  115. if invoked_as in ('conv','passchg'):
  116. msg(green('Processing output wallet'))
  117. ss_out = SeedSource(ss=ss_in,passchg=invoked_as=='passchg')
  118. if invoked_as == 'gen':
  119. qmsg("This wallet's Seed ID: %s" % ss_out.seed.sid.hl())
  120. if invoked_as == 'passchg':
  121. if not (opt.force_update or [k for k in 'passwd','hash_preset','label'
  122. if getattr(ss_out.ssdata,k) != getattr(ss_in.ssdata,k)]):
  123. die(1,'Password, hash preset and label are unchanged. Taking no action')
  124. m1 = yellow('Confirmation of default wallet update')
  125. m2 = 'update the default wallet'
  126. m3 = 'Make this wallet your default and move it to the data directory?'
  127. if invoked_as == 'passchg' and ss_in.infile.dirname == g.data_dir:
  128. confirm_or_exit(m1,m2,exit_msg='Password not changed')
  129. ss_out.write_to_file(desc='New wallet',outdir=g.data_dir)
  130. msg('Securely deleting old wallet')
  131. from subprocess import check_output,CalledProcessError
  132. sd_cmd = (['wipe','-sf'],['sdelete','-p','20'])[g.platform=='win']
  133. try:
  134. check_output(sd_cmd + [ss_in.infile.name])
  135. except:
  136. msg(yellow("WARNING: '%s' command failed, using regular file delete instead" % sd_cmd[0]))
  137. # msg('Command output: {}\nReturn value {}'.format(e.output,e.returncode))
  138. os.unlink(ss_in.infile.name)
  139. elif invoked_as == 'gen' and not find_file_in_dir(Wallet,g.data_dir) \
  140. and not opt.stdout and keypress_confirm(m3,default_yes=True):
  141. ss_out.write_to_file(outdir=g.data_dir)
  142. else:
  143. ss_out.write_to_file()
  144. if invoked_as == 'passchg':
  145. if ss_out.ssdata.passwd == ss_in.ssdata.passwd:
  146. msg('New and old passphrases are the same')
  147. else:
  148. msg('Wallet passphrase has changed')
  149. if ss_out.ssdata.hash_preset != ss_in.ssdata.hash_preset:
  150. msg("Hash preset has been changed to '{}'".format(ss_out.ssdata.hash_preset))