mmgen-txsign 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C) 2013 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-txsign: Sign a Bitcoin transaction generated by mmgen-txcreate
  20. """
  21. import sys
  22. #from hashlib import sha256
  23. from mmgen.Opts import *
  24. from mmgen.license import *
  25. from mmgen.config import *
  26. from mmgen.tx import *
  27. from mmgen.utils import *
  28. help_data = {
  29. 'prog_name': sys.argv[0].split("/")[-1],
  30. 'desc': "Sign a Bitcoin transaction generated by mmgen-txcreate",
  31. 'usage': "[opts] <transaction file> [mmgen wallet/seed/words/brain file]...",
  32. 'options': """
  33. -h, --help Print this help message
  34. -d, --outdir d Specify an alternate directory 'd' for output
  35. -e, --echo-passphrase Print passphrase to screen when typing it
  36. -f, --force-wallet-dat Force the use of wallet.dat as a key source
  37. -i, --info Display information about the transaction and exit
  38. -k, --keys-from-file k Provide additional key data from file 'k'
  39. -q, --quiet Suppress warnings; overwrite files without asking
  40. -b, --from-brain l,p Generate keys from a user-created password,
  41. i.e. a "brainwallet", using seed length 'l' and
  42. hash preset 'p' (comma-separated)
  43. -m, --from-mnemonic Generate keys from an electrum-like mnemonic
  44. -s, --from-seed Generate keys from a seed in .{} format
  45. Transactions with either mmgen or non-mmgen input addresses may be signed.
  46. For non-mmgen inputs, the bitcoind wallet.dat is used as the key source.
  47. For mmgen inputs, key data is generated from your seed as with the
  48. mmgen-addrgen and mmgen-keygen utilities.
  49. Data for the --from-<what> options will be taken from a file if a second
  50. file is specified on the command line. Otherwise, the user will be
  51. prompted to enter the data.
  52. In cases of transactions with mixed mmgen and non-mmgen inputs, non-mmgen
  53. keys must be supplied in a separate file (WIF format, one key per line)
  54. using the '--keys-from-file' option. Alternatively, one may import the
  55. required mmgen keys into the bitcoind wallet.dat and use the
  56. '--force-wallet-dat' option.
  57. Seed data supplied in files must have the following extensions:
  58. wallet: '.{}'
  59. seed: '.{}'
  60. mnemonic: '.{}'
  61. brainwallet: '.{}'
  62. """.format(seed_ext,wallet_ext,seed_ext,mn_ext,brain_ext)
  63. }
  64. short_opts = "hd:efik:qb:ms"
  65. long_opts = "help","outdir=","echo_passphrase","force_wallet_dat","info",\
  66. "keys_from_file=","quiet","from_brain=","from_mnemonic","from_seed"
  67. opts,infiles = process_opts(sys.argv,help_data,short_opts,long_opts)
  68. # Exits on invalid input
  69. check_opts(opts, ('outdir','from_brain'))
  70. if 'keys_from_file' in opts: check_infile(opts['keys_from_file'])
  71. if not infiles: usage(help_data)
  72. for i in infiles: check_infile(i)
  73. # Begin execution
  74. c = connect_to_bitcoind()
  75. tx_file = infiles.pop(0)
  76. tx_data = get_lines_from_file(tx_file,"transaction data")
  77. metadata,tx_hex,sig_data,inputs_data = parse_tx_data(tx_data,tx_file)
  78. if 'info' in opts:
  79. view_tx_data(c,inputs_data,tx_hex,metadata)
  80. sys.exit(0)
  81. if not 'quiet' in opts: do_license_msg()
  82. msg("Successfully opened transaction file '%s'" % tx_file)
  83. if user_confirm("View transaction data? ",default_yes=False):
  84. view_tx_data(c,inputs_data,tx_hex,metadata)
  85. # Are inputs mmgen addresses?
  86. mmgen_addrs,other_addrs,keys = [],[],[]
  87. for i in inputs_data:
  88. if verify_mmgen_label(i['account']):
  89. mmgen_addrs.append(i)
  90. else:
  91. other_addrs.append(i)
  92. if mmgen_addrs and not 'force_wallet_dat' in opts:
  93. # Check that all the seed IDs are the same:
  94. seed_ids = list(set([i['account'][:8] for i in mmgen_addrs]))
  95. ext_data = (
  96. (wallet_ext, {}),
  97. (mn_ext, {"from_mnemonic":True}),
  98. (seed_ext, {"from_seed": True}),
  99. (brain_ext, opts)
  100. )
  101. while seed_ids:
  102. infile = False
  103. if infiles:
  104. infile = infiles.pop()
  105. ext = infile.split(".")[-1]
  106. for e,o in ext_data:
  107. if e == ext:
  108. if e == brain_ext:
  109. if "from_brain" not in opts:
  110. msg(
  111. "'--from-brain' option must be specified for brainwallet file")
  112. sys.exit(2)
  113. seed = get_seed_retry(infile,o); break
  114. else:
  115. msg("Invalid file extension: '.%s'\nValid extensions: '.%s'" %
  116. (ext,"' '.".join([i[0] for i in ext_data])))
  117. sys.exit(2)
  118. elif "from_brain" in opts or "from_mnemonic" in opts or "from_seed" in opts:
  119. msg("Need data for seed ID %s" % seed_ids[0])
  120. seed = get_seed_retry("",opts)
  121. else:
  122. b,p,v = ("A seed","","is") if len(seed_ids) == 1 else ("Seed","s","are")
  123. msg("ERROR: %s source%s %s required for the following seed ID%s: %s" %
  124. (b,p,v,p," ".join(seed_ids)))
  125. sys.exit(2)
  126. seed_id = make_chksum_8(seed)
  127. if seed_id in seed_ids:
  128. seed_ids.remove(seed_id)
  129. seed_id_addrs = [
  130. int(i['account'].split()[0][9:]) for i in mmgen_addrs
  131. if i['account'][:8] == seed_id]
  132. from mmgen.addr import generate_keys
  133. keys += [i['wif'] for i in generate_keys(seed, seed_id_addrs)]
  134. else:
  135. msg("Seed source produced an invalid seed ID (%s)" % seed_id)
  136. if infile:
  137. msg("Invalid input file: %s" % infile)
  138. sys.exit(2)
  139. if other_addrs:
  140. if 'keys_from_file' in opts:
  141. keys += get_lines_from_file(opts['keys_from_file'],
  142. "additional key data")
  143. else:
  144. msg("""
  145. A key file must be supplied (option '-f') for the following non-mmgen
  146. address%s: %s""" % (
  147. "" if len(other_addrs) == 1 else "es",
  148. " ".join([i['address'] for i in other_addrs])
  149. ))
  150. sys.exit(2)
  151. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  152. elif 'keys_from_file' in opts:
  153. keys = get_lines_from_file(opts['keys_from_file'],"key data")
  154. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  155. else:
  156. prompt = "Enter passphrase for bitcoind wallet: "
  157. if 'echo_passphrase' in opts:
  158. password = my_raw_input(prompt)
  159. else:
  160. password = my_getpass(prompt)
  161. wallet_enc = True
  162. from mmgen.rpc import exceptions
  163. try:
  164. c.walletpassphrase(password, 9999)
  165. except exceptions.WalletWrongEncState:
  166. msg("Wallet is unencrypted")
  167. wallet_enc = False
  168. except exceptions.WalletPassphraseIncorrect:
  169. msg("Passphrase incorrect")
  170. sys.exit(3)
  171. except exceptions.WalletAlreadyUnlocked:
  172. msg("WARNING: Wallet already unlocked!")
  173. else:
  174. msg("Passphrase OK")
  175. sig_tx = sign_transaction(c,tx_hex,sig_data)
  176. if wallet_enc:
  177. c.walletlock()
  178. msg("Locking wallet")
  179. if sig_tx['complete']:
  180. msg("Signing completed")
  181. else:
  182. msg("Some keys were missing. Transaction could not be signed.")
  183. sys.exit(3)
  184. prompt = "Save signed transaction?"
  185. if user_confirm(prompt,default_yes=True):
  186. print_signed_tx_to_file(tx_hex,sig_tx['hex'],metadata,opts)