mmgen-txcreate 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 decimal import Decimal
  23. import mmgen.config as g
  24. from mmgen.Opts import *
  25. from mmgen.license import *
  26. from mmgen.tx import *
  27. from mmgen.util import msg, msg_r, user_confirm
  28. help_data = {
  29. 'prog_name': g.prog_name,
  30. 'desc': "Create a BTC transaction with outputs to specified addresses",
  31. 'usage': "[opts] <addr,amt> ... [change addr] [addr 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, --tx-fee= f Transaction fee (default: {g.tx_fee} BTC)
  37. -i, --info Display unspent outputs and exit
  38. -q, --quiet Suppress warnings; overwrite files without
  39. prompting
  40. """.format(g=g),
  41. 'notes': """
  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 {g.mins_per_block} minutes.
  46. Addresses on the command line can be Bitcoin addresses or {pnm} 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. """.format(g=g,pnm=g.proj_name)
  51. }
  52. opts,cmd_args = parse_opts(sys.argv,help_data)
  53. if 'quiet' in opts: g.quiet = True
  54. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  55. c = connect_to_bitcoind()
  56. if not 'info' in opts:
  57. do_license_msg(immed=True)
  58. tx_out,addr_data,b2m_map,acct_data,change_addr = {},[],{},[],""
  59. addrfiles = [a for a in cmd_args if get_extension(a) == g.addrfile_ext]
  60. cmd_args = set(cmd_args) - set(addrfiles)
  61. for a in addrfiles:
  62. check_infile(a)
  63. addr_data.append(parse_addrs_file(a))
  64. def mmaddr2btcaddr(c,mmaddr,acct_data,addr_data,b2m_map):
  65. # assume mmaddr has already been checked
  66. btcaddr,label = mmaddr2btcaddr_bitcoind(c,mmaddr,acct_data)
  67. if not btcaddr:
  68. if addr_data:
  69. btcaddr,label = mmaddr2btcaddr_addrfile(mmaddr,addr_data)
  70. else:
  71. msg(txmsg['addrfile_no_data_msg'] % mmaddr)
  72. sys.exit(2)
  73. b2m_map[btcaddr] = mmaddr,label
  74. return btcaddr
  75. for a in cmd_args:
  76. if "," in a:
  77. a1,a2 = a.split(",")
  78. if is_btc_addr(a1):
  79. btcaddr = a1
  80. elif is_mmgen_addr(a1):
  81. btcaddr = mmaddr2btcaddr(c,a1,acct_data,addr_data,b2m_map)
  82. else:
  83. msg("%s: unrecognized subargument in argument '%s'" % (a1,a))
  84. sys.exit(2)
  85. if is_btc_amt(a2):
  86. tx_out[btcaddr] = normalize_btc_amt(a2)
  87. else:
  88. msg("%s: invalid amount in argument '%s'" % (a2,a))
  89. sys.exit(2)
  90. elif is_mmgen_addr(a) or is_btc_addr(a):
  91. if change_addr:
  92. msg("ERROR: More than one change address specified: %s, %s" %
  93. (change_addr, a))
  94. sys.exit(2)
  95. change_addr = a if is_btc_addr(a) else \
  96. mmaddr2btcaddr(c,a,acct_data,addr_data,b2m_map)
  97. tx_out[change_addr] = 0
  98. else:
  99. msg("%s: unrecognized argument" % a)
  100. sys.exit(2)
  101. if not tx_out:
  102. msg("At least one output must be specified on the command line")
  103. sys.exit(2)
  104. tx_fee = opts['tx_fee'] if 'tx_fee' in opts else g.tx_fee
  105. tx_fee = normalize_btc_amt(tx_fee)
  106. if tx_fee > g.max_tx_fee:
  107. msg("Transaction fee too large: %s > %s" % (tx_fee,g.max_tx_fee))
  108. sys.exit(2)
  109. if g.debug: show_opts_and_cmd_args(opts,cmd_args)
  110. #write_to_file("bogus_unspent.json", repr(us), opts); sys.exit()
  111. #if False:
  112. if g.bogus_wallet_data:
  113. import mmgen.rpc
  114. us = eval(get_data_from_file(g.bogus_wallet_data))
  115. else:
  116. us = c.listunspent()
  117. if not us: msg(txmsg['no_spendable_outputs']); sys.exit(2)
  118. unspent = sort_and_view(us,opts)
  119. total = trim_exponent(sum([i.amount for i in unspent]))
  120. msg("Total unspent: %s BTC (%s outputs)" % (total, len(unspent)))
  121. if 'info' in opts: sys.exit(0)
  122. send_amt = sum([tx_out[i] for i in tx_out.keys()])
  123. msg("Total amount to spend: %s%s" % (
  124. (send_amt or "Unknown")," BTC" if send_amt else ""))
  125. while True:
  126. sel_nums = select_outputs(unspent,
  127. "Enter a range or space-separated list of outputs to spend: ")
  128. msg("Selected output%s: %s" %
  129. (("" if len(sel_nums) == 1 else "s"), " ".join(str(i) for i in sel_nums))
  130. )
  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. amt = send_amt or change
  168. tx_id = make_chksum_6(unhexlify(tx_hex)).upper()
  169. outfile = "tx_%s[%s].%s" % (tx_id,amt,g.rawtx_ext)
  170. data = "{} {} {}\n{}\n{}\n{}\n".format(
  171. tx_id, amt, make_timestamp(),
  172. tx_hex,
  173. repr([i.__dict__ for i in sel_unspent]),
  174. repr(b2m_map)
  175. )
  176. write_to_file(outfile,data,opts,"transaction",False,True)
  177. else:
  178. msg("Transaction not saved")