tx.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 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. tx.py: Transaction routines for the MMGen suite
  20. """
  21. import sys,os
  22. from stat import *
  23. from binascii import unhexlify
  24. from mmgen.common import *
  25. from mmgen.obj import *
  26. def is_mmgen_seed_id(s): return SeedID(sid=s,on_fail='silent')
  27. def is_mmgen_idx(s): return AddrIdx(s,on_fail='silent')
  28. def is_mmgen_id(s): return MMGenID(s,on_fail='silent')
  29. def is_btc_addr(s): return BTCAddr(s,on_fail='silent')
  30. def is_addrlist_id(s): return AddrListID(s,on_fail='silent')
  31. def is_tw_label(s): return TwLabel(s,on_fail='silent')
  32. def is_wif(s):
  33. if s == '': return False
  34. from mmgen.bitcoin import wif2hex
  35. return bool(wif2hex(s))
  36. def segwit_is_active(exit_on_error=False):
  37. d = bitcoin_connection().getblockchaininfo()
  38. if d['chain'] == 'regtest' or d['bip9_softforks']['segwit']['status'] == 'active':
  39. return True
  40. if g.skip_segwit_active_check: return True
  41. if exit_on_error:
  42. die(2,'Segwit not active on this chain. Exiting')
  43. else:
  44. return False
  45. def bytes2int(hex_bytes):
  46. r = hexlify(unhexlify(hex_bytes)[::-1])
  47. if r[0] in '89abcdef':
  48. die(3,"{}: Negative values not permitted in transaction!".format(hex_bytes))
  49. return int(r,16)
  50. def bytes2btc(hex_bytes):
  51. return bytes2int(hex_bytes) * g.satoshi
  52. from collections import OrderedDict
  53. class DeserializedTX(OrderedDict,MMGenObject): # need to add MMGen types
  54. def __init__(self,txhex):
  55. tx = list(unhexlify(txhex))
  56. tx_copy = tx[:]
  57. def hshift(l,n,reverse=False):
  58. ret = l[:n]
  59. del l[:n]
  60. return hexlify(''.join(ret[::-1] if reverse else ret))
  61. # https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
  62. # For example, the number 515 is encoded as 0xfd0302.
  63. def readVInt(l):
  64. s = int(hexlify(l[0]),16)
  65. bytes_len = 1 if s < 0xfd else 2 if s == 0xfd else 4 if s == 0xfe else 8
  66. if bytes_len != 1: del l[0]
  67. ret = int(hexlify(''.join(l[:bytes_len][::-1])),16)
  68. del l[:bytes_len]
  69. return ret
  70. d = { 'version': bytes2int(hshift(tx,4)) }
  71. has_witness = (False,True)[hexlify(tx[0])=='00']
  72. if has_witness:
  73. u = hshift(tx,2)[2:]
  74. if u != '01':
  75. die(2,"'{}': Illegal value for flag in transaction!".format(u))
  76. del tx_copy[-len(tx)-2:-len(tx)]
  77. d['num_txins'] = readVInt(tx)
  78. d['txins'] = MMGenList([OrderedDict((
  79. ('txid', hshift(tx,32,reverse=True)),
  80. ('vout', bytes2int(hshift(tx,4))),
  81. ('scriptSig', hshift(tx,readVInt(tx))),
  82. ('nSeq', hshift(tx,4,reverse=True))
  83. )) for i in range(d['num_txins'])])
  84. d['num_txouts'] = readVInt(tx)
  85. d['txouts'] = MMGenList([OrderedDict((
  86. ('amount', bytes2btc(hshift(tx,8))),
  87. ('scriptPubKey', hshift(tx,readVInt(tx)))
  88. )) for i in range(d['num_txouts'])])
  89. d['witness_size'] = 0
  90. if has_witness:
  91. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  92. # A non-witness program (defined hereinafter) txin MUST be associated with an empty
  93. # witness field, represented by a 0x00.
  94. del tx_copy[-len(tx):-4]
  95. wd,tx = tx[:-4],tx[-4:]
  96. d['witness_size'] = len(wd) + 2 # add marker and flag
  97. for i in range(len(d['txins'])):
  98. if hexlify(wd[0]) == '00':
  99. hshift(wd,1)
  100. continue
  101. d['txins'][i]['witness'] = [hshift(wd,readVInt(wd)) for item in range(readVInt(wd))]
  102. if wd:
  103. die(3,'More witness data than inputs with witnesses!')
  104. d['lock_time'] = bytes2int(hshift(tx,4))
  105. d['txid'] = hexlify(sha256(sha256(''.join(tx_copy)).digest()).digest()[::-1])
  106. keys = 'txid','version','lock_time','witness_size','num_txins','txins','num_txouts','txouts'
  107. return OrderedDict.__init__(self, ((k,d[k]) for k in keys))
  108. class MMGenTX(MMGenObject):
  109. ext = 'rawtx'
  110. raw_ext = 'rawtx'
  111. sig_ext = 'sigtx'
  112. txid_ext = 'txid'
  113. desc = 'transaction'
  114. class MMGenTxInput(MMGenListItem):
  115. attrs = 'txid','vout','amt','label','mmid','addr','confs','scriptPubKey','have_wif','sequence'
  116. txid = MMGenListItemAttr('txid','BitcoinTxID')
  117. scriptPubKey = MMGenListItemAttr('scriptPubKey','HexStr')
  118. class MMGenTxOutput(MMGenListItem):
  119. attrs = 'txid','vout','amt','label','mmid','addr','have_wif','is_chg'
  120. class MMGenTxInputOldFmt(MMGenListItem): # for converting old tx files only
  121. tr = {'amount':'amt', 'address':'addr', 'confirmations':'confs','comment':'label'}
  122. attrs = 'txid','vout','amt','label','mmid','addr','confs','scriptPubKey','wif'
  123. attrs_priv = 'tr',
  124. class MMGenTxInputList(list,MMGenObject): pass
  125. class MMGenTxOutputList(list,MMGenObject): pass
  126. def __init__(self,filename=None):
  127. self.inputs = self.MMGenTxInputList()
  128. self.outputs = self.MMGenTxOutputList()
  129. self.send_amt = BTCAmt('0') # total amt minus change
  130. self.hex = '' # raw serialized hex transaction
  131. self.label = MMGenTXLabel('')
  132. self.txid = ''
  133. self.btc_txid = ''
  134. self.timestamp = ''
  135. self.chksum = ''
  136. self.fmt_data = ''
  137. self.blockcount = 0
  138. self.chain = None
  139. if filename:
  140. self.parse_tx_file(filename)
  141. self.check_sigs() # marks the tx as signed
  142. # repeat with sign and send, because bitcoind could be restarted
  143. self.die_if_incorrect_chain()
  144. def die_if_incorrect_chain(self):
  145. if self.chain and g.chain and self.chain != g.chain:
  146. die(2,'Transaction is for {}, but current chain is {}!'.format(self.chain,g.chain))
  147. def add_output(self,btcaddr,amt,is_chg=None):
  148. self.outputs.append(self.MMGenTxOutput(addr=btcaddr,amt=amt,is_chg=is_chg))
  149. def get_chg_output_idx(self):
  150. for i in range(len(self.outputs)):
  151. if self.outputs[i].is_chg == True:
  152. return i
  153. return None
  154. def update_output_amt(self,idx,amt):
  155. o = self.outputs[idx].__dict__
  156. o['amt'] = amt
  157. self.outputs[idx] = self.MMGenTxOutput(**o)
  158. def del_output(self,idx):
  159. self.outputs.pop(idx)
  160. def sum_outputs(self,exclude=None):
  161. olist = self.outputs if exclude == None else \
  162. self.outputs[:exclude] + self.outputs[exclude+1:]
  163. return BTCAmt(sum(e.amt for e in olist))
  164. def add_mmaddrs_to_outputs(self,ad_w,ad_f):
  165. a = [e.addr for e in self.outputs]
  166. d = ad_w.make_reverse_dict(a)
  167. d.update(ad_f.make_reverse_dict(a))
  168. for e in self.outputs:
  169. if e.addr and e.addr in d:
  170. e.mmid,f = d[e.addr]
  171. if f: e.label = f
  172. # def encode_io(self,desc):
  173. # tr = getattr((self.MMGenTxOutput,self.MMGenTxInput)[desc=='inputs'],'tr')
  174. # tr_rev = dict([(v,k) for k,v in tr.items()])
  175. # return [dict([(tr_rev[e] if e in tr_rev else e,getattr(d,e)) for e in d.__dict__])
  176. # for d in getattr(self,desc)]
  177. #
  178. def create_raw(self,c):
  179. i = [{'txid':e.txid,'vout':e.vout} for e in self.inputs]
  180. if self.inputs[0].sequence:
  181. i[0]['sequence'] = self.inputs[0].sequence
  182. o = dict([(e.addr,e.amt) for e in self.outputs])
  183. self.hex = c.createrawtransaction(i,o)
  184. self.txid = MMGenTxID(make_chksum_6(unhexlify(self.hex)).upper())
  185. # returns true if comment added or changed
  186. def add_comment(self,infile=None):
  187. if infile:
  188. self.label = MMGenTXLabel(get_data_from_file(infile,'transaction comment'))
  189. else: # get comment from user, or edit existing comment
  190. m = ('Add a comment to transaction?','Edit transaction comment?')[bool(self.label)]
  191. if keypress_confirm(m,default_yes=False):
  192. while True:
  193. s = MMGenTXLabel(my_raw_input('Comment: ',insert_txt=self.label))
  194. if s:
  195. lbl_save = self.label
  196. self.label = s
  197. return (True,False)[lbl_save == self.label]
  198. else:
  199. msg('Invalid comment')
  200. return False
  201. def edit_comment(self):
  202. return self.add_comment(self)
  203. def has_segwit_inputs(self):
  204. return any(i.mmid and i.mmid.mmtype == 'S' for i in self.inputs)
  205. # https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
  206. # 180: uncompressed, 148: compressed
  207. def estimate_size_old(self):
  208. if not self.inputs or not self.outputs: return None
  209. return len(self.inputs)*180 + len(self.outputs)*34 + 10
  210. # https://bitcoincore.org/en/segwit_wallet_dev/
  211. # vsize: 3 times of the size with original serialization, plus the size with new
  212. # serialization, divide the result by 4 and round up to the next integer.
  213. # TODO: results differ slightly from actual transaction size
  214. def estimate_vsize(self):
  215. if not self.inputs or not self.outputs: return None
  216. sig_size = 72 # sig in DER format
  217. pubkey_size = { 'compressed':33, 'uncompressed':65 }
  218. outpoint_size = 36 # txid + vout
  219. def get_inputs_size():
  220. segwit_isize = outpoint_size + 1 + 23 + 4 # (txid,vout) [scriptSig size] scriptSig nSeq # = 64
  221. # txid vout [scriptSig size] scriptSig (<sig> <pubkey>) nSeq
  222. legacy_isize = outpoint_size + 1 + 2 + sig_size + pubkey_size['uncompressed'] + 4 # = 180
  223. compressed_isize = outpoint_size + 1 + 2 + sig_size + pubkey_size['compressed'] + 4 # = 148
  224. ret = sum((legacy_isize,segwit_isize)[i.mmid.mmtype=='S'] for i in self.inputs if i.mmid)
  225. # assume all non-MMGen pubkeys are compressed (we have no way of knowing
  226. # until we see the key). TODO: add user option to specify this?
  227. return ret + sum(compressed_isize for i in self.inputs if not i.mmid)
  228. def get_outputs_size():
  229. return sum((34,32)[o.addr.addr_fmt=='p2sh'] for o in self.outputs)
  230. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  231. # The witness is a serialization of all witness data of the transaction. Each txin is
  232. # associated with a witness field. A witness field starts with a var_int to indicate the
  233. # number of stack items for the txin. It is followed by stack items, with each item starts
  234. # with a var_int to indicate the length. Witness data is NOT script.
  235. # A non-witness program txin MUST be associated with an empty witness field, represented
  236. # by a 0x00. If all txins are not witness program, a transaction's wtxid is equal to its txid.
  237. def get_witness_size():
  238. if not self.has_segwit_inputs(): return 0
  239. wf_size = 1 + 1 + sig_size + 1 + pubkey_size['compressed'] # vInt vInt sig vInt pubkey = 108
  240. return sum((1,wf_size)[bool(i.mmid) and i.mmid.mmtype=='S'] for i in self.inputs)
  241. isize = get_inputs_size()
  242. osize = get_outputs_size()
  243. wsize = get_witness_size()
  244. # pmsg([i.mmid and i.mmid.mmtype == 'S' for i in self.inputs])
  245. # pmsg([i.mmid for i in self.inputs])
  246. # pmsg([i.mmid for i in self.outputs])
  247. # pmsg('isize',isize)
  248. # pmsg('osize',osize)
  249. # pmsg('wsize',wsize)
  250. # TODO: compute real varInt sizes instead of assuming 1 byte
  251. # old serialization: [nVersion] [vInt][txins][vInt][txouts] [nLockTime]
  252. old_size = 4 + 1 + isize + 1 + osize + 4
  253. # new serialization: [nVersion][marker][flag][vInt][txins][vInt][txouts][witness][nLockTime]
  254. new_size = 4 + 1 + 1 + 1 + isize + 1 + osize + wsize + 4 \
  255. if wsize else old_size
  256. ret = (old_size * 3 + new_size) / 4
  257. # pmsg('old_size',old_size) # This should be equal to the size of serialized signed tx
  258. # pmsg('ret',ret)
  259. # pmsg('estimate_size_old',self.estimate_size_old())
  260. return ret
  261. estimate_size = estimate_vsize
  262. def get_fee(self):
  263. return self.sum_inputs() - self.sum_outputs()
  264. def btc2spb(self,btc_fee):
  265. return int(btc_fee/g.satoshi/self.estimate_size())
  266. def get_relay_fee(self):
  267. assert self.estimate_size()
  268. kb_fee = BTCAmt(bitcoin_connection().getnetworkinfo()['relayfee'])
  269. vmsg('Relay fee: {} BTC/kB'.format(kb_fee))
  270. return kb_fee * self.estimate_size() / 1024
  271. def convert_fee_spec(self,tx_fee,tx_size,on_fail='throw'):
  272. if BTCAmt(tx_fee,on_fail='silent'):
  273. return BTCAmt(tx_fee)
  274. elif len(tx_fee) >= 2 and tx_fee[-1] == 's' and is_int(tx_fee[:-1]) and int(tx_fee[:-1]) >= 1:
  275. if tx_size:
  276. return BTCAmt(int(tx_fee[:-1]) * tx_size * g.satoshi)
  277. else:
  278. return None
  279. else:
  280. if on_fail == 'return':
  281. return False
  282. elif on_fail == 'throw':
  283. assert False, "'{}': invalid tx-fee argument".format(tx_fee)
  284. def get_usr_fee(self,tx_fee,desc='Missing description'):
  285. btc_fee = self.convert_fee_spec(tx_fee,self.estimate_size(),on_fail='return')
  286. if btc_fee == None:
  287. msg("'{}': cannot convert satoshis-per-byte to BTC because transaction size is unknown".format(tx_fee))
  288. assert False # because we shouldn't be calling this if tx size is unknown
  289. elif btc_fee == False:
  290. msg("'{}': invalid TX fee (not a BTC amount or satoshis-per-byte specification)".format(tx_fee))
  291. return False
  292. elif btc_fee > g.max_tx_fee:
  293. msg('{} BTC: {} fee too large (maximum fee: {} BTC)'.format(btc_fee,desc,g.max_tx_fee))
  294. return False
  295. elif btc_fee < self.get_relay_fee():
  296. msg('{} BTC: {} fee too small (below relay fee of {} BTC)'.format(str(btc_fee),desc,str(self.get_relay_fee())))
  297. return False
  298. else:
  299. return btc_fee
  300. def get_usr_fee_interactive(self,tx_fee=None,desc='Starting'):
  301. btc_fee = None
  302. while True:
  303. if tx_fee:
  304. btc_fee = self.get_usr_fee(tx_fee,desc)
  305. if btc_fee:
  306. m = ('',' (after {}x adjustment)'.format(opt.tx_fee_adj))[opt.tx_fee_adj != 1]
  307. p = '{} TX fee{}: {} BTC ({} satoshis per byte)'.format(desc,m,
  308. btc_fee.hl(),pink(str(self.btc2spb(btc_fee))))
  309. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  310. if opt.yes: msg(p)
  311. return btc_fee
  312. tx_fee = my_raw_input('Enter transaction fee: ')
  313. desc = 'User-selected'
  314. # inputs methods
  315. def list_wifs(self,desc,mmaddrs_only=False):
  316. return [e.wif for e in getattr(self,desc) if e.mmid] if mmaddrs_only \
  317. else [e.wif for e in getattr(self,desc)]
  318. def delete_attrs(self,desc,attr):
  319. for e in getattr(self,desc):
  320. if hasattr(e,attr): delattr(e,attr)
  321. def decode_io(self,desc,data):
  322. io,il = (
  323. (self.MMGenTxOutput,self.MMGenTxOutputList),
  324. (self.MMGenTxInput,self.MMGenTxInputList)
  325. )[desc=='inputs']
  326. return il([io(**dict([(k,d[k]) for k in io.attrs
  327. if k in d and d[k] not in ('',None)])) for d in data])
  328. def decode_io_oldfmt(self,data):
  329. io = self.MMGenTxInputOldFmt
  330. tr_rev = dict([(v,k) for k,v in io.tr.items()])
  331. copy_keys = [tr_rev[k] if k in tr_rev else k for k in io.attrs]
  332. return [io(**dict([(io.tr[k] if k in io.tr else k,d[k])
  333. for k in copy_keys if k in d and d[k] != ''])) for d in data]
  334. def copy_inputs_from_tw(self,tw_unspent_data):
  335. txi,self.inputs = self.MMGenTxInput,self.MMGenTxInputList()
  336. for d in tw_unspent_data:
  337. t = txi(**dict([(attr,getattr(d,attr)) for attr in d.__dict__ if attr in txi.attrs]))
  338. if d.twmmid.type == 'mmgen': t.mmid = d.twmmid # twmmid -> mmid
  339. self.inputs.append(t)
  340. def get_input_sids(self):
  341. return set(e.mmid.sid for e in self.inputs if e.mmid)
  342. def get_output_sids(self):
  343. return set(e.mmid.sid for e in self.outputs if e.mmid)
  344. def sum_inputs(self):
  345. return sum(e.amt for e in self.inputs)
  346. def add_timestamp(self):
  347. self.timestamp = make_timestamp()
  348. def add_blockcount(self,c):
  349. self.blockcount = int(c.getblockcount())
  350. def format(self):
  351. from mmgen.bitcoin import b58encode
  352. lines = [
  353. '{} {} {} {} {}'.format(
  354. self.chain.upper() if self.chain else 'Unknown',
  355. self.txid,
  356. self.send_amt,
  357. self.timestamp,
  358. self.blockcount
  359. ),
  360. self.hex,
  361. repr([e.__dict__ for e in self.inputs]),
  362. repr([e.__dict__ for e in self.outputs])
  363. ]
  364. if self.label:
  365. lines.append(b58encode(self.label.encode('utf8')))
  366. if self.btc_txid:
  367. if not self.label: lines.append('-') # keep old tx files backwards compatible
  368. lines.append(self.btc_txid)
  369. self.chksum = make_chksum_6(' '.join(lines))
  370. self.fmt_data = '\n'.join([self.chksum] + lines)+'\n'
  371. def get_non_mmaddrs(self,desc):
  372. return list(set(i.addr for i in getattr(self,desc) if not i.mmid))
  373. # return true or false, don't exit
  374. def sign(self,c,tx_num_str,keys):
  375. self.die_if_incorrect_chain()
  376. if not keys:
  377. msg('No keys. Cannot sign!')
  378. return False
  379. qmsg('Passing %s key%s to bitcoind' % (len(keys),suf(keys,'s')))
  380. sig_data = []
  381. for d in self.inputs:
  382. e = dict([(k,getattr(d,k)) for k in ('txid','vout','scriptPubKey','amt')])
  383. e['amount'] = e['amt']
  384. del e['amt']
  385. wif = keys[d.addr]
  386. if d.mmid and d.mmid.mmtype == 'S':
  387. from mmgen.bitcoin import pubhex2redeem_script
  388. from mmgen.addr import keygen_wif2pubhex,keygen_selector
  389. pubhex = keygen_wif2pubhex(wif,keygen_selector())
  390. e['redeemScript'] = pubhex2redeem_script(pubhex)
  391. sig_data.append(e)
  392. from mmgen.bitcoin import hash256
  393. msg_r('Signing transaction{}...'.format(tx_num_str))
  394. # sighashtype defaults to 'ALL'
  395. sig_tx = c.signrawtransaction(self.hex,sig_data,keys.values())
  396. if sig_tx['complete']:
  397. self.hex = sig_tx['hex']
  398. vmsg('Signed transaction size: {}'.format(len(self.hex)/2))
  399. dt = DeserializedTX(self.hex)
  400. txid = dt['txid']
  401. self.check_sigs(dt)
  402. assert txid == c.decoderawtransaction(self.hex)['txid'], 'txid mismatch (after signing)'
  403. self.btc_txid = BitcoinTxID(txid,on_fail='return')
  404. msg('OK')
  405. return True
  406. else:
  407. msg('failed\nBitcoind returned the following errors:')
  408. msg(repr(sig_tx['errors']))
  409. return False
  410. def mark_raw(self):
  411. self.desc = 'transaction'
  412. self.ext = self.raw_ext
  413. def mark_signed(self): # called ONLY by check_sigs()
  414. self.desc = 'signed transaction'
  415. self.ext = self.sig_ext
  416. def marked_signed(self,color=False):
  417. ret = self.desc == 'signed transaction'
  418. return (red,green)[ret](str(ret)) if color else ret
  419. def check_sigs(self,deserial_tx=None): # return False if no sigs, die on error
  420. txins = (deserial_tx or DeserializedTX(self.hex))['txins']
  421. has_ss = any(ti['scriptSig'] for ti in txins)
  422. has_witness = any('witness' in ti and ti['witness'] for ti in txins)
  423. if not (has_ss or has_witness):
  424. return False
  425. for ti in txins:
  426. if ti['scriptSig'][:6] == '160014' and len(ti['scriptSig']) == 46: # P2SH-P2WPKH
  427. assert 'witness' in ti, 'missing witness'
  428. assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness'
  429. assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
  430. elif ti['scriptSig'] == '': # native P2WPKH
  431. die(3,('TX has missing signature','Native P2WPKH not implemented')['witness' in ti])
  432. else: # non-witness
  433. assert not 'witness' in ti, 'non-witness input has witness'
  434. # sig_size 72 (DER format), pubkey_size 'compressed':33, 'uncompressed':65
  435. assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
  436. self.mark_signed()
  437. return True
  438. def has_segwit_outputs(self):
  439. return any(o.mmid and o.mmid.mmtype == 'S' for o in self.outputs)
  440. def is_in_mempool(self,c):
  441. return 'size' in c.getmempoolentry(self.btc_txid,on_fail='silent')
  442. def is_in_wallet(self,c):
  443. ret = c.gettransaction(self.btc_txid,on_fail='silent')
  444. return 'confirmations' in ret and ret['confirmations'] > 0
  445. def is_replaced(self,c):
  446. if self.is_in_mempool(c): return False
  447. ret = c.gettransaction(self.btc_txid,on_fail='silent')
  448. if not 'bip125-replaceable' in ret or not 'confirmations' in ret or ret['confirmations'] > 0:
  449. return False
  450. return -ret['confirmations'] + 1 # 1: replacement in mempool, 2: replacement confirmed
  451. def is_in_utxos(self,c):
  452. return 'txid' in c.getrawtransaction(self.btc_txid,True,on_fail='silent')
  453. def send(self,c,prompt_user=True):
  454. self.die_if_incorrect_chain()
  455. bogus_send = os.getenv('MMGEN_BOGUS_SEND')
  456. if self.has_segwit_outputs() and not segwit_is_active() and not bogus_send:
  457. m = 'Transaction has MMGen Segwit outputs, but this blockchain does not support Segwit'
  458. die(2,m+' at the current height')
  459. if self.get_fee() > g.max_tx_fee:
  460. die(2,'Transaction fee ({}) greater than max_tx_fee ({})!'.format(self.get_fee(),g.max_tx_fee))
  461. if self.is_in_mempool(c):
  462. msg('Warning: transaction is in mempool!')
  463. elif self.is_in_wallet(c):
  464. die(1,'Transaction has been confirmed!')
  465. elif self.is_in_utxos(c):
  466. die(2,red('ERROR: transaction is in the blockchain (but not in the tracking wallet)!'))
  467. ret = self.is_replaced(c) # 1: replacement in mempool, 2: replacement confirmed
  468. if ret:
  469. die(1,'Transaction has been replaced'+('',', and the replacement TX is confirmed')[ret==2]+'!')
  470. if prompt_user:
  471. m1 = ("Once this transaction is sent, there's no taking it back!",'')[bool(opt.quiet)]
  472. m2 = 'broadcast this transaction to the {} network'.format(g.chain.upper())
  473. m3 = ('YES, I REALLY WANT TO DO THIS','YES')[bool(opt.quiet or opt.yes)]
  474. confirm_or_exit(m1,m2,m3)
  475. msg('Sending transaction')
  476. if bogus_send:
  477. ret = 'deadbeef' * 8
  478. m = 'BOGUS transaction NOT sent: %s'
  479. else:
  480. ret = c.sendrawtransaction(self.hex) # exits on failure
  481. m = 'Transaction sent: %s'
  482. if ret:
  483. if not bogus_send:
  484. assert ret == self.btc_txid, 'txid mismatch (after sending)'
  485. self.desc = 'sent transaction'
  486. msg(m % self.btc_txid.hl())
  487. self.add_timestamp()
  488. self.add_blockcount(c)
  489. return True
  490. # rpc call exits on failure, so we won't get here
  491. msg('Sending of transaction {} failed'.format(self.txid))
  492. return False
  493. def write_txid_to_file(self,ask_write=False,ask_write_default_yes=True):
  494. fn = '%s[%s].%s' % (self.txid,self.send_amt,self.txid_ext)
  495. write_data_to_file(fn,self.btc_txid+'\n','transaction ID',
  496. ask_write=ask_write,
  497. ask_write_default_yes=ask_write_default_yes)
  498. def write_to_file(self,add_desc='',ask_write=True,ask_write_default_yes=False,ask_tty=True,ask_overwrite=True):
  499. if ask_write == False:
  500. ask_write_default_yes=True
  501. self.format()
  502. spbs = ('',',{}'.format(self.btc2spb(self.get_fee())))[self.is_rbf()]
  503. fn = '{}[{}{}].{}'.format(self.txid,self.send_amt,spbs,self.ext)
  504. write_data_to_file(fn,self.fmt_data,self.desc+add_desc,
  505. ask_overwrite=ask_overwrite,
  506. ask_write=ask_write,
  507. ask_tty=ask_tty,
  508. ask_write_default_yes=ask_write_default_yes)
  509. def view_with_prompt(self,prompt=''):
  510. prompt += ' (y)es, (N)o, pager (v)iew, (t)erse view'
  511. reply = prompt_and_get_char(prompt,'YyNnVvTt',enter_ok=True)
  512. if reply and reply in 'YyVvTt':
  513. self.view(pager=reply in 'Vv',terse=reply in 'Tt')
  514. def view(self,pager=False,pause=True,terse=False):
  515. o = self.format_view(terse=terse).encode('utf8')
  516. if pager: do_pager(o)
  517. else:
  518. Msg_r(o)
  519. from mmgen.term import get_char
  520. if pause:
  521. get_char('Press any key to continue: ')
  522. msg('')
  523. # def is_rbf_fromhex(self,color=False):
  524. # try:
  525. # dec_tx = bitcoin_connection().decoderawtransaction(self.hex)
  526. # except:
  527. # return yellow('Unknown') if color else None
  528. # rbf = bool(dec_tx['vin'][0]['sequence'] == g.max_int - 2)
  529. # return (red,green)[rbf](str(rbf)) if color else rbf
  530. def is_rbf(self,color=False):
  531. ret = None < self.inputs[0].sequence <= g.max_int - 2
  532. return (red,green)[ret](str(ret)) if color else ret
  533. def signal_for_rbf(self):
  534. self.inputs[0].sequence = g.max_int - 2
  535. def format_view(self,terse=False):
  536. # self.pdie()
  537. try:
  538. blockcount = bitcoin_connection().getblockcount()
  539. except:
  540. blockcount = None
  541. hdr_fs = (
  542. 'TRANSACTION DATA\n\nHeader: [ID:{}] [{} BTC] [{} UTC] [RBF:{}] [Signed:{}]\n',
  543. 'Transaction {} {} BTC ({} UTC) RBF={} Signed={}\n'
  544. )[bool(terse)]
  545. out = hdr_fs.format(self.txid.hl(),self.send_amt.hl(),self.timestamp,
  546. self.is_rbf(color=True),self.marked_signed(color=True))
  547. enl = ('\n','')[bool(terse)]
  548. if self.chain in ('testnet','regtest'): out += green('Chain: {}\n'.format(self.chain.upper()))
  549. if self.btc_txid: out += 'Bitcoin TxID: {}\n'.format(self.btc_txid.hl())
  550. out += enl
  551. if self.label:
  552. out += 'Comment: %s\n%s' % (self.label.hl(),enl)
  553. out += 'Inputs:\n' + enl
  554. nonmm_str = '(non-{pnm} address){s} '.format(pnm=g.proj_name,s=('',' ')[terse])
  555. for n,e in enumerate(sorted(self.inputs,key=lambda o: o.mmid.sort_key if o.mmid else o.addr)):
  556. if blockcount:
  557. confs = e.confs + blockcount - self.blockcount
  558. days = int(confs * g.mins_per_block / (60*24))
  559. mmid_fmt = e.mmid.fmt(width=len(nonmm_str),encl='()',color=True) if e.mmid \
  560. else MMGenID.hlc(nonmm_str)
  561. if terse:
  562. out += '%3s: %s %s %s BTC' % (n+1, e.addr.fmt(color=True),mmid_fmt, e.amt.hl())
  563. else:
  564. for d in (
  565. (n+1, 'tx,vout:', '%s,%s' % (e.txid, e.vout)),
  566. ('', 'address:', e.addr.fmt(color=True) + ' ' + mmid_fmt),
  567. ('', 'comment:', e.label.hl() if e.label else ''),
  568. ('', 'amount:', '%s BTC' % e.amt.hl()),
  569. ('', 'confirmations:', '%s (around %s days)' % (confs,days) if blockcount else '')
  570. ):
  571. if d[2]: out += ('%3s %-8s %s\n' % d)
  572. out += '\n'
  573. out += 'Outputs:\n' + enl
  574. for n,e in enumerate(sorted(self.outputs,key=lambda o: o.mmid.sort_key if o.mmid else o.addr)):
  575. if e.mmid:
  576. app=('',' (chg)')[bool(e.is_chg and terse)]
  577. mmid_fmt = e.mmid.fmt(width=len(nonmm_str),encl='()',color=True,
  578. app=app,appcolor='green')
  579. else:
  580. mmid_fmt = MMGenID.hlc(nonmm_str)
  581. if terse:
  582. out += '%3s: %s %s %s BTC' % (n+1, e.addr.fmt(color=True),mmid_fmt, e.amt.hl())
  583. else:
  584. for d in (
  585. (n+1, 'address:', e.addr.fmt(color=True) + ' ' + mmid_fmt),
  586. ('', 'comment:', e.label.hl() if e.label else ''),
  587. ('', 'amount:', '%s BTC' % e.amt.hl()),
  588. ('', 'change:', green('True') if e.is_chg else '')
  589. ):
  590. if d[2]: out += ('%3s %-8s %s\n' % d)
  591. out += '\n'
  592. fs = (
  593. 'Total input: %s BTC\nTotal output: %s BTC\nTX fee: %s BTC (%s satoshis per byte)\n',
  594. 'In %s BTC - Out %s BTC - Fee %s BTC (%s satoshis/byte)\n'
  595. )[bool(terse)]
  596. total_in = self.sum_inputs()
  597. total_out = self.sum_outputs()
  598. out += fs % (
  599. total_in.hl(),
  600. total_out.hl(),
  601. (total_in-total_out).hl(),
  602. pink(str(self.btc2spb(total_in-total_out))),
  603. )
  604. if opt.verbose:
  605. ts = len(self.hex)/2 if self.hex else 'unknown'
  606. out += 'Transaction size: Vsize={} Actual={}'.format(self.estimate_size(),ts)
  607. if self.marked_signed():
  608. ws = DeserializedTX(self.hex)['witness_size']
  609. out += ' Base={} Witness={}'.format(ts-ws,ws)
  610. out += '\n'
  611. # TX label might contain non-ascii chars
  612. return out
  613. def parse_tx_file(self,infile):
  614. self.parse_tx_data(get_lines_from_file(infile,self.desc+' data'))
  615. def parse_tx_data(self,tx_data):
  616. def do_err(s): die(2,'Invalid %s in transaction file' % s)
  617. if len(tx_data) < 5: do_err('number of lines')
  618. self.chksum = HexStr(tx_data.pop(0))
  619. if self.chksum != make_chksum_6(' '.join(tx_data)):
  620. do_err('checksum')
  621. if len(tx_data) == 6:
  622. self.btc_txid = BitcoinTxID(tx_data.pop(-1),on_fail='return')
  623. if not self.btc_txid:
  624. do_err('Bitcoin TxID')
  625. if len(tx_data) == 5:
  626. c = tx_data.pop(-1)
  627. if c != '-':
  628. from mmgen.bitcoin import b58decode
  629. comment = b58decode(c)
  630. if comment == False:
  631. do_err('encoded comment (not base58)')
  632. else:
  633. self.label = MMGenTXLabel(comment,on_fail='return')
  634. if not self.label:
  635. do_err('comment')
  636. else:
  637. comment = ''
  638. if len(tx_data) == 4:
  639. metadata,self.hex,inputs_data,outputs_data = tx_data
  640. else:
  641. do_err('number of lines')
  642. metadata = metadata.split()
  643. if len(metadata) not in (4,5): do_err('metadata')
  644. if len(metadata) == 5:
  645. t = metadata.pop(0)
  646. self.chain = (t.lower(),None)[t=='Unknown']
  647. self.txid,send_amt,self.timestamp,blockcount = metadata
  648. self.txid = MMGenTxID(self.txid)
  649. self.send_amt = BTCAmt(send_amt)
  650. self.blockcount = int(blockcount)
  651. self.hex = HexStr(self.hex)
  652. try: unhexlify(self.hex)
  653. except: do_err('hex data')
  654. try: self.inputs = self.decode_io('inputs',eval(inputs_data))
  655. except: do_err('inputs data')
  656. if not self.chain and not self.inputs[0].addr.testnet:
  657. self.chain = 'mainnet'
  658. try: self.outputs = self.decode_io('outputs',eval(outputs_data))
  659. except: do_err('btc-to-mmgen address map data')
  660. class MMGenBumpTX(MMGenTX):
  661. min_fee = None
  662. bump_output_idx = None
  663. def __init__(self,filename,send=False):
  664. super(type(self),self).__init__(filename)
  665. if not self.is_rbf():
  666. die(1,"Transaction '{}' is not replaceable (RBF)".format(self.txid))
  667. # If sending, require tx to have been signed
  668. if send:
  669. if not self.marked_signed():
  670. die(1,"File '{}' is not a signed {} transaction file".format(filename,g.proj_name))
  671. if not self.btc_txid:
  672. die(1,"Transaction '{}' was not broadcast to the network".format(self.txid,g.proj_name))
  673. self.btc_txid = ''
  674. self.mark_raw()
  675. def choose_output(self):
  676. chg_idx = self.get_chg_output_idx()
  677. init_reply = opt.output_to_reduce
  678. while True:
  679. if init_reply == None:
  680. m = 'Choose an output to deduct the fee from (Hit ENTER for the change output): '
  681. reply = my_raw_input(m) or 'c'
  682. else:
  683. reply,init_reply = init_reply,None
  684. if chg_idx == None and not is_int(reply):
  685. msg("Output must be an integer")
  686. elif chg_idx != None and not is_int(reply) and reply != 'c':
  687. msg("Output must be an integer, or 'c' for the change output")
  688. else:
  689. idx = chg_idx if reply == 'c' else (int(reply) - 1)
  690. if idx < 0 or idx >= len(self.outputs):
  691. msg('Output must be in the range 1-{}'.format(len(self.outputs)))
  692. else:
  693. o_amt = self.outputs[idx].amt
  694. cs = ('',' (change output)')[chg_idx == idx]
  695. p = 'Fee will be deducted from output {}{} ({} BTC)'.format(idx+1,cs,o_amt)
  696. if o_amt < self.min_fee:
  697. msg('Minimum fee ({} BTC) is greater than output amount ({} BTC)'.format(
  698. self.min_fee,o_amt))
  699. elif opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  700. if opt.yes: msg(p)
  701. self.bump_output_idx = idx
  702. return idx
  703. def set_min_fee(self):
  704. self.min_fee = self.sum_inputs() - self.sum_outputs() + self.get_relay_fee()
  705. def get_usr_fee(self,tx_fee,desc):
  706. ret = super(type(self),self).get_usr_fee(tx_fee,desc)
  707. if ret < self.min_fee:
  708. msg('{} BTC: {} fee too small. Minimum fee: {} BTC ({} satoshis per byte)'.format(
  709. ret,desc,self.min_fee,self.btc2spb(self.min_fee)))
  710. return False
  711. output_amt = self.outputs[self.bump_output_idx].amt
  712. if ret >= output_amt:
  713. msg('{} BTC: {} fee too large. Maximum fee: <{} BTC'.format(ret,desc,output_amt))
  714. return False
  715. return ret