main_wallet.py 10 KB

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