mmgen-txcreate 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C) 2013-2014 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] [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. -f, --tx-fee= f Transaction fee (default: {g.tx_fee} BTC)
  39. -i, --info Display unspent outputs and exit
  40. -q, --quiet Suppress warnings; overwrite files without
  41. prompting
  42. """.format(g=g),
  43. 'notes': """
  44. Transaction inputs are chosen from a list of the user's unpent outputs
  45. via an interactive menu.
  46. Ages of transactions are approximate based on an average block creation
  47. interval of {g.mins_per_block} minutes.
  48. Addresses on the command line can be Bitcoin addresses or MMGen addresses
  49. of the form <seed ID>:<number>.
  50. To send all inputs (minus TX fee) to a single output, specify one address
  51. with no amount on the command line.
  52. """.format(g=g)
  53. }
  54. opts,cmd_args = parse_opts(sys.argv,help_data)
  55. if 'quiet' in opts: g.quiet = True
  56. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  57. c = connect_to_bitcoind()
  58. if not 'info' in opts:
  59. tx_out,addr_data,b2m_map,acct_data,change_addr = {},[],{},[],""
  60. addrfiles = [a for a in cmd_args if get_extension(a) == g.addrfile_ext]
  61. cmd_args = set(cmd_args) - set(addrfiles)
  62. for a in addrfiles:
  63. check_infile(a)
  64. addr_data.append(parse_addrs_file(a))
  65. def mmaddr2btcaddr(c,mmaddr,acct_data,addr_data,b2m_map):
  66. # assume mmaddr has already been checked
  67. btcaddr,label = mmaddr2btcaddr_bitcoind(c,mmaddr,acct_data)
  68. if not btcaddr:
  69. if addr_data:
  70. btcaddr,label = mmaddr2btcaddr_addrfile(mmaddr,addr_data)
  71. else:
  72. msg(txmsg['addrfile_no_data_msg'] % mmaddr)
  73. sys.exit(2)
  74. b2m_map[btcaddr] = mmaddr,label
  75. return btcaddr
  76. for a in cmd_args:
  77. if "," in a:
  78. a1,a2 = a.split(",")
  79. if is_btc_addr(a1):
  80. btcaddr = a1
  81. elif is_mmgen_addr(a1):
  82. btcaddr = mmaddr2btcaddr(c,a1,acct_data,addr_data,b2m_map)
  83. else:
  84. msg("%s: unrecognized subargument in argument '%s'" % (a1,a))
  85. sys.exit(2)
  86. if is_btc_amt(a2):
  87. tx_out[btcaddr] = normalize_btc_amt(a2)
  88. else:
  89. msg("%s: invalid amount in argument '%s'" % (a2,a))
  90. sys.exit(2)
  91. elif is_mmgen_addr(a) or is_btc_addr(a):
  92. if change_addr:
  93. msg("ERROR: More than one change address specified: %s, %s" %
  94. (change_addr, a))
  95. sys.exit(2)
  96. change_addr = a if is_btc_addr(a) else \
  97. mmaddr2btcaddr(c,a,acct_data,addr_data,b2m_map)
  98. tx_out[change_addr] = 0
  99. else:
  100. msg("%s: unrecognized argument" % a)
  101. sys.exit(2)
  102. if not tx_out:
  103. msg("At least one output must be specified on the command line")
  104. sys.exit(2)
  105. tx_fee = opts['tx_fee'] if 'tx_fee' in opts else g.tx_fee
  106. tx_fee = normalize_btc_amt(tx_fee)
  107. if tx_fee > g.max_tx_fee:
  108. msg("Transaction fee too large: %s > %s" % (tx_fee,g.max_tx_fee))
  109. sys.exit(2)
  110. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  111. if not 'info' in opts: do_license_msg(immed=True)
  112. #write_to_file("bogus_unspent.json", repr(us)); sys.exit()
  113. if g.bogus_wallet_data:
  114. import mmgen.rpc
  115. us = eval(get_data_from_file("bogus_unspent.json"))
  116. else:
  117. us = c.listunspent()
  118. if not us: msg(txmsg['no_spendable_outputs']); sys.exit(2)
  119. unspent = sort_and_view(us)
  120. total = trim_exponent(sum([i.amount for i in unspent]))
  121. msg("Total unspent: %s BTC (%s outputs)" % (total, len(unspent)))
  122. if 'info' in opts: sys.exit(0)
  123. send_amt = sum([tx_out[i] for i in tx_out.keys()])
  124. msg("Total amount to spend: %s%s" % (
  125. (send_amt or "Unknown")," BTC" if send_amt else ""))
  126. while True:
  127. sel_nums = select_outputs(unspent,
  128. "Enter a range or space-separated list of outputs to spend: ")
  129. msg("Selected output%s: %s" %
  130. (("" if len(sel_nums) == 1 else "s"), " ".join(str(i) for i in sel_nums))
  131. )
  132. sel_unspent = [unspent[i-1] for i in sel_nums]
  133. mmaddrs = set([parse_mmgen_label(i.account)[0] for i in sel_unspent])
  134. mmaddrs.discard("")
  135. if mmaddrs and len(mmaddrs) < len(sel_unspent):
  136. msg(txmsg['mixed_inputs'] % ", ".join(sorted(mmaddrs)))
  137. if not user_confirm("Accept?"):
  138. continue
  139. total_in = trim_exponent(sum([i.amount for i in sel_unspent]))
  140. change = trim_exponent(total_in - (send_amt + tx_fee))
  141. if change >= 0:
  142. prompt = "Transaction produces %s BTC in change. OK?" % change
  143. if user_confirm(prompt,default_yes=True):
  144. break
  145. else:
  146. msg(txmsg['not_enough_btc'] % change)
  147. if change > 0 and not change_addr:
  148. msg(txmsg['throwaway_change'] % change)
  149. sys.exit(2)
  150. if change_addr in tx_out and not change:
  151. msg("Warning: Change address will be unused as transaction produces no change")
  152. del tx_out[change_addr]
  153. for k,v in tx_out.items(): tx_out[k] = float(v)
  154. if change > 0: tx_out[change_addr] = float(change)
  155. tx_in = [{"txid":i.txid, "vout":i.vout} for i in sel_unspent]
  156. if g.debug:
  157. print "tx_in:", repr(tx_in)
  158. print "tx_out:", repr(tx_out)
  159. tx_hex = c.createrawtransaction(tx_in,tx_out)
  160. qmsg("Transaction successfully created")
  161. prompt = "View decoded transaction? (y)es, (N)o, (v)iew in pager"
  162. reply = prompt_and_get_char(prompt,"YyNnVv",enter_ok=True)
  163. if reply and reply in "YyVv":
  164. pager = True if reply in "Vv" else False
  165. view_tx_data(c,[i.__dict__ for i in sel_unspent],tx_hex,b2m_map,pager=pager)
  166. prompt = "Save transaction?"
  167. if user_confirm(prompt,default_yes=True):
  168. write_tx_to_file(tx_hex,sel_unspent,send_amt or change,b2m_map,opts)
  169. else:
  170. msg("Transaction not saved")