mmgen-txcreate 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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.util 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 addresses
  47. of the form <seed ID>:<number>.
  48. To send all inputs (minus TX fee) to a single output, specify one address
  49. with no amount on the command line.
  50. """ % (Decimal(g.tx_fee),g.mins_per_block)
  51. }
  52. short_opts = "hd:eiqf:"
  53. long_opts = "help","outdir=","echo_passphrase","info","quiet","tx_fee="
  54. opts,cmd_args = process_opts(sys.argv,help_data,short_opts,long_opts)
  55. if 'quiet' in opts: g.quiet = True
  56. check_opts(opts,long_opts)
  57. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  58. c = connect_to_bitcoind()
  59. if not 'info' in opts:
  60. tx_out,addr_data,b2m_map,acct_data,change_addr = {},[],{},[],""
  61. for a in [i for i in cmd_args if match_ext(i,g.addrfile_ext)]:
  62. if match_ext(a,g.addrfile_ext):
  63. check_infile(a)
  64. addr_data.append(parse_addrs_file(a))
  65. def mm2btc_addr_proc(c,mmadr,acct_data,addr_data,b2m_map):
  66. btaddr,label = mmgen_addr_to_walletd(c,mmadr,acct_data)
  67. if not btaddr:
  68. btaddr,label = mmgen_addr_to_addr_data(mmadr,addr_data)
  69. b2m_map[btaddr] = mmadr,label
  70. return btaddr
  71. for a in [i for i in cmd_args if not match_ext(i,g.addrfile_ext)]:
  72. if "," in a:
  73. a1,a2 = a.split(",")
  74. if is_mmgen_addr(a1) or is_btc_addr(a1):
  75. if is_mmgen_addr(a1):
  76. btaddr = mm2btc_addr_proc(c,a1,acct_data,addr_data,b2m_map)
  77. if is_btc_amt(a2):
  78. tx_out[btaddr] = check_btc_amt(a2)
  79. else:
  80. msg("%s: invalid amount in argument '%s'" % (a2,a))
  81. sys.exit(2)
  82. else:
  83. msg("%s: unrecognized subargument in argument '%s'" % (a1,a))
  84. sys.exit(2)
  85. elif is_mmgen_addr(a) or is_btc_addr(a):
  86. if change_addr:
  87. msg("More than one change address specified: %s, %s" %
  88. (change_addr, a))
  89. sys.exit(2)
  90. if is_mmgen_addr(a):
  91. change_addr = mm2btc_addr_proc(c,a,acct_data,addr_data,b2m_map)
  92. else:
  93. change_addr = a
  94. tx_out[change_addr] = 0
  95. else:
  96. msg("%s: unrecognized argument" % a)
  97. sys.exit(2)
  98. if not tx_out:
  99. msg("At least one output must be specified on the command line")
  100. sys.exit(2)
  101. tx_fee = opts['tx_fee'] if 'tx_fee' in opts else g.tx_fee
  102. tx_fee = check_btc_amt(tx_fee)
  103. if tx_fee > g.max_tx_fee:
  104. msg("Transaction fee too large: %s > %s" % (tx_fee,g.max_tx_fee))
  105. sys.exit(2)
  106. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  107. if not 'info' in opts: do_license_msg(immed=True)
  108. # Begin test
  109. # import mmgen.rpc
  110. # us = eval(get_data_from_file("listunspent.json"))
  111. # End test
  112. us = c.listunspent()
  113. if not us:
  114. msg("""
  115. No spendable outputs found! Import addresses with balances into your
  116. watch-only wallet using 'mmgen-addrimport' and then re-run this program.""")
  117. sys.exit(2)
  118. # write_to_file("listunspent.json",repr(us))
  119. # sys.exit()
  120. unspent = sort_and_view(us)
  121. total = trim_exponent(sum([i.amount for i in unspent]))
  122. msg("Total unspent: %s BTC (%s outputs)" % (total, len(unspent)))
  123. if 'info' in opts: sys.exit(0)
  124. send_amt = sum([tx_out[i] for i in tx_out.keys()])
  125. msg("Total amount to spend: %s%s" % (
  126. (send_amt or "Unknown")," BTC" if send_amt else ""))
  127. while True:
  128. sel_nums = select_outputs(unspent,
  129. "Enter a range or space-separated list of outputs to spend: ")
  130. msg("Selected outputs: %s" % " ".join(str(i) for i in sel_nums))
  131. sel_unspent = [unspent[i-1] for i in sel_nums]
  132. mmaddrs = set([parse_mmgen_label(i.account)[0] for i in sel_unspent])
  133. mmaddrs.discard("")
  134. if mmaddrs and len(mmaddrs) < len(sel_unspent):
  135. msg(txmsg['mixed_inputs'] % ", ".join(sorted(mmaddrs)))
  136. if not user_confirm("Accept?"):
  137. continue
  138. total_in = trim_exponent(sum([i.amount for i in sel_unspent]))
  139. change = trim_exponent(total_in - (send_amt + tx_fee))
  140. if change >= 0:
  141. prompt = "Transaction produces %s BTC in change. OK?" % change
  142. if user_confirm(prompt,default_yes=True):
  143. break
  144. else:
  145. msg(txmsg['not_enough_btc'] % change)
  146. if change > 0 and not change_addr:
  147. msg(txmsg['throwaway_change'] % change)
  148. sys.exit(2)
  149. if change_addr in tx_out and not change:
  150. msg("Warning: Change address will be unused as transaction produces no change")
  151. del tx_out[change_addr]
  152. for k,v in tx_out.items(): tx_out[k] = float(v)
  153. if change > 0: tx_out[change_addr] = float(change)
  154. tx_in = [{"txid":i.txid, "vout":i.vout} for i in sel_unspent]
  155. if g.debug:
  156. print "tx_in:", repr(tx_in)
  157. print "tx_out:", repr(tx_out)
  158. tx_hex = c.createrawtransaction(tx_in,tx_out)
  159. qmsg("Transaction successfully created")
  160. prompt = "View decoded transaction? (y)es, (N)o, (v)iew in pager"
  161. reply = prompt_and_get_char(prompt,"YyNnVv",enter_ok=True)
  162. if reply and reply in "YyVv":
  163. pager = True if reply in "Vv" else False
  164. view_tx_data(c,[i.__dict__ for i in sel_unspent],tx_hex,b2m_map,pager=pager)
  165. prompt = "Save transaction?"
  166. if user_confirm(prompt,default_yes=True):
  167. print_tx_to_file(tx_hex,sel_unspent,send_amt or change,b2m_map,opts)
  168. else:
  169. msg("Transaction not saved")