main_wallet.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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/main_wallet: Entry point for MMGen wallet-related scripts
  20. """
  21. import os
  22. from .common import *
  23. from .wallet import Wallet,MMGenWallet
  24. from .filename import find_file_in_dir
  25. usage = '[opts] [infile]'
  26. nargs = 1
  27. iaction = 'convert'
  28. oaction = 'convert'
  29. do_bw_note = True
  30. do_sw_note = False
  31. do_ss_note = False
  32. invoked_as = {
  33. 'mmgen-walletgen': 'gen',
  34. 'mmgen-walletconv': 'conv',
  35. 'mmgen-walletchk': 'chk',
  36. 'mmgen-passchg': 'passchg',
  37. 'mmgen-subwalletgen': 'subgen',
  38. 'mmgen-seedsplit': 'seedsplit',
  39. }[g.prog_name]
  40. dsw = f'the default or specified {g.proj_name} wallet'
  41. # full: defhHiJkKlLmoOpPqrSvz-
  42. if invoked_as == 'gen':
  43. desc = f'Generate an {g.proj_name} wallet from a random seed'
  44. opt_filter = 'ehdoJlLpPqrSvz-'
  45. usage = '[opts]'
  46. oaction = 'output'
  47. nargs = 0
  48. elif invoked_as == 'conv':
  49. desc = 'Convert ' + dsw + ' from one format to another'
  50. opt_filter = 'dehHiJkKlLmoOpPqrSvz-'
  51. elif invoked_as == 'chk':
  52. desc = 'Check validity of ' + dsw
  53. opt_filter = 'ehiHOlpPqrvz-'
  54. iaction = 'input'
  55. elif invoked_as == 'passchg':
  56. desc = 'Change the passphrase, hash preset or label of ' + dsw
  57. opt_filter = 'efhdiHkKOlLmpPqrSvz-'
  58. iaction = 'input'
  59. do_bw_note = False
  60. elif invoked_as == 'subgen':
  61. desc = 'Generate a subwallet from ' + dsw
  62. opt_filter = 'dehHiJkKlLmoOpPqrSvz-' # omitted: f
  63. usage = '[opts] [infile] <Subseed Index>'
  64. iaction = 'input'
  65. oaction = 'output'
  66. do_sw_note = True
  67. elif invoked_as == 'seedsplit':
  68. desc = 'Generate a seed share from ' + dsw
  69. opt_filter = 'dehHiJlLMIoOpPqrSvz-'
  70. usage = '[opts] [infile] [<Split ID String>:]<index>:<share count>'
  71. iaction = 'input'
  72. oaction = 'output'
  73. do_ss_note = True
  74. opts_data = {
  75. 'text': {
  76. 'desc': desc,
  77. 'usage': usage,
  78. 'options': """
  79. -h, --help Print this help message
  80. --, --longhelp Print help message for long options (common options)
  81. -d, --outdir= d Output files to directory 'd' instead of working dir
  82. -e, --echo-passphrase Echo passphrases and other user input to screen
  83. -f, --force-update Force update of wallet even if nothing has changed
  84. -i, --in-fmt= f {iaction} from wallet format 'f' (see FMT CODES below)
  85. -o, --out-fmt= f {oaction} to wallet format 'f' (see FMT CODES below)
  86. -H, --hidden-incog-input-params=f,o Read hidden incognito data from file
  87. 'f' at offset 'o' (comma-separated)
  88. -J, --hidden-incog-output-params=f,o Write hidden incognito data to file
  89. 'f' at offset 'o' (comma-separated). File 'f' will be
  90. created if necessary and filled with random data.
  91. -O, --old-incog-fmt Specify old-format incognito input
  92. -k, --keep-passphrase Reuse passphrase of input wallet for output wallet
  93. -K, --keep-hash-preset Reuse hash preset of input wallet for output wallet
  94. -l, --seed-len= l Specify wallet seed length of 'l' bits. This option
  95. is required only for brainwallet and incognito inputs
  96. with non-standard (< {dsl}-bit) seed lengths.
  97. -L, --label= l Specify a label 'l' for output wallet
  98. -m, --keep-label Reuse label of input wallet for output wallet
  99. -M, --master-share=i Use a master share with index 'i' (min:{ms_min}, max:{ms_max})
  100. -p, --hash-preset= p Use the scrypt hash parameters defined by preset 'p'
  101. for password hashing (default: '{g.dfl_hash_preset}')
  102. -z, --show-hash-presets Show information on available hash presets
  103. -P, --passwd-file= f Get wallet passphrase from file 'f'
  104. -q, --quiet Produce quieter output; suppress some warnings
  105. -r, --usr-randchars=n Get 'n' characters of additional randomness from user
  106. (min={g.min_urandchars}, max={g.max_urandchars}, default={g.usr_randchars})
  107. -S, --stdout Write wallet data to stdout instead of file
  108. -v, --verbose Produce more verbose output
  109. """,
  110. 'notes': """
  111. {n_ss}{n_sw}{n_pw}{n_bw}
  112. FMT CODES:
  113. {f}
  114. """
  115. },
  116. 'code': {
  117. 'options': lambda help_notes,s: s.format(
  118. iaction=capfirst(iaction),
  119. oaction=capfirst(oaction),
  120. ms_min=help_notes('MasterShareIdx').min_val,
  121. ms_max=help_notes('MasterShareIdx').max_val,
  122. dsl=help_notes('dfl_seed_len'),
  123. g=g,
  124. ),
  125. 'notes': lambda help_notes,s: s.format(
  126. f=help_notes('fmt_codes'),
  127. n_ss=('',help_notes('seedsplit')+'\n\n')[do_ss_note],
  128. n_sw=('',help_notes('subwallet')+'\n\n')[do_sw_note],
  129. n_pw=help_notes('passwd'),
  130. n_bw=('','\n\n'+help_notes('brainwallet'))[do_bw_note]
  131. )
  132. }
  133. }
  134. cmd_args = opts.init(opts_data,opt_filter=opt_filter)
  135. if invoked_as == 'subgen':
  136. from .subseed import SubSeedIdx
  137. ss_idx = SubSeedIdx(cmd_args.pop())
  138. elif invoked_as == 'seedsplit':
  139. from .obj import get_obj
  140. from .seedsplit import SeedSplitSpecifier,MasterShareIdx
  141. master_share = MasterShareIdx(opt.master_share) if opt.master_share else None
  142. if cmd_args:
  143. sss = get_obj(SeedSplitSpecifier,s=cmd_args.pop(),silent=True)
  144. if master_share:
  145. if not sss:
  146. sss = SeedSplitSpecifier('1:2')
  147. elif sss.idx == 1:
  148. m1 = 'Share index of 1 meaningless in master share context.'
  149. m2 = 'To generate a master share, omit the seed split specifier.'
  150. die(1,m1+' '+m2)
  151. elif not sss:
  152. opts.usage()
  153. elif master_share:
  154. sss = SeedSplitSpecifier('1:2')
  155. else:
  156. opts.usage()
  157. from .fileutil import check_infile,get_seed_file
  158. if cmd_args:
  159. if invoked_as == 'gen' or len(cmd_args) > 1:
  160. opts.usage()
  161. check_infile(cmd_args[0])
  162. sf = get_seed_file(cmd_args,nargs,invoked_as=invoked_as)
  163. if invoked_as != 'chk':
  164. do_license_msg()
  165. if invoked_as == 'gen':
  166. ss_in = None
  167. else:
  168. ss_in = Wallet(sf,passchg=(invoked_as=='passchg'))
  169. m1 = green('Processing input wallet ')
  170. m2 = ss_in.seed.sid.hl()
  171. m3 = yellow(' (default wallet)') if sf and os.path.dirname(sf) == g.data_dir else ''
  172. msg(m1+m2+m3)
  173. if invoked_as == 'chk':
  174. lbl = ss_in.ssdata.label.hl() if hasattr(ss_in.ssdata,'label') else 'NONE'
  175. vmsg(f'Wallet label: {lbl}')
  176. # TODO: display creation date
  177. sys.exit(0)
  178. if invoked_as != 'gen':
  179. gmsg_r('Processing output wallet' + ('\n',' ')[invoked_as == 'seedsplit'])
  180. if invoked_as == 'subgen':
  181. ss_out = Wallet( seed_bin = ss_in.seed.subseed(ss_idx,print_msg=True).data )
  182. elif invoked_as == 'seedsplit':
  183. shares = ss_in.seed.split(sss.count,sss.id,master_share)
  184. seed_out = shares.get_share_by_idx(sss.idx,base_seed=True)
  185. msg(seed_out.get_desc(ui=True))
  186. ss_out = Wallet(seed=seed_out)
  187. else:
  188. ss_out = Wallet(
  189. ss = ss_in,
  190. passchg = invoked_as == 'passchg' )
  191. if invoked_as == 'gen':
  192. qmsg(f"This wallet's Seed ID: {ss_out.seed.sid.hl()}")
  193. if invoked_as == 'passchg':
  194. def data_changed(attrs):
  195. for attr in attrs:
  196. if getattr(ss_out.ssdata,attr) != getattr(ss_in.ssdata,attr):
  197. return True
  198. return False
  199. if not ( opt.force_update or data_changed(('passwd','hash_preset','label')) ):
  200. die(1,'Password, hash preset and label are unchanged. Taking no action')
  201. if invoked_as == 'passchg' and ss_in.infile.dirname == g.data_dir:
  202. m1 = yellow('Confirmation of default wallet update')
  203. m2 = 'update the default wallet'
  204. confirm_or_raise(m1,m2,exit_msg='Password not changed')
  205. ss_out.write_to_file(desc='New wallet',outdir=g.data_dir)
  206. bmsg('Securely deleting old wallet')
  207. from .fileutil import shred_file
  208. shred_file(
  209. ss_in.infile.name,
  210. verbose = opt.verbose )
  211. elif (
  212. invoked_as == 'gen'
  213. and not opt.outdir
  214. and not opt.stdout
  215. and not find_file_in_dir( MMGenWallet, g.data_dir )
  216. and keypress_confirm(
  217. 'Make this wallet your default and move it to the data directory?',
  218. default_yes = True ) ):
  219. ss_out.write_to_file(outdir=g.data_dir)
  220. else:
  221. ss_out.write_to_file()
  222. if invoked_as == 'passchg':
  223. if ss_out.ssdata.passwd == ss_in.ssdata.passwd:
  224. msg('New and old passphrases are the same')
  225. else:
  226. msg('Wallet passphrase has changed')
  227. if ss_out.ssdata.hash_preset != ss_in.ssdata.hash_preset:
  228. msg(f'Hash preset has been changed to {ss_out.ssdata.hash_preset!r}')