mmgen-addrgen 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C) 2013-2014 by 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-addrgen: Generate a list or range of addresses from a mmgen
  20. deterministic wallet.
  21. Call as 'btc-keygen' to allow key generation.
  22. """
  23. import sys
  24. import mmgen.config as g
  25. from mmgen.Opts import *
  26. from mmgen.license import *
  27. from mmgen.util import *
  28. from mmgen.crypto import *
  29. from mmgen.addr import *
  30. from mmgen.tx import make_addr_data_chksum
  31. what = "keys" if sys.argv[0].split("-")[-1] == "keygen" else "addresses"
  32. help_data = {
  33. 'prog_name': g.prog_name,
  34. 'desc': """Generate a list or range of {} from an {g.proj_name} wallet,
  35. mnemonic, seed or password""".format(what,g=g),
  36. 'usage':"[opts] [infile] <address list>",
  37. 'options': """
  38. -h, --help Print this help message{}
  39. -d, --outdir= d Specify an alternate directory 'd' for output
  40. -c, --save-checksum Save address list checksum to file
  41. -e, --echo-passphrase Echo passphrase or mnemonic to screen upon entry{}
  42. -H, --show-hash-presets Show information on available hash presets
  43. -K, --no-keyconv Use internal libraries for address generation
  44. instead of 'keyconv'
  45. -l, --seed-len= N Length of seed. Options: {seed_lens}
  46. (default: {g.seed_len})
  47. -p, --hash-preset= p Use scrypt.hash() parameters from preset 'p' when
  48. hashing password (default: '{g.hash_preset}')
  49. -P, --passwd-file= f Get passphrase from file 'f'
  50. -q, --quiet Suppress warnings; overwrite files without
  51. prompting
  52. -S, --stdout Print {what} to stdout
  53. -v, --verbose Produce more verbose output{}
  54. -b, --from-brain= l,p Generate {what} from a user-created password,
  55. i.e. a "brainwallet", using seed length 'l' and
  56. hash preset 'p' (comma-separated)
  57. -g, --from-incog Generate {what} from an incognito wallet
  58. -X, --from-incog-hex Generate {what} from incognito hexadecimal wallet
  59. -G, --from-incog-hidden=f,o,l Generate {what} from incognito data in file
  60. 'f' at offset 'o', with seed length of 'l'
  61. -m, --from-mnemonic Generate {what} from an electrum-like mnemonic
  62. -s, --from-seed Generate {what} from a seed in .{g.seed_ext} format
  63. """.format(
  64. *(
  65. (
  66. "\n-A, --no-addresses Print only secret keys, no addresses",
  67. "\n-f, --flat-list Produce a flat list of keys suitable for use with" +
  68. "\n '{}-txsign'".format(g.proj_name.lower()),
  69. "\n-x, --b16 Print secret keys in hexadecimal too"
  70. )
  71. if what == "keys" else ("","","")),
  72. seed_lens=", ".join([str(i) for i in g.seed_lens]),
  73. what=what, g=g
  74. ),
  75. 'notes': """
  76. Addresses are given in a comma-separated list. Hyphen-separated ranges are
  77. also allowed.{}
  78. If available, the external 'keyconv' program will be used for address
  79. generation.
  80. Data for the --from-<what> options will be taken from <infile> if <infile>
  81. is specified. Otherwise, the user will be prompted to enter the data.
  82. For passphrases all combinations of whitespace are equal, and leading and
  83. trailing space are ignored. This permits reading passphrase data from a
  84. multi-line file with free spacing and indentation. This is particularly
  85. convenient for long brainwallet passphrases, for example.
  86. BRAINWALLET NOTE:
  87. As brainwallets require especially strong hashing to thwart dictionary
  88. attacks, the brainwallet hash preset must be specified by the user, using
  89. the 'p' parameter of the '--from-brain' option
  90. The '--from-brain' option also requires the user to specify a seed length
  91. (the 'l' parameter)
  92. For a brainwallet passphrase to always generate the same keys and addresses,
  93. the same 'l' and 'p' parameters to '--from-brain' must be used in all future
  94. invocations with that passphrase
  95. """.format("\n\nBy default, both addresses and secret keys are generated."
  96. if what == "keys" else "")
  97. }
  98. opts,cmd_args = parse_opts(sys.argv,help_data)
  99. if 'show_hash_presets' in opts: show_hash_presets()
  100. if 'verbose' in opts: g.verbose = True
  101. if 'quiet' in opts: g.quiet = True
  102. if 'from_incog_hex' in opts or 'from_incog_hidden' in opts:
  103. opts['from_incog'] = True
  104. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  105. if len(cmd_args) == 1 and (
  106. 'from_mnemonic' in opts
  107. or 'from_brain' in opts
  108. or 'from_seed' in opts
  109. or 'from_incog_hidden' in opts
  110. ):
  111. infile,addr_idx_arg = "",cmd_args[0]
  112. elif len(cmd_args) == 2:
  113. infile,addr_idx_arg = cmd_args
  114. check_infile(infile)
  115. else: usage(help_data)
  116. addr_idxs = parse_address_list(addr_idx_arg)
  117. if not addr_idxs: sys.exit(2)
  118. do_license_msg()
  119. # Interact with user:
  120. if what == "keys" and not g.quiet:
  121. confirm_or_exit(cmessages['unencrypted_secret_keys'], 'continue')
  122. # Generate data:
  123. seed = get_seed_retry(infile,opts)
  124. seed_id = make_chksum_8(seed)
  125. for l in (
  126. ('flat_list', 'no_addresses'),
  127. ('flat_list', 'b16'),
  128. ): warn_incompatible_opts(opts,l)
  129. opts['gen_what'] = \
  130. ("addrs") if what == "addresses" else (
  131. ("keys") if 'no_addresses' in opts else ("addrs","keys"))
  132. addr_data = generate_addrs(seed, addr_idxs, opts)
  133. addr_data_chksum = make_addr_data_chksum([(a.num,a.addr)
  134. for a in addr_data]) if 'addrs' in opts['gen_what'] else ""
  135. addr_data_str = format_addr_data(
  136. addr_data, addr_data_chksum, seed_id, addr_idxs, opts)
  137. outfile_base = "{}[{}]".format(seed_id, fmt_addr_idxs(addr_idxs))
  138. if 'flat_list' in opts:
  139. confirm = False if g.quiet else True
  140. outfile = "%s.%s" % (outfile_base,g.keylist_ext)
  141. if (user_confirm("Encrypt key list?")):
  142. enc_data = mmgen_encrypt(addr_data_str,"",opts)
  143. outfile += "."+g.mmenc_ext
  144. write_to_file(outfile,enc_data,opts,"encrypted key list",confirm,True)
  145. else:
  146. write_to_file(outfile,addr_data_str,opts,"key list",confirm,True)
  147. sys.exit()
  148. # Output data:
  149. if 'stdout' in opts:
  150. confirm = True if (what == "keys" and not g.quiet) else False
  151. write_to_stdout(addr_data_str,what,confirm)
  152. elif not sys.stdout.isatty():
  153. write_to_stdout(addr_data_str,what,confirm=False)
  154. else:
  155. confirm = False if g.quiet else True
  156. outfile = outfile_base + "." + (
  157. g.keylist_ext if 'flat_list' in opts else (
  158. g.keyfile_ext if opts['gen_what'] == ("keys") else (
  159. g.addrfile_ext if opts['gen_what'] == ("addrs") else "akeys")))
  160. write_to_file(outfile,addr_data_str,opts,what,confirm,True)
  161. if 'addrs' in opts['gen_what']:
  162. msg("Checksum for address data {}: {}".format(outfile_base,addr_data_chksum))
  163. if 'save_checksum' in opts:
  164. a = "address data checksum"
  165. write_to_file(outfile_base+".chk",addr_data_chksum,opts,a,confirm,True)
  166. else:
  167. qmsg("This checksum will be used to verify the address file in the future.")
  168. qmsg("Record it to a safe location.")