main_wallet.py 10.0 KB

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