mmgen-txcreate 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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-txcreate: Create a BTC transaction, sending to specified addresses
  20. """
  21. import sys
  22. #from hashlib import sha256
  23. from mmgen.Opts import *
  24. from mmgen.license import *
  25. import mmgen.config as g
  26. from mmgen.tx import *
  27. from mmgen.utils import msg, msg_r, user_confirm
  28. from decimal import Decimal
  29. prog_name = sys.argv[0].split("/")[-1]
  30. help_data = {
  31. 'prog_name': prog_name,
  32. 'desc': "Create a BTC transaction with outputs to specified addresses",
  33. 'usage': "[opts] <addr,amt> ... [change addr] [tx fee] [addr file] ...",
  34. 'options': """
  35. -h, --help Print this help message
  36. -d, --outdir d Specify an alternate directory 'd' for output
  37. -e, --echo-passphrase Print passphrase to screen when typing it
  38. -i, --info Display unspent outputs and exit
  39. -q, --quiet Suppress warnings; overwrite files without
  40. prompting
  41. -f, --tx-fee f Transaction fee (default: %s BTC)
  42. Transaction inputs are chosen from a list of the user's unpent outputs
  43. via an interactive menu.
  44. Ages of transactions are approximate based on an average block creation
  45. interval of %s minutes.
  46. Addresses on the command line can be Bitcoin addresses or MMGen
  47. addresses in the form <seed ID>:<number>
  48. """ % (Decimal(g.tx_fee),g.mins_per_block)
  49. }
  50. short_opts = "ha:d:eiqf:"
  51. long_opts = "help","addr_file","outdir=","echo_passphrase","info","quiet",\
  52. "tx_fee="
  53. opts,cmd_args = process_opts(sys.argv,help_data,short_opts,long_opts)
  54. check_opts(opts,long_opts)
  55. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  56. if not 'info' in opts:
  57. outputs,addr_files,change_addr = [],[],""
  58. for a in cmd_args:
  59. if a.split(".")[-1] == g.addrfile_ext:
  60. check_infile(a)
  61. addr_files.append(a)
  62. elif "," in a:
  63. outputs.append(a)
  64. else:
  65. if change_addr:
  66. msg("More than one change address specified: %s, %s" %
  67. (change_addr, a))
  68. sys.exit(2)
  69. change_addr = a
  70. if not outputs:
  71. msg("At least one output must be specified on the command line")
  72. sys.exit(2)
  73. addr_data = [parse_addrs_file(f) for f in addr_files]
  74. tx_fee = opts['tx_fee'] if 'tx_fee' in opts else g.tx_fee
  75. try:
  76. tx_fee = Decimal(tx_fee)
  77. except:
  78. msg("Invalid transaction fee format: %s" % tx_fee)
  79. sys.exit(2)
  80. if tx_fee > g.max_tx_fee:
  81. msg("Transaction fee too large: %s > %s" % (tx_fee,g.max_tx_fee))
  82. sys.exit(2)
  83. if change_addr:
  84. if ":" in change_addr:
  85. change_addr = mmgen_addr_to_btc_addr(change_addr,addr_data)
  86. else:
  87. check_address(change_addr)
  88. tx_out = make_tx_out(outputs,addr_data)
  89. for i in tx_out.keys(): check_address(i)
  90. for i in tx_out.values(): check_btc_amt(i)
  91. tx_fee = check_btc_amt(tx_fee)
  92. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  93. # Begin execution
  94. c = connect_to_bitcoind()
  95. if not 'quiet' in opts and not 'info' in opts:
  96. do_license_msg(immed=True)
  97. # Begin test
  98. # import mmgen.rpc
  99. # us = eval(get_data_from_file("listunspent.json"))
  100. # End test
  101. us = c.listunspent()
  102. if not us:
  103. msg_r("""
  104. No spendable outputs found! Import addresses with balances into your
  105. watch-only wallet using 'mmgen-addrimport' and then re-run this program.
  106. """)
  107. sys.exit(2)
  108. # write_to_file("listunspent.json",repr(us))
  109. # sys.exit()
  110. unspent = sort_and_view(us)
  111. total = trim_exponent(sum([i.amount for i in unspent]))
  112. msg("Total unspent: %s BTC (%s outputs)" % (total, len(unspent)))
  113. if 'info' in opts: sys.exit(0)
  114. send_amt = sum(tx_out.values())
  115. msg("Total amount to spend: %s BTC" % send_amt)
  116. while True:
  117. sel_nums = select_outputs(unspent,
  118. "Enter a range or space-separated list of outputs to spend: ")
  119. msg("Selected outputs: %s" % " ".join(str(i) for i in sel_nums))
  120. sel_unspent = [unspent[i-1] for i in sel_nums]
  121. lbls = set([verify_mmgen_label(
  122. i.account,return_str=True,check_label_len=True)
  123. for i in sel_unspent])
  124. lbls.discard("")
  125. if lbls and len(lbls) < len(sel_unspent):
  126. msg(txmsg['mixed_inputs'] % ", ".join(sorted(lbls)))
  127. if not user_confirm("Accept?"):
  128. continue
  129. total_in = trim_exponent(sum([o.amount for o in sel_unspent]))
  130. change = trim_exponent(total_in - (send_amt + tx_fee))
  131. if change >= 0:
  132. prompt = "Transaction produces %s BTC in change. OK?" % change
  133. if user_confirm(prompt,default_yes=True):
  134. break
  135. else:
  136. msg(txmsg['not_enough_btc'] % change)
  137. if change > 0 and not change_addr:
  138. msg(txmsg['throwaway_change'] % (change, total_in-tx_fee))
  139. sys.exit(2)
  140. tx_in = [{"txid":i.txid, "vout":i.vout} for i in sel_unspent]
  141. for i in tx_out.keys(): tx_out[i] = float(tx_out[i])
  142. if change: tx_out[change_addr] = float(change)
  143. if g.debug:
  144. print "tx_in:", repr(tx_in)
  145. print "tx_out:", repr(tx_out)
  146. tx_hex = c.createrawtransaction(tx_in,tx_out)
  147. msg("Transaction successfully created")
  148. prompt = "View decoded transaction? (y)es, (N)o, (v)iew in pager"
  149. reply = prompt_and_get_char(prompt,"YyNnVv",enter_ok=True)
  150. if reply and reply in "YyVv":
  151. pager = True if reply in "Vv" else False
  152. view_tx_data(c,[i.__dict__ for i in sel_unspent],tx_hex,pager=pager)
  153. prompt = "Save transaction?"
  154. if user_confirm(prompt,default_yes=True):
  155. print_tx_to_file(tx_hex,sel_unspent,send_amt,opts)
  156. else:
  157. msg("Transaction not saved")