mmgen-txsign 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. -i, --info Display information about the transaction and exit
  37. -I, --tx_id Display transaction ID and exit
  38. -k, --keys-from-file k Provide additional key data from file 'k'
  39. -P, --passwd-file f Get passphrase from file 'f'
  40. -q, --quiet Suppress warnings; overwrite files without
  41. prompting
  42. -b, --from-brain l,p Generate keys from a user-created password,
  43. i.e. a "brainwallet", using seed length 'l' and
  44. hash preset 'p' (comma-separated)
  45. -m, --from-mnemonic Generate keys from an electrum-like mnemonic
  46. -s, --from-seed Generate keys from a seed in .{} format
  47. -w, --use-wallet-dat Use the keys in the bitcoind wallet.dat file too
  48. Transactions with either mmgen or non-mmgen input addresses may be signed.
  49. For non-mmgen inputs, the bitcoind wallet.dat is used as the key source.
  50. For mmgen inputs, key data is generated from your seed as with the
  51. mmgen-addrgen and mmgen-keygen utilities.
  52. Data for the --from-<what> options will be taken from a file if a second
  53. file is specified on the command line. Otherwise, the user will be
  54. prompted to enter the data.
  55. In cases of transactions with mixed mmgen and non-mmgen inputs, non-mmgen
  56. keys must be supplied in a separate file (WIF format, one key per line)
  57. using the '--keys-from-file' option. Alternatively, one may import the
  58. required mmgen keys into the bitcoind wallet.dat and use the
  59. '--force-wallet-dat' option.
  60. Seed data supplied in files must have the following extensions:
  61. wallet: '.{}'
  62. seed: '.{}'
  63. mnemonic: '.{}'
  64. brainwallet: '.{}'
  65. """.format(seed_ext,wallet_ext,seed_ext,mn_ext,brain_ext)
  66. }
  67. short_opts = "hd:eiIk:P:qb:msw"
  68. long_opts = "help","outdir=","echo_passphrase","info","tx_id",\
  69. "keys_from_file=","passwd_file=","quiet","from_brain=",\
  70. "from_mnemonic","from_seed","use_wallet_dat"
  71. opts,infiles = process_opts(sys.argv,help_data,short_opts,long_opts)
  72. # Exits on invalid input
  73. check_opts(opts, ('outdir','from_brain'))
  74. if 'keys_from_file' in opts: check_infile(opts['keys_from_file'])
  75. if not infiles: usage(help_data)
  76. for i in infiles: check_infile(i)
  77. def get_keys_for_mmgen_addrs(mmgen_addrs,infiles):
  78. seed_ids = list(set([i['account'][:8] for i in mmgen_addrs]))
  79. seed_ids_save = seed_ids[0:]
  80. keys = []
  81. while seed_ids:
  82. infile = False
  83. if infiles:
  84. infile = infiles.pop()
  85. seed = get_seed(infile,opts)
  86. elif "from_brain" in opts or "from_mnemonic" in opts or "from_seed" in opts:
  87. msg("Need data for seed ID %s" % seed_ids[0])
  88. seed = get_seed_retry("",opts)
  89. else:
  90. b,p,v = ("A seed","","is") if len(seed_ids) == 1 else ("Seed","s","are")
  91. msg("ERROR: %s source%s %s required for the following seed ID%s: %s" %
  92. (b,p,v,p," ".join(seed_ids)))
  93. sys.exit(2)
  94. seed_id = make_chksum_8(seed)
  95. if seed_id in seed_ids:
  96. seed_ids.remove(seed_id)
  97. seed_id_addrs = [
  98. int(i['account'].split()[0][9:]) for i in mmgen_addrs
  99. if i['account'][:8] == seed_id]
  100. from mmgen.addr import generate_keys
  101. keys += [i['wif'] for i in generate_keys(seed, seed_id_addrs)]
  102. else:
  103. if seed_id in seed_ids_save:
  104. msg_r("Ignoring duplicate seed source")
  105. if infile: msg(" '%s'" % infile)
  106. else: msg(" for ID %s" % seed_id)
  107. else:
  108. msg("Seed source produced an invalid seed ID (%s)" % seed_id)
  109. if infile:
  110. msg("Invalid input file: %s" % infile)
  111. sys.exit(2)
  112. return keys
  113. def sign_tx_with_bitcoind_wallet(c,tx_hex,sig_data,keys):
  114. try:
  115. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  116. except:
  117. from mmgen.rpc import exceptions
  118. msg("Using keys in wallet.dat as per user request")
  119. prompt = "Enter passphrase for bitcoind wallet: "
  120. while True:
  121. passwd = get_bitcoind_passphrase(prompt,opts)
  122. try:
  123. c.walletpassphrase(passwd, 9999)
  124. except exceptions.WalletPassphraseIncorrect:
  125. msg("Passphrase incorrect")
  126. else:
  127. msg("Passphrase OK"); break
  128. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  129. msg("Locking wallet")
  130. try:
  131. c.walletlock()
  132. except:
  133. msg("Failed to lock wallet")
  134. return sig_tx
  135. def missing_keys_errormsg(other_addrs):
  136. msg("""
  137. A key file (option '-f') or wallet.dat (option '-w') must be supplied
  138. for the following non-mmgen address%s: %s""" %
  139. ("" if len(other_addrs) == 1 else "es",
  140. " ".join([i['address'] for i in other_addrs])
  141. ))
  142. # Begin execution
  143. c = connect_to_bitcoind()
  144. tx_file = infiles.pop(0)
  145. m = "" if 'tx_id' in opts else "transaction data"
  146. tx_data = get_lines_from_file(tx_file,m)
  147. metadata,tx_hex,sig_data,inputs_data = parse_tx_data(tx_data,tx_file)
  148. if 'tx_id' in opts:
  149. msg(metadata[0])
  150. sys.exit(0)
  151. if 'info' in opts:
  152. view_tx_data(c,inputs_data,tx_hex,metadata)
  153. sys.exit(0)
  154. if not 'quiet' in opts: do_license_msg()
  155. msg("Successfully opened transaction file '%s'" % tx_file)
  156. if user_confirm("View transaction data? ",default_yes=False):
  157. view_tx_data(c,inputs_data,tx_hex,metadata)
  158. # Are inputs mmgen addresses?
  159. mmgen_addrs,other_addrs = [],[]
  160. for i in inputs_data:
  161. if verify_mmgen_label(i['account']):
  162. mmgen_addrs.append(i)
  163. else:
  164. other_addrs.append(i)
  165. if 'keys_from_file' in opts:
  166. keys = get_lines_from_file(opts['keys_from_file'],"key data")
  167. else:
  168. keys = []
  169. if mmgen_addrs:
  170. if other_addrs and not keys and not 'use_wallet_dat' in opts:
  171. missing_keys_errormsg(other_addrs)
  172. sys.exit(2)
  173. keys += get_keys_for_mmgen_addrs(mmgen_addrs,infiles)
  174. if 'use_wallet_dat' in opts:
  175. sig_tx = sign_tx_with_bitcoind_wallet(c,tx_hex,sig_data,keys)
  176. else:
  177. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  178. elif other_addrs:
  179. if 'use_wallet_dat' in opts:
  180. sig_tx = sign_tx_with_bitcoind_wallet(c,tx_hex,sig_data,keys)
  181. else:
  182. if keys:
  183. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  184. else:
  185. missing_keys_errormsg(other_addrs)
  186. sys.exit(2)
  187. if sig_tx['complete']:
  188. msg("Signing completed")
  189. prompt = "Save signed transaction?"
  190. if user_confirm(prompt,default_yes=True):
  191. print_signed_tx_to_file(tx_hex,sig_tx['hex'],metadata,opts)
  192. else:
  193. msg("Some keys were missing. Transaction could not be signed.")
  194. sys.exit(3)