mmgen-txsign 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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,cmd_args = 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 debug:
  72. print "Processed options: %s" % repr(opts)
  73. print "Cmd args: %s" % repr(cmd_args)
  74. if len(cmd_args) > 0:
  75. for i in cmd_args: check_infile(i)
  76. else: usage(help_data)
  77. # Begin execution
  78. c = connect_to_bitcoind()
  79. tx_file = cmd_args.pop(0)
  80. tx_data = get_lines_from_file(tx_file,"transaction data")
  81. metadata,tx_hex,sig_data,inputs_data = parse_tx_data(tx_data,tx_file)
  82. if 'info' in opts:
  83. view_tx_data(c,inputs_data,tx_hex,metadata)
  84. sys.exit(0)
  85. if not 'quiet' in opts: do_license_msg()
  86. msg("Successfully opened transaction file '%s'" % tx_file)
  87. if user_confirm("View transaction data? ",default_yes=False):
  88. view_tx_data(c,inputs_data,tx_hex,metadata)
  89. # Are inputs mmgen addresses?
  90. infile,mmgen_addrs,other_addrs,keys = "",[],[],[]
  91. for i in inputs_data:
  92. if verify_mmgen_label(i['account']):
  93. mmgen_addrs.append(i)
  94. else:
  95. other_addrs.append(i)
  96. if mmgen_addrs and not 'force_wallet_dat' in opts:
  97. # Check that all the seed IDs are the same:
  98. seed_ids = list(set([i['account'][:8] for i in mmgen_addrs]))
  99. while seed_ids:
  100. if cmd_args:
  101. infile = cmd_args.pop()
  102. ext = infile.split(".")[-1]
  103. for e,o in (
  104. (wallet_ext, {}),
  105. (mn_ext, {"from_mnemonic":True}),
  106. (seed_ext, {"from_seed": True}),
  107. (brain_ext, {})
  108. ):
  109. if e == ext:
  110. if e == brain_ext:
  111. if "from_brain" in opts: o = opts
  112. else:
  113. msg("'--from-brain' option must be specified for brainwallet file")
  114. sys.exit(2)
  115. seed = get_seed(infile,o)
  116. elif "from_brain" in opts or "from_mnemonic" in opts or "from_seed" in opts:
  117. msg("Need data for seed ID %s" % seed_ids[0])
  118. seed = get_seed("",opts)
  119. else:
  120. msg("One of '-b', '-m' or '-s' must be specified for seed IDs: %s" %
  121. " ".join(seed_ids))
  122. sys.exit(2)
  123. seed_id = make_chksum_8(seed)
  124. if seed_id in seed_ids:
  125. seed_ids.remove(seed_id)
  126. seed_id_addrs = []
  127. for i in mmgen_addrs:
  128. if i['account'][:8] == seed_id:
  129. seed_id_addrs.append(int(i['account'].split()[0][9:]))
  130. from mmgen.addr import generate_addrs
  131. o = {'no_addresses': True, 'gen_what': "keys"}
  132. keys += [i['wif'] for i in generate_addrs(seed, seed_id_addrs, o)]
  133. else:
  134. msg("Supplied seed ID (%s) is incorrect" % seed_id)
  135. sys.exit(2)
  136. if other_addrs:
  137. if 'keys_from_file' in opts:
  138. keys += get_lines_from_file(opts['keys_from_file'],
  139. "additional key data")
  140. else:
  141. msg("""
  142. A key file must be supplied (option '-f') for the following non-mmgen
  143. address%s: %s""" % (
  144. "" if len(other_addrs) == 1 else "es",
  145. " ".join([i['address'] for i in other_addrs])
  146. ))
  147. sys.exit(2)
  148. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  149. elif 'keys_from_file' in opts:
  150. keys = get_lines_from_file(opts['keys_from_file'],"key data")
  151. sig_tx = sign_transaction(c,tx_hex,sig_data,keys)
  152. else:
  153. prompt = "Enter passphrase for bitcoind wallet: "
  154. if 'echo_passphrase' in opts:
  155. password = my_raw_input(prompt)
  156. else:
  157. password = my_getpass(prompt)
  158. wallet_enc = True
  159. from mmgen.rpc import exceptions
  160. try:
  161. c.walletpassphrase(password, 9999)
  162. except exceptions.WalletWrongEncState:
  163. msg("Wallet is unencrypted")
  164. wallet_enc = False
  165. except exceptions.WalletPassphraseIncorrect:
  166. msg("Passphrase incorrect")
  167. sys.exit(3)
  168. except exceptions.WalletAlreadyUnlocked:
  169. msg("WARNING: Wallet already unlocked!")
  170. else:
  171. msg("Passphrase OK")
  172. sig_tx = sign_transaction(c,tx_hex,sig_data)
  173. if wallet_enc:
  174. c.walletlock()
  175. msg("Locking wallet")
  176. if sig_tx['complete']:
  177. msg("Signing completed")
  178. else:
  179. msg("Some keys were missing. Transaction could not be signed.")
  180. sys.exit(3)
  181. prompt = "Save signed transaction?"
  182. if user_confirm(prompt,default_yes=True):
  183. print_signed_tx_to_file(tx_hex,sig_tx['hex'],metadata,opts)