mmgen-txsign 5.9 KB

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