mmgen-txsign 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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/mnemonic 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 wallet.dat and use the '--force-wallet-dat' option.
  56. """.format(seed_ext)
  57. }
  58. short_opts = "hd:efik:qb:ms"
  59. long_opts = "help","outdir=","echo_passphrase","force_wallet_dat","info",\
  60. "keys_from_file=","quiet","from_brain=","from_mnemonic","from_seed"
  61. opts,cmd_args = process_opts(sys.argv,help_data,short_opts,long_opts)
  62. # Exits on invalid input
  63. check_opts(opts, ('outdir','from_brain'))
  64. if 'keys_from_file' in opts: check_infile(opts['keys_from_file'])
  65. if debug:
  66. print "Processed options: %s" % repr(opts)
  67. print "Cmd args: %s" % repr(cmd_args)
  68. if len(cmd_args) in (1,2):
  69. tx_file = cmd_args[0]
  70. check_infile(tx_file)
  71. else: usage(help_data)
  72. # Begin execution
  73. c = connect_to_bitcoind()
  74. tx_data = get_lines_from_file(tx_file,"transaction data")
  75. metadata,tx_hex,sig_data,inputs_data = parse_tx_data(tx_data,tx_file)
  76. if 'info' in opts:
  77. view_tx_data(c,inputs_data,tx_hex,metadata)
  78. sys.exit(0)
  79. if not 'quiet' in opts: do_license_msg()
  80. msg("Successfully opened transaction file '%s'" % tx_file)
  81. if user_confirm("View transaction data? ",default_yes=False):
  82. view_tx_data(c,inputs_data,tx_hex,metadata)
  83. def sign_transaction(tx_hex,sig_data,keys=None):
  84. from mmgen.rpc import exceptions
  85. try:
  86. sig_tx = c.signrawtransaction(tx_hex,sig_data,keys)
  87. except exceptions.InvalidAddressOrKey:
  88. msg("Invalid address or key")
  89. sys.exit(3)
  90. # except:
  91. # msg("Failed to sign transaction")
  92. # sys.exit(3)
  93. return sig_tx
  94. # Are inputs mmgen addresses?
  95. infile,mmgen_addrs,other_addrs = "",[],[]
  96. for i in inputs_data:
  97. if verify_mmgen_label(i['account']):
  98. mmgen_addrs.append(i)
  99. else:
  100. other_addrs.append(i)
  101. if mmgen_addrs and not 'force_wallet_dat' in opts:
  102. # Check that all the seed IDs are the same:
  103. a_ids = list(set([i['account'][:8] for i in mmgen_addrs]))
  104. if len(a_ids) != 1:
  105. msg("Addresses come from different seeds! (%s)" % " ".join(a_ids))
  106. sys.exit(3)
  107. if len(cmd_args) == 2:
  108. infile = cmd_args[1]
  109. elif "from_brain" in opts or "from_mnemonic" in opts or "from_seed" in opts:
  110. infile = ""
  111. else:
  112. msg("Inputs contain mmgen addresses. An MMGen wallet file must be specified on the command line (or use the '-b', '-m' or '-s' options).".strip())
  113. sys.exit(2)
  114. seed = get_seed(infile,opts)
  115. seed_id = make_chksum_8(seed)
  116. if seed_id != a_ids[0]:
  117. msg("Seed ID of wallet (%s) doesn't match that of addresses (%s)"
  118. % (seed_id,a_ids[0]))
  119. sys.exit(3)
  120. addr_nums = [int(i['account'].split()[0][9:]) for i in mmgen_addrs]
  121. from mmgen.addr import generate_addrs
  122. o = {'no_addresses': True, 'gen_what': "keys"}
  123. keys = [i['wif'] for i in generate_addrs(seed, addr_nums, o)]
  124. if other_addrs:
  125. if 'keys_from_file' in opts:
  126. keys += get_lines_from_file(opts['keys_from_file'],
  127. "additional key data")
  128. else:
  129. msg("""
  130. A key file must be supplied (option '-f') for the following non-mmgen
  131. address%s: %s""" % (
  132. "" if len(other_addrs) == 1 else "es",
  133. " ".join([i['address'] for i in other_addrs])
  134. ))
  135. sys.exit(2)
  136. sig_tx = sign_transaction(tx_hex,sig_data,keys)
  137. elif 'keys_from_file' in opts:
  138. keys = get_lines_from_file(opts['keys_from_file'],"key data")
  139. sig_tx = sign_transaction(tx_hex,sig_data,keys)
  140. else:
  141. prompt = "Enter passphrase for bitcoind wallet: "
  142. if 'echo_passphrase' in opts:
  143. password = my_raw_input(prompt)
  144. else:
  145. password = my_getpass(prompt)
  146. wallet_enc = True
  147. from mmgen.rpc import exceptions
  148. try:
  149. c.walletpassphrase(password, 9999)
  150. except exceptions.WalletWrongEncState:
  151. msg("Wallet is unencrypted")
  152. wallet_enc = False
  153. except exceptions.WalletPassphraseIncorrect:
  154. msg("Passphrase incorrect")
  155. sys.exit(3)
  156. except exceptions.WalletAlreadyUnlocked:
  157. msg("WARNING: Wallet already unlocked!")
  158. else:
  159. msg("Passphrase OK")
  160. sig_tx = sign_transaction(tx_hex,sig_data)
  161. if wallet_enc:
  162. c.walletlock()
  163. msg("Locking wallet")
  164. if sig_tx['complete']:
  165. msg("Signing completed")
  166. else:
  167. msg("Not all keys could be found to sign this transaction")
  168. sys.exit(3)
  169. prompt = "Save signed transaction?"
  170. if user_confirm(prompt,default_yes=True):
  171. print_signed_tx_to_file(tx_hex,sig_tx['hex'],metadata,opts)