tx.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2018 The MMGen Project <mmgen@tuta.io>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. tx.py: Transaction routines for the MMGen suite
  21. """
  22. import sys,os
  23. from stat import *
  24. from binascii import unhexlify
  25. from mmgen.common import *
  26. from mmgen.obj import *
  27. pnm = g.proj_name
  28. wmsg = {
  29. 'addr_in_addrfile_only': """
  30. Warning: output address {mmgenaddr} is not in the tracking wallet, which means
  31. its balance will not be tracked. You're strongly advised to import the address
  32. into your tracking wallet before broadcasting this transaction.
  33. """.strip(),
  34. 'addr_not_found': """
  35. No data for {pnm} address {mmgenaddr} could be found in either the tracking
  36. wallet or the supplied address file. Please import this address into your
  37. tracking wallet, or supply an address file for it on the command line.
  38. """.strip(),
  39. 'addr_not_found_no_addrfile': """
  40. No data for {pnm} address {mmgenaddr} could be found in the tracking wallet.
  41. Please import this address into your tracking wallet or supply an address file
  42. for it on the command line.
  43. """.strip(),
  44. 'non_mmgen_inputs': """
  45. NOTE: This transaction includes non-{pnm} inputs, which makes the signing
  46. process more complicated. When signing the transaction, keys for non-{pnm}
  47. inputs must be supplied to '{pnl}-txsign' in a file with the '--keys-from-file'
  48. option.
  49. Selected non-{pnm} inputs: {{}}
  50. """.strip().format(pnm=pnm,pnl=pnm.lower()),
  51. 'not_enough_coin': """
  52. Selected outputs insufficient to fund this transaction ({{}} {} needed)
  53. """.strip().format(g.coin),
  54. 'no_change_output': """
  55. ERROR: No change address specified. If you wish to create a transaction with
  56. only one output, specify a single output address with no {} amount
  57. """.strip().format(g.coin),
  58. }
  59. def strfmt_locktime(num,terse=False):
  60. # Locktime itself is an unsigned 4-byte integer which can be parsed two ways:
  61. #
  62. # If less than 500 million, locktime is parsed as a block height. The transaction can be
  63. # added to any block which has this height or higher.
  64. # MMGen note: s/this height or higher/a higher block height/
  65. #
  66. # If greater than or equal to 500 million, locktime is parsed using the Unix epoch time
  67. # format (the number of seconds elapsed since 1970-01-01T00:00 UTC). The transaction can be
  68. # added to any block whose block time is greater than the locktime.
  69. if num >= 5 * 10**6:
  70. return ' '.join(time.strftime('%c',time.gmtime(num)).split()[1:])
  71. elif num > 0:
  72. return '{}{}'.format(('block height ','')[terse],num)
  73. elif num == None:
  74. return '(None)'
  75. else:
  76. die(2,"'{}': invalid locktime value!".format(num))
  77. def mmaddr2coinaddr(mmaddr,ad_w,ad_f):
  78. # assume mmaddr has already been checked
  79. coin_addr = ad_w.mmaddr2coinaddr(mmaddr)
  80. if not coin_addr:
  81. if ad_f:
  82. coin_addr = ad_f.mmaddr2coinaddr(mmaddr)
  83. if coin_addr:
  84. msg(wmsg['addr_in_addrfile_only'].format(mmgenaddr=mmaddr))
  85. if not keypress_confirm('Continue anyway?'):
  86. sys.exit(1)
  87. else:
  88. die(2,wmsg['addr_not_found'].format(pnm=pnm,mmgenaddr=mmaddr))
  89. else:
  90. die(2,wmsg['addr_not_found_no_addrfile'].format(pnm=pnm,mmgenaddr=mmaddr))
  91. return CoinAddr(coin_addr)
  92. def segwit_is_active(exit_on_error=False):
  93. d = g.rpch.getblockchaininfo()
  94. if d['chain'] == 'regtest':
  95. return True
  96. if 'segwit' in d['bip9_softforks'] and d['bip9_softforks']['segwit']['status'] == 'active':
  97. return True
  98. if g.skip_segwit_active_check:
  99. return True
  100. if exit_on_error:
  101. die(2,'Segwit not active on this chain. Exiting')
  102. else:
  103. return False
  104. def bytes2int(hex_bytes):
  105. r = hexlify(unhexlify(hex_bytes)[::-1])
  106. if r[0] in '89abcdef':
  107. die(3,"{}: Negative values not permitted in transaction!".format(hex_bytes))
  108. return int(r,16)
  109. def bytes2coin_amt(hex_bytes):
  110. return g.proto.coin_amt(bytes2int(hex_bytes) * g.proto.coin_amt.min_coin_unit)
  111. def scriptPubKey2addr(s):
  112. if len(s) == 50 and s[:6] == '76a914' and s[-4:] == '88ac':
  113. return g.proto.pubhash2addr(s[6:-4],p2sh=False),'p2pkh'
  114. elif len(s) == 46 and s[:4] == 'a914' and s[-2:] == '87':
  115. return g.proto.pubhash2addr(s[4:-2],p2sh=True),'p2sh'
  116. elif len(s) == 44 and s[:4] == g.proto.witness_vernum_hex + '14':
  117. return g.proto.pubhash2bech32addr(s[4:]),'bech32'
  118. else:
  119. raise NotImplementedError,'Unknown scriptPubKey ({})'.format(s)
  120. from collections import OrderedDict
  121. class DeserializedTX(OrderedDict,MMGenObject): # need to add MMGen types
  122. def __init__(self,txhex):
  123. tx = list(unhexlify(txhex))
  124. tx_copy = tx[:]
  125. d = { 'raw_tx':'' }
  126. def hshift(l,n,reverse=False,skip=False):
  127. ret = l[:n]
  128. if not skip: d['raw_tx'] += ''.join(ret)
  129. del l[:n]
  130. return hexlify(''.join(ret[::-1] if reverse else ret))
  131. # https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
  132. # For example, the number 515 is encoded as 0xfd0302.
  133. def readVInt(l,skip=False,sub_null=False):
  134. s = int(hexlify(l[0]),16)
  135. bytes_len = 1 if s < 0xfd else 2 if s == 0xfd else 4 if s == 0xfe else 8
  136. if bytes_len != 1: del l[0]
  137. ret = int(hexlify(''.join(l[:bytes_len][::-1])),16)
  138. if sub_null: d['raw_tx'] += '\0'
  139. elif not skip: d['raw_tx'] += ''.join(l[:bytes_len])
  140. del l[:bytes_len]
  141. return ret
  142. d['version'] = bytes2int(hshift(tx,4))
  143. has_witness = tx[0] == '\x00'
  144. if has_witness:
  145. u = hshift(tx,2,skip=True)[2:]
  146. if u != '01':
  147. die(2,"'{}': Illegal value for flag in transaction!".format(u))
  148. del tx_copy[-len(tx)-2:-len(tx)]
  149. d['num_txins'] = readVInt(tx)
  150. d['txins'] = MMGenList([OrderedDict((
  151. ('txid', hshift(tx,32,reverse=True)),
  152. ('vout', bytes2int(hshift(tx,4))),
  153. ('scriptSig', hshift(tx,readVInt(tx,sub_null=True),skip=True)),
  154. ('nSeq', hshift(tx,4,reverse=True))
  155. )) for i in range(d['num_txins'])])
  156. d['num_txouts'] = readVInt(tx)
  157. d['txouts'] = MMGenList([OrderedDict((
  158. ('amount', bytes2coin_amt(hshift(tx,8))),
  159. ('scriptPubKey', hshift(tx,readVInt(tx)))
  160. )) for i in range(d['num_txouts'])])
  161. for o in d['txouts']:
  162. o['address'] = scriptPubKey2addr(o['scriptPubKey'])[0]
  163. d['witness_size'] = 0
  164. if has_witness:
  165. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  166. # A non-witness program (defined hereinafter) txin MUST be associated with an empty
  167. # witness field, represented by a 0x00.
  168. del tx_copy[-len(tx):-4]
  169. wd,tx = tx[:-4],tx[-4:]
  170. d['witness_size'] = len(wd) + 2 # add marker and flag
  171. for i in range(len(d['txins'])):
  172. if hexlify(wd[0]) == '00':
  173. hshift(wd,1,skip=True)
  174. continue
  175. d['txins'][i]['witness'] = [
  176. hshift(wd,readVInt(wd,skip=True),skip=True) for item in range(readVInt(wd,skip=True))
  177. ]
  178. if wd:
  179. die(3,'More witness data than inputs with witnesses!')
  180. d['lock_time'] = bytes2int(hshift(tx,4))
  181. d['txid'] = hexlify(sha256(sha256(''.join(tx_copy)).digest()).digest()[::-1])
  182. d['unsigned_hex'] = hexlify(d['raw_tx'])
  183. del d['raw_tx']
  184. keys = 'txid','version','lock_time','witness_size','num_txins','txins','num_txouts','txouts','unsigned_hex'
  185. return OrderedDict.__init__(self, ((k,d[k]) for k in keys))
  186. txio_attrs = {
  187. 'vout': MMGenListItemAttr('vout',int,typeconv=False),
  188. 'amt': MMGenImmutableAttr('amt',g.proto.coin_amt,typeconv=False), # require amt to be of proper type
  189. 'label': MMGenListItemAttr('label','TwComment',reassign_ok=True),
  190. 'mmid': MMGenListItemAttr('mmid','MMGenID'),
  191. 'addr': MMGenImmutableAttr('addr','CoinAddr'),
  192. 'confs': MMGenListItemAttr('confs',int,typeconv=True), # long confs exist in the wild, so convert
  193. 'txid': MMGenListItemAttr('txid','CoinTxID'),
  194. 'have_wif': MMGenListItemAttr('have_wif',bool,typeconv=False,delete_ok=True)
  195. }
  196. class MMGenTX(MMGenObject):
  197. ext = 'rawtx'
  198. raw_ext = 'rawtx'
  199. sig_ext = 'sigtx'
  200. txid_ext = 'txid'
  201. desc = 'transaction'
  202. chg_msg_fs = 'Transaction produces {} {} in change'
  203. fee_fail_fs = 'Network fee estimation for {c} confirmations failed ({t})'
  204. no_chg_msg = 'Warning: Change address will be deleted as transaction produces no change'
  205. rel_fee_desc = 'satoshis per byte'
  206. rel_fee_disp = 'satoshis per byte'
  207. txview_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  208. txview_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  209. usr_fee_prompt = 'Enter transaction fee: '
  210. class MMGenTxInput(MMGenListItem):
  211. for k in txio_attrs: locals()[k] = txio_attrs[k] # in lieu of inheritance
  212. scriptPubKey = MMGenListItemAttr('scriptPubKey','HexStr')
  213. sequence = MMGenListItemAttr('sequence',(int,long)[g.platform=='win'],typeconv=False)
  214. class MMGenTxOutput(MMGenListItem):
  215. for k in txio_attrs: locals()[k] = txio_attrs[k]
  216. is_chg = MMGenListItemAttr('is_chg',bool,typeconv=False)
  217. class MMGenTxInputList(list,MMGenObject):
  218. desc = 'transaction inputs'
  219. member_type = 'MMGenTxInput'
  220. def convert_coin(self,verbose=False):
  221. from mmgen.protocol import CoinProtocol
  222. io = getattr(MMGenTX,self.member_type)
  223. if verbose:
  224. msg('{}:'.format(self.desc.capitalize()))
  225. for i in self:
  226. d = i.__dict__
  227. d['amt'] = g.proto.coin_amt(d['amt'])
  228. i = io(**d)
  229. if verbose:
  230. pmsg(i.__dict__)
  231. def check_coin_mismatch(self):
  232. for i in self:
  233. if type(i.amt) != g.proto.coin_amt:
  234. die(2,'Coin mismatch in transaction: amount {} not of type {}!'.format(i.amt,g.proto.coin_amt))
  235. class MMGenTxOutputList(MMGenTxInputList):
  236. desc = 'transaction outputs'
  237. member_type = 'MMGenTxOutput'
  238. def __new__(cls,*args,**kwargs):
  239. if g.coin == 'ETH':
  240. from mmgen.altcoins.eth.tx import EthereumMMGenTX
  241. cls = EthereumMMGenTX
  242. return MMGenObject.__new__(cls,*args,**kwargs)
  243. def __init__(self,filename=None,coin_sym_only=False,caller=None,silent_open=False):
  244. self.inputs = self.MMGenTxInputList()
  245. self.outputs = self.MMGenTxOutputList()
  246. self.send_amt = g.proto.coin_amt('0') # total amt minus change
  247. self.fee = g.proto.coin_amt('0')
  248. self.hex = '' # raw serialized hex transaction
  249. self.label = MMGenTXLabel('')
  250. self.txid = ''
  251. self.coin_txid = ''
  252. self.timestamp = ''
  253. self.chksum = ''
  254. self.fmt_data = ''
  255. self.fn = ''
  256. self.blockcount = 0
  257. self.chain = None
  258. self.coin = None
  259. self.caller = caller
  260. self.locktime = None
  261. if filename:
  262. self.parse_tx_file(filename,coin_sym_only=coin_sym_only,silent_open=silent_open)
  263. if coin_sym_only: return
  264. self.check_pubkey_scripts()
  265. self.check_sigs() # marks the tx as signed
  266. # repeat with sign and send, because coin daemon could be restarted
  267. self.check_correct_chain(on_fail='die')
  268. def check_correct_chain(self,on_fail='return'):
  269. assert on_fail in ('return','die'),"'{}': invalid value for 'on_fail'".format(on_fail)
  270. m = 'Transaction is for {}, but current chain is {}!'.format(self.chain,g.chain)
  271. bad = self.chain and g.chain and self.chain != g.chain
  272. if bad and g.chain in g.proto.chain_aliases:
  273. bad = self.chain not in g.proto.chain_aliases[g.chain]
  274. if bad:
  275. msg(m) if on_fail == 'return' else die(2,m)
  276. return not bad
  277. def add_output(self,coinaddr,amt,is_chg=None):
  278. self.outputs.append(MMGenTX.MMGenTxOutput(addr=coinaddr,amt=amt,is_chg=is_chg))
  279. def get_chg_output_idx(self):
  280. for i in range(len(self.outputs)):
  281. if self.outputs[i].is_chg == True:
  282. return i
  283. return None
  284. def update_output_amt(self,idx,amt):
  285. o = self.outputs[idx].__dict__
  286. o['amt'] = amt
  287. self.outputs[idx] = MMGenTX.MMGenTxOutput(**o)
  288. def del_output(self,idx):
  289. self.outputs.pop(idx)
  290. def sum_outputs(self,exclude=None):
  291. olist = self.outputs if exclude == None else \
  292. self.outputs[:exclude] + self.outputs[exclude+1:]
  293. return g.proto.coin_amt(sum(e.amt for e in olist))
  294. def add_mmaddrs_to_outputs(self,ad_w,ad_f):
  295. a = [e.addr for e in self.outputs]
  296. d = ad_w.make_reverse_dict(a)
  297. if ad_f:
  298. d.update(ad_f.make_reverse_dict(a))
  299. for e in self.outputs:
  300. if e.addr and e.addr in d:
  301. e.mmid,f = d[e.addr]
  302. if f: e.label = f
  303. def check_dup_addrs(self,io_str):
  304. assert io_str in ('inputs','outputs')
  305. io = getattr(self,io_str)
  306. for k in ('mmid','addr'):
  307. old_attr = None
  308. for attr in sorted(getattr(e,k) for e in io):
  309. if attr != None and attr == old_attr:
  310. die(2,'{}: duplicate address in transaction {}'.format(attr,io_str))
  311. old_attr = attr
  312. def update_txid(self):
  313. self.txid = MMGenTxID(make_chksum_6(unhexlify(self.hex)).upper())
  314. def create_raw(self):
  315. i = [{'txid':e.txid,'vout':e.vout} for e in self.inputs]
  316. if self.inputs[0].sequence:
  317. i[0]['sequence'] = self.inputs[0].sequence
  318. o = dict([(e.addr,e.amt) for e in self.outputs])
  319. self.hex = g.rpch.createrawtransaction(i,o)
  320. self.update_txid()
  321. # returns true if comment added or changed
  322. def add_comment(self,infile=None):
  323. if infile:
  324. self.label = MMGenTXLabel(get_data_from_file(infile,'transaction comment'))
  325. else: # get comment from user, or edit existing comment
  326. m = ('Add a comment to transaction?','Edit transaction comment?')[bool(self.label)]
  327. if keypress_confirm(m,default_yes=False):
  328. while True:
  329. s = MMGenTXLabel(my_raw_input('Comment: ',insert_txt=self.label))
  330. if s:
  331. lbl_save = self.label
  332. self.label = s
  333. return (True,False)[lbl_save == self.label]
  334. else:
  335. msg('Invalid comment')
  336. return False
  337. def edit_comment(self):
  338. return self.add_comment(self)
  339. def get_fee_from_tx(self):
  340. return self.sum_inputs() - self.sum_outputs()
  341. def has_segwit_inputs(self):
  342. return any(i.mmid and i.mmid.mmtype in ('S','B') for i in self.inputs)
  343. def compare_size_and_estimated_size(self):
  344. est_vsize = self.estimate_size()
  345. d = g.rpch.decoderawtransaction(self.hex)
  346. vsize = d['vsize'] if 'vsize' in d else d['size']
  347. vmsg('\nSize: {}, Vsize: {} (true) {} (estimated)'.format(d['size'],vsize,est_vsize))
  348. m1 = '\nERROR: Estimated transaction vsize is {:1.2f} times the true vsize\n'
  349. m2 = 'Your transaction fee estimates will be inaccurate\n'
  350. m3 = 'Please re-create and re-sign the transaction using the option --vsize-adj={:1.2f}'
  351. # allow for 5% error
  352. ratio = float(est_vsize) / vsize
  353. if not (0.95 < ratio < 1.05):
  354. die(2,(m1+m2+m3).format(ratio,1/ratio))
  355. # https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
  356. # 180: uncompressed, 148: compressed
  357. def estimate_size_old(self):
  358. if not self.inputs or not self.outputs: return None
  359. return len(self.inputs)*180 + len(self.outputs)*34 + 10
  360. # https://bitcoincore.org/en/segwit_wallet_dev/
  361. # vsize: 3 times of the size with original serialization, plus the size with new
  362. # serialization, divide the result by 4 and round up to the next integer.
  363. # TODO: results differ slightly from actual transaction size
  364. def estimate_size(self):
  365. if not self.inputs or not self.outputs: return None
  366. sig_size = 72 # sig in DER format
  367. pubkey_size_uncompressed = 65
  368. pubkey_size_compressed = 33
  369. def get_inputs_size():
  370. # txid vout [scriptSig size (vInt)] scriptSig (<sig> <pubkey>) nSeq
  371. isize_common = 32 + 4 + 1 + 4 # txid vout [scriptSig size] nSeq = 41
  372. input_size = {
  373. 'L': isize_common + sig_size + pubkey_size_uncompressed, # = 180
  374. 'C': isize_common + sig_size + pubkey_size_compressed, # = 148
  375. 'S': isize_common + 23, # = 64
  376. 'B': isize_common + 0 # = 41
  377. }
  378. ret = sum(input_size[i.mmid.mmtype] for i in self.inputs if i.mmid)
  379. # We have no way of knowing whether a non-MMGen addr is compressed or uncompressed until
  380. # we see the key, so assume compressed for fee-estimation purposes. If fee estimate is
  381. # off by more than 5%, sign() aborts and user is instructed to use --vsize-adj option
  382. return ret + sum(input_size['C'] for i in self.inputs if not i.mmid)
  383. def get_outputs_size():
  384. # output bytes = amt: 8, byte_count: 1+, pk_script
  385. # pk_script bytes: p2pkh: 25, p2sh: 23, bech32: 22
  386. return sum({'p2pkh':34,'p2sh':32,'bech32':31}[o.addr.addr_fmt] for o in self.outputs)
  387. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  388. # The witness is a serialization of all witness data of the transaction. Each txin is
  389. # associated with a witness field. A witness field starts with a var_int to indicate the
  390. # number of stack items for the txin. It is followed by stack items, with each item starts
  391. # with a var_int to indicate the length. Witness data is NOT script.
  392. # A non-witness program txin MUST be associated with an empty witness field, represented
  393. # by a 0x00. If all txins are not witness program, a transaction's wtxid is equal to its txid.
  394. def get_witness_size():
  395. if not self.has_segwit_inputs(): return 0
  396. wf_size = 1 + 1 + sig_size + 1 + pubkey_size_compressed # vInt vInt sig vInt pubkey = 108
  397. return sum((1,wf_size)[bool(i.mmid) and i.mmid.mmtype in ('S','B')] for i in self.inputs)
  398. isize = get_inputs_size()
  399. osize = get_outputs_size()
  400. wsize = get_witness_size()
  401. # TODO: compute real varInt sizes instead of assuming 1 byte
  402. # old serialization: [nVersion] [vInt][txins][vInt][txouts] [nLockTime]
  403. old_size = 4 + 1 + isize + 1 + osize + 4
  404. # marker = 0x00, flag = 0x01
  405. # new serialization: [nVersion][marker][flag][vInt][txins][vInt][txouts][witness][nLockTime]
  406. new_size = 4 + 1 + 1 + 1 + isize + 1 + osize + wsize + 4 \
  407. if wsize else old_size
  408. ret = (old_size * 3 + new_size) / 4
  409. dmsg('\nData from estimate_size():')
  410. dmsg(' inputs size: {}, outputs size: {}, witness size: {}'.format(isize,osize,wsize))
  411. dmsg(' size: {}, vsize: {}, old_size: {}'.format(new_size,ret,old_size))
  412. return int(ret * float(opt.vsize_adj)) if hasattr(opt,'vsize_adj') and opt.vsize_adj else ret
  413. # coin-specific fee routines
  414. def get_relay_fee(self):
  415. kb_fee = g.proto.coin_amt(g.rpch.getnetworkinfo()['relayfee'])
  416. ret = kb_fee * self.estimate_size() / 1024
  417. vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=g.coin))
  418. return ret
  419. # convert absolute BTC fee to satoshis-per-byte using estimated size
  420. def fee_abs2rel(self,abs_fee):
  421. return int(abs_fee/g.proto.coin_amt.min_coin_unit/self.estimate_size())
  422. def get_rel_fee_from_network(self): # rel_fee is in BTC/kB
  423. try:
  424. ret = g.rpch.estimatesmartfee(opt.tx_confs,on_fail='raise')
  425. rel_fee = ret['feerate'] if 'feerate' in ret else -2
  426. fe_type = 'estimatesmartfee'
  427. except:
  428. rel_fee = g.rpch.estimatefee(opt.tx_confs)
  429. fe_type = 'estimatefee'
  430. return rel_fee,fe_type
  431. # given tx size, rel fee and units, return absolute fee
  432. def convert_fee_spec(self,tx_size,units,amt,unit):
  433. self.usr_rel_fee = None # TODO
  434. return g.proto.coin_amt(int(amt)*tx_size*getattr(g.proto.coin_amt,units[unit])) \
  435. if tx_size else None
  436. # given network fee estimate in BTC/kB, return absolute fee using estimated tx size
  437. def fee_est2abs(self,rel_fee,fe_type=None):
  438. tx_size = self.estimate_size()
  439. ret = g.proto.coin_amt(rel_fee) * opt.tx_fee_adj * tx_size / 1024
  440. if opt.verbose:
  441. msg('{} fee for {} confirmations: {} {}/kB'.format(fe_type.upper(),opt.tx_confs,rel_fee,g.coin))
  442. msg('TX size (estimated): {}'.format(tx_size))
  443. return ret
  444. def convert_and_check_fee(self,tx_fee,desc='Missing description'):
  445. abs_fee = self.process_fee_spec(tx_fee,self.estimate_size(),on_fail='return')
  446. if abs_fee == None:
  447. # we shouldn't be calling this if tx size is unknown
  448. m = "'{}': cannot convert {} to {} because transaction size is unknown"
  449. assert False, m.format(tx_fee,self.rel_fee_desc,g.coin)
  450. elif abs_fee == False:
  451. m = "'{}': invalid TX fee (not a {} amount or {} specification)"
  452. msg(m.format(tx_fee,g.coin,self.rel_fee_desc))
  453. return False
  454. elif abs_fee > g.proto.max_tx_fee:
  455. m = '{} {c}: {} fee too large (maximum fee: {} {c})'
  456. msg(m.format(abs_fee,desc,g.proto.max_tx_fee,c=g.coin))
  457. return False
  458. elif abs_fee < self.get_relay_fee():
  459. m = '{} {c}: {} fee too small (below relay fee of {} {c})'
  460. msg(m.format(str(abs_fee),desc,str(self.get_relay_fee()),c=g.coin))
  461. return False
  462. else:
  463. return abs_fee
  464. # non-coin-specific fee routines
  465. # given tx size and absolute fee or fee spec, return absolute fee
  466. # relative fee is N+<first letter of unit name>
  467. def process_fee_spec(self,tx_fee,tx_size,on_fail='throw'):
  468. import re
  469. units = dict((u[0],u) for u in g.proto.coin_amt.units)
  470. pat = r'([1-9][0-9]*)({})'.format('|'.join(units.keys()))
  471. if g.proto.coin_amt(tx_fee,on_fail='silent'):
  472. return g.proto.coin_amt(tx_fee)
  473. elif re.match(pat,tx_fee):
  474. return self.convert_fee_spec(tx_size,units,*re.match(pat,tx_fee).groups())
  475. else:
  476. if on_fail == 'return':
  477. return False
  478. elif on_fail == 'throw':
  479. assert False, "'{}': invalid tx-fee argument".format(tx_fee)
  480. def get_usr_fee_interactive(self,tx_fee=None,desc='Starting'):
  481. abs_fee = None
  482. while True:
  483. if tx_fee:
  484. abs_fee = self.convert_and_check_fee(tx_fee,desc)
  485. if abs_fee:
  486. m = ('',' (after {}x adjustment)'.format(opt.tx_fee_adj))[opt.tx_fee_adj != 1]
  487. p = u'{} TX fee{}: {} {} ({} {})\n'.format(
  488. desc,
  489. m,
  490. abs_fee.hl(),
  491. g.coin,
  492. pink(str(self.fee_abs2rel(abs_fee))),
  493. self.rel_fee_disp)
  494. if opt.yes or keypress_confirm(p+'OK?',default_yes=True):
  495. if opt.yes: msg(p)
  496. return abs_fee
  497. tx_fee = my_raw_input(self.usr_fee_prompt)
  498. desc = 'User-selected'
  499. def get_fee_from_user(self,have_estimate_fail=[]):
  500. if opt.tx_fee:
  501. desc = 'User-selected'
  502. start_fee = opt.tx_fee
  503. else:
  504. desc = 'Network-estimated'
  505. rel_fee,fe_type = self.get_rel_fee_from_network()
  506. if rel_fee < 0:
  507. if not have_estimate_fail:
  508. msg(self.fee_fail_fs.format(c=opt.tx_confs,t=fe_type))
  509. have_estimate_fail.append(True)
  510. start_fee = None
  511. else:
  512. start_fee = self.fee_est2abs(rel_fee,fe_type)
  513. return self.get_usr_fee_interactive(start_fee,desc=desc)
  514. def delete_attrs(self,desc,attr):
  515. for e in getattr(self,desc):
  516. if hasattr(e,attr): delattr(e,attr)
  517. def decode_io_oldfmt(self,data):
  518. tr = {'amount':'amt', 'address':'addr', 'confirmations':'confs','comment':'label'}
  519. tr_rev = dict(map(reversed,tr.items()))
  520. copy_keys = [tr_rev[k] if k in tr_rev else k for k in self.MMGenTxInput.__dict__]
  521. ret = MMGenList(self.MMGenTxInput(**dict([(tr[k] if k in tr else k,d[k])
  522. for k in copy_keys if k in d and d[k] != ''])) for d in data)
  523. for i in ret: i.sequence = int('0xffffffff',16)
  524. return ret
  525. # inputs methods
  526. def copy_inputs_from_tw(self,tw_unspent_data):
  527. txi,self.inputs = self.MMGenTxInput,self.MMGenTxInputList()
  528. for d in tw_unspent_data:
  529. t = txi(**dict([(attr,getattr(d,attr)) for attr in d.__dict__ if attr in txi.__dict__]))
  530. if d.twmmid.type == 'mmgen': t.mmid = d.twmmid # twmmid -> mmid
  531. self.inputs.append(t)
  532. def get_input_sids(self):
  533. return set(e.mmid.sid for e in self.inputs if e.mmid)
  534. def get_output_sids(self):
  535. return set(e.mmid.sid for e in self.outputs if e.mmid)
  536. def sum_inputs(self):
  537. return sum(e.amt for e in self.inputs)
  538. def add_timestamp(self):
  539. self.timestamp = make_timestamp()
  540. def get_hex_locktime(self):
  541. return int(hexlify(unhexlify(self.hex[-8:])[::-1]),16)
  542. def set_hex_locktime(self,val):
  543. assert type(val) == int,'locktime value not an integer'
  544. self.hex = self.hex[:-8] + hexlify(unhexlify('{:08x}'.format(val))[::-1])
  545. def get_blockcount(self):
  546. return int(g.rpch.getblockcount())
  547. def add_blockcount(self):
  548. self.blockcount = self.get_blockcount()
  549. def format(self):
  550. self.inputs.check_coin_mismatch()
  551. self.outputs.check_coin_mismatch()
  552. def amt_to_str(d):
  553. return dict([(k,str(d[k]) if k == 'amt' else d[k]) for k in d])
  554. lines = [
  555. '{}{} {} {} {} {}{}'.format(
  556. (g.coin+' ','')[g.coin=='BTC'],
  557. self.chain.upper() if self.chain else 'Unknown',
  558. self.txid,
  559. self.send_amt,
  560. self.timestamp,
  561. self.blockcount,
  562. ('',' LT={}'.format(self.locktime))[bool(self.locktime)]
  563. ),
  564. self.hex,
  565. repr([amt_to_str(e.__dict__) for e in self.inputs]),
  566. repr([amt_to_str(e.__dict__) for e in self.outputs])
  567. ]
  568. if self.label:
  569. lines.append(baseconv.b58encode(self.label.encode('utf8')))
  570. if self.coin_txid:
  571. if not self.label: lines.append('-') # keep old tx files backwards compatible
  572. lines.append(self.coin_txid)
  573. self.chksum = make_chksum_6(' '.join(lines))
  574. self.fmt_data = '\n'.join([self.chksum] + lines)+'\n'
  575. assert len(self.fmt_data) <= g.max_tx_file_size,(
  576. 'Transaction file size exceeds limit ({} bytes)'.format(g.max_tx_file_size))
  577. def get_non_mmaddrs(self,desc):
  578. return list(set(i.addr for i in getattr(self,desc) if not i.mmid))
  579. # return true or false; don't exit
  580. def sign(self,tx_num_str,keys):
  581. if self.marked_signed():
  582. msg('Transaction is already signed!')
  583. return False
  584. if not self.check_correct_chain(on_fail='return'):
  585. return False
  586. if (self.has_segwit_inputs() or self.has_segwit_outputs()) and not g.proto.cap('segwit'):
  587. ymsg("TX has Segwit inputs or outputs, but {} doesn't support Segwit!".format(g.coin))
  588. return False
  589. self.check_pubkey_scripts()
  590. qmsg('Passing {} key{} to {}'.format(len(keys),suf(keys,'s'),g.proto.daemon_name))
  591. if self.has_segwit_inputs():
  592. from mmgen.addr import KeyGenerator,AddrGenerator
  593. kg = KeyGenerator('std')
  594. ag = AddrGenerator('segwit')
  595. keydict = MMGenDict([(d.addr,d.sec) for d in keys])
  596. sig_data = []
  597. for d in self.inputs:
  598. e = dict([(k,getattr(d,k)) for k in ('txid','vout','scriptPubKey','amt')])
  599. e['amount'] = e['amt']
  600. del e['amt']
  601. if d.mmid and d.mmid.mmtype == 'S':
  602. e['redeemScript'] = ag.to_segwit_redeem_script(kg.to_pubhex(keydict[d.addr]))
  603. sig_data.append(e)
  604. msg_r('Signing transaction{}...'.format(tx_num_str))
  605. wifs = [d.sec.wif for d in keys]
  606. ret = g.rpch.signrawtransaction(self.hex,sig_data,wifs,g.proto.sighash_type,on_fail='return')
  607. from mmgen.rpc import rpc_error,rpc_errmsg
  608. if rpc_error(ret):
  609. errmsg = rpc_errmsg(ret)
  610. if 'Invalid sighash param' in errmsg:
  611. m = 'This is not the BCH chain.'
  612. m += "\nRe-run the script without the --coin=bch option."
  613. else:
  614. m = errmsg
  615. msg(yellow(m))
  616. return False
  617. else:
  618. if ret['complete']:
  619. # Msg(pretty_hexdump(unhexlify(self.hex),cols=16)) # DEBUG
  620. # pmsg(make_chksum_6(unhexlify(self.hex)).upper())
  621. self.hex = ret['hex']
  622. self.compare_size_and_estimated_size()
  623. dt = DeserializedTX(self.hex)
  624. self.check_hex_tx_matches_mmgen_tx(dt)
  625. self.coin_txid = CoinTxID(dt['txid'],on_fail='return')
  626. self.check_sigs(dt)
  627. assert self.coin_txid == g.rpch.decoderawtransaction(self.hex)['txid'],(
  628. 'txid mismatch (after signing)')
  629. msg('OK')
  630. return True
  631. else:
  632. msg('failed\n{} returned the following errors:'.format(g.proto.daemon_name.capitalize()))
  633. msg(repr(ret['errors']))
  634. return False
  635. def mark_raw(self):
  636. self.desc = 'transaction'
  637. self.ext = self.raw_ext
  638. def mark_signed(self): # called ONLY by check_sigs()
  639. self.desc = 'signed transaction'
  640. self.ext = self.sig_ext
  641. def marked_signed(self,color=False):
  642. ret = self.desc == 'signed transaction'
  643. return (red,green)[ret](str(ret)) if color else ret
  644. # check that a malicious, compromised or malfunctioning coin daemon hasn't altered hex tx data:
  645. # does not check witness or signature data
  646. def check_hex_tx_matches_mmgen_tx(self,deserial_tx):
  647. m = 'Fatal error: a malicious or malfunctioning coin daemon or other program may have altered your data!'
  648. lt = deserial_tx['lock_time']
  649. if lt != int(self.locktime or 0):
  650. m2 = '\nTransaction hex locktime ({}) does not match MMGen transaction locktime ({})\n{}'
  651. rdie(3,m2.format(lt,self.locktime,m))
  652. def check_equal(desc,hexio,mmio):
  653. if mmio != hexio:
  654. msg('\nMMGen {}:\n{}'.format(desc,pformat(mmio)))
  655. msg('Hex {}:\n{}'.format(desc,pformat(hexio)))
  656. m2 = '{} in hex transaction data from coin daemon do not match those in MMGen transaction!\n'
  657. rdie(3,(m2+m).format(desc.capitalize()))
  658. seq_hex = map(lambda i: int(i['nSeq'],16),deserial_tx['txins'])
  659. seq_mmgen = map(lambda i: i.sequence or g.max_int,self.inputs)
  660. check_equal('sequence numbers',seq_hex,seq_mmgen)
  661. d_hex = sorted((i['txid'],i['vout']) for i in deserial_tx['txins'])
  662. d_mmgen = sorted((i.txid,i.vout) for i in self.inputs)
  663. check_equal('inputs',d_hex,d_mmgen)
  664. d_hex = sorted((o['address'],g.proto.coin_amt(o['amount'])) for o in deserial_tx['txouts'])
  665. d_mmgen = sorted((o.addr,o.amt) for o in self.outputs)
  666. check_equal('outputs',d_hex,d_mmgen)
  667. uh = deserial_tx['unsigned_hex']
  668. if str(self.txid) != make_chksum_6(unhexlify(uh)).upper():
  669. rdie(3,'MMGen TxID ({}) does not match hex transaction data!\n{}'.format(self.txid,m))
  670. def check_pubkey_scripts(self):
  671. for n,i in enumerate(self.inputs,1):
  672. addr,fmt = scriptPubKey2addr(i.scriptPubKey)
  673. if i.addr != addr:
  674. if fmt != i.addr.addr_fmt:
  675. m = 'Address format of scriptPubKey ({}) does not match that of address ({}) in input #{}'
  676. msg(m.format(fmt,i.addr.addr_fmt,n))
  677. m = 'ERROR: Address and scriptPubKey of transaction input #{} do not match!'
  678. die(3,(m+'\n {:23}{}'*3).format(n, 'address:',i.addr,
  679. 'scriptPubKey:',i.scriptPubKey,
  680. 'scriptPubKey->address:',addr ))
  681. # check signature and witness data
  682. def check_sigs(self,deserial_tx=None): # return False if no sigs, die on error
  683. txins = (deserial_tx or DeserializedTX(self.hex))['txins']
  684. has_ss = any(ti['scriptSig'] for ti in txins)
  685. has_witness = any('witness' in ti and ti['witness'] for ti in txins)
  686. if not (has_ss or has_witness):
  687. return False
  688. fs = "Hex TX has {} scriptSig but input is of type '{}'!"
  689. for n in range(len(txins)):
  690. ti,mmti = txins[n],self.inputs[n]
  691. if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH
  692. ti['scriptSig'][:6] == '16' + g.proto.witness_vernum_hex + '14' ):
  693. assert 'witness' in ti, 'missing witness'
  694. assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness'
  695. assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
  696. assert mmti.mmid, fs.format('witness-type','non-MMGen')
  697. assert mmti.mmid.mmtype == ('S','B')[ti['scriptSig']==''],fs.format('witness-type',mmti.mmid.mmtype)
  698. else: # non-witness
  699. if mmti.mmid:
  700. assert mmti.mmid.mmtype not in ('S','B'), fs.format('signature in',mmti.mmid.mmtype)
  701. assert not 'witness' in ti, 'non-witness input has witness'
  702. # sig_size 72 (DER format), pubkey_size 'compressed':33, 'uncompressed':65
  703. assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
  704. self.mark_signed()
  705. return True
  706. def has_segwit_outputs(self):
  707. return any(o.mmid and o.mmid.mmtype in ('S','B') for o in self.outputs)
  708. def is_in_mempool(self):
  709. return 'size' in g.rpch.getmempoolentry(self.coin_txid,on_fail='silent')
  710. def is_in_wallet(self):
  711. ret = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  712. if 'confirmations' in ret and ret['confirmations'] > 0:
  713. return ret['confirmations']
  714. else:
  715. return False
  716. def is_replaced(self):
  717. if self.is_in_mempool(): return False
  718. ret = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  719. if not 'bip125-replaceable' in ret or not 'confirmations' in ret or ret['confirmations'] > 0:
  720. return False
  721. return -ret['confirmations'] + 1,ret # 1: replacement in mempool, 2: replacement confirmed
  722. def is_in_utxos(self):
  723. return 'txid' in g.rpch.getrawtransaction(self.coin_txid,True,on_fail='silent')
  724. def get_status(self,status=False):
  725. if self.is_in_mempool():
  726. if status:
  727. d = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  728. brs = 'bip125-replaceable'
  729. r = '{}replaceable'.format(('NOT ','')[brs in d and d[brs]=='yes'])
  730. t = d['timereceived']
  731. m = 'Sent {} ({} h/m/s ago)'
  732. b = m.format(time.strftime('%c',time.gmtime(t)),secs_to_dhms(int(time.time()-t)))
  733. if opt.quiet:
  734. msg('Transaction is in mempool')
  735. else:
  736. msg('TX status: in mempool, {}\n{}'.format(r,b))
  737. else:
  738. msg('Warning: transaction is in mempool!')
  739. elif self.is_in_wallet():
  740. confs = self.is_in_wallet()
  741. die(0,'Transaction has {} confirmation{}'.format(confs,suf(confs,'s')))
  742. elif self.is_in_utxos():
  743. die(2,red('ERROR: transaction is in the blockchain (but not in the tracking wallet)!'))
  744. else:
  745. ret = self.is_replaced() # ret[0]==1: replacement in mempool, ret[0]==2: replacement confirmed
  746. if ret and ret[0]:
  747. m1 = 'Transaction has been replaced'
  748. m2 = ('',', and the replacement TX is confirmed')[ret[0]==2]
  749. msg('{}{}!'.format(m1,m2))
  750. if not opt.quiet:
  751. msg('Replacing transactions:')
  752. rt = ret[1]['walletconflicts']
  753. for t,s in [(tx,'size' in g.rpch.getmempoolentry(tx,on_fail='silent')) for tx in rt]:
  754. msg(' {}{}'.format(t,('',' in mempool')[s]))
  755. die(0,'')
  756. def confirm_send(self):
  757. m1 = ("Once this transaction is sent, there's no taking it back!",'')[bool(opt.quiet)]
  758. m2 = 'broadcast this transaction to the {} network'.format(g.chain.upper())
  759. m3 = ('YES, I REALLY WANT TO DO THIS','YES')[bool(opt.quiet or opt.yes)]
  760. confirm_or_exit(m1,m2,m3)
  761. msg('Sending transaction')
  762. def send(self,prompt_user=True,exit_on_fail=False):
  763. if not self.marked_signed():
  764. die(1,'Transaction is not signed!')
  765. self.check_correct_chain(on_fail='die')
  766. self.check_pubkey_scripts()
  767. self.check_hex_tx_matches_mmgen_tx(DeserializedTX(self.hex))
  768. bogus_send = os.getenv('MMGEN_BOGUS_SEND')
  769. if self.has_segwit_outputs() and not segwit_is_active() and not bogus_send:
  770. m = 'Transaction has MMGen Segwit outputs, but this blockchain does not support Segwit'
  771. die(2,m+' at the current height')
  772. if self.get_fee_from_tx() > g.proto.max_tx_fee:
  773. die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
  774. self.get_fee_from_tx(),g.proto.name.capitalize(),g.proto.max_tx_fee,g.coin))
  775. self.get_status()
  776. if prompt_user: self.confirm_send()
  777. ret = None if bogus_send else g.rpch.sendrawtransaction(self.hex,on_fail='return')
  778. from mmgen.rpc import rpc_error,rpc_errmsg
  779. if rpc_error(ret):
  780. errmsg = rpc_errmsg(ret)
  781. if 'Signature must use SIGHASH_FORKID' in errmsg:
  782. m = 'The Aug. 1 2017 UAHF has activated on this chain.'
  783. m += "\nRe-run the script with the --coin=bch option."
  784. elif 'Illegal use of SIGHASH_FORKID' in errmsg:
  785. m = 'The Aug. 1 2017 UAHF is not yet active on this chain.'
  786. m += "\nRe-run the script without the --coin=bch option."
  787. elif '64: non-final' in errmsg:
  788. m2 = "Transaction with locktime '{}' can't be included in this block!"
  789. m = m2.format(strfmt_locktime(self.get_hex_locktime()))
  790. else:
  791. m = errmsg
  792. msg(yellow(m))
  793. msg(red('Send of MMGen transaction {} failed'.format(self.txid)))
  794. if exit_on_fail: sys.exit(1)
  795. return False
  796. else:
  797. if bogus_send:
  798. m = 'BOGUS transaction NOT sent: {}'
  799. else:
  800. assert ret == self.coin_txid, 'txid mismatch (after sending)'
  801. m = 'Transaction sent: {}'
  802. self.desc = 'sent transaction'
  803. msg(m.format(self.coin_txid.hl()))
  804. self.add_timestamp()
  805. self.add_blockcount()
  806. return True
  807. def write_txid_to_file(self,ask_write=False,ask_write_default_yes=True):
  808. fn = '{}[{}].{}'.format(self.txid,self.send_amt,self.txid_ext)
  809. write_data_to_file(fn,self.coin_txid+'\n','transaction ID',
  810. ask_write=ask_write,
  811. ask_write_default_yes=ask_write_default_yes)
  812. def create_fn(self):
  813. tl = self.get_hex_locktime()
  814. tn = ('','.testnet')[g.proto.is_testnet()]
  815. self.fn = u'{}{}[{!s}{}{}]{x}{}.{}'.format(
  816. self.txid,
  817. ('-'+g.coin,'')[g.coin=='BTC'],
  818. self.send_amt,
  819. ('',',{}'.format(self.fee_abs2rel(self.get_fee_from_tx())))[self.is_rbf()],
  820. ('',',tl={}'.format(tl))[bool(tl)],
  821. tn,self.ext,
  822. x=u'-α' if g.debug_utf8 else '')
  823. def write_to_file( self,
  824. add_desc='',
  825. ask_write=True,
  826. ask_write_default_yes=False,
  827. ask_tty=True,
  828. ask_overwrite=True):
  829. if ask_write == False: ask_write_default_yes = True
  830. if not self.fmt_data: self.format()
  831. if not self.fn: self.create_fn()
  832. write_data_to_file(self.fn,self.fmt_data,self.desc+add_desc,
  833. ask_overwrite=ask_overwrite,
  834. ask_write=ask_write,
  835. ask_tty=ask_tty,
  836. ask_write_default_yes=ask_write_default_yes)
  837. def view_with_prompt(self,prompt=''):
  838. prompt += ' (y)es, (N)o, pager (v)iew, (t)erse view'
  839. reply = prompt_and_get_char(prompt,'YyNnVvTt',enter_ok=True)
  840. if reply and reply in 'YyVvTt':
  841. self.view(pager=reply in 'Vv',terse=reply in 'Tt')
  842. def view(self,pager=False,pause=True,terse=False):
  843. o = self.format_view(terse=terse)
  844. if pager: do_pager(o)
  845. else:
  846. msg_r(o)
  847. from mmgen.term import get_char
  848. if pause:
  849. get_char('Press any key to continue: ')
  850. msg('')
  851. # def is_rbf_from_rpc(self):
  852. # dec_tx = g.rpch.decoderawtransaction(self.hex)
  853. # return None < dec_tx['vin'][0]['sequence'] <= g.max_int - 2
  854. def is_rbf(self):
  855. return self.inputs[0].sequence == g.max_int - 2
  856. def format_view_body(self,blockcount,nonmm_str,max_mmwid,enl,terse):
  857. def format_io(desc):
  858. io = getattr(self,desc)
  859. ip = desc == 'inputs'
  860. out = desc.capitalize() + ':\n' + enl
  861. addr_w = max(len(e.addr) for e in io)
  862. confs_per_day = 60*60*24 / g.proto.secs_per_block
  863. for n,e in enumerate(sorted(io,key=lambda o: o.mmid.sort_key if o.mmid else o.addr)):
  864. if ip and blockcount:
  865. confs = e.confs + blockcount - self.blockcount
  866. days = int(confs / confs_per_day)
  867. if e.mmid:
  868. mmid_fmt = e.mmid.fmt(
  869. width=max_mmwid,
  870. encl='()',
  871. color=True,
  872. append_chars=('',' (chg)')[bool(not ip and e.is_chg and terse)],
  873. append_color='green')
  874. else:
  875. mmid_fmt = MMGenID.fmtc(nonmm_str,width=max_mmwid,color=True)
  876. if terse:
  877. out += '{:3} {} {} {} {}\n'.format(n+1,
  878. e.addr.fmt(color=True,width=addr_w),
  879. mmid_fmt,e.amt.hl(),g.coin)
  880. else:
  881. icommon = [
  882. ((n+1,'')[ip],'address:',e.addr.fmt(color=True,width=addr_w) + ' '+mmid_fmt),
  883. ('','comment:',e.label.hl() if e.label else ''),
  884. ('','amount:','{} {}'.format(e.amt.hl(),g.coin))]
  885. items = [(n+1, 'tx,vout:','{},{}'.format(e.txid,e.vout))] + icommon + [
  886. ('','confirmations:','{} (around {} days)'.format(confs,days) if blockcount else '')
  887. ] if ip else icommon + [
  888. ('','change:',green('True') if e.is_chg else '')]
  889. out += '\n'.join([(u'{:>3} {:<8} {}'.format(*d)) for d in items if d[2]]) + '\n\n'
  890. return out
  891. return format_io('inputs') + format_io('outputs')
  892. def format_view_rel_fee(self,terse):
  893. return ' ({} {})\n'.format(
  894. pink(str(self.fee_abs2rel(self.get_fee_from_tx()))),
  895. self.rel_fee_disp)
  896. def format_view_abs_fee(self):
  897. return g.proto.coin_amt(self.get_fee_from_tx()).hl()
  898. def format_view_verbose_footer(self):
  899. ts = len(self.hex)/2 if self.hex else 'unknown'
  900. out = 'Transaction size: Vsize {} (estimated), Total {}'.format(self.estimate_size(),ts)
  901. if self.marked_signed():
  902. ws = DeserializedTX(self.hex)['witness_size']
  903. out += ', Base {}, Witness {}'.format(ts-ws,ws)
  904. return out + '\n'
  905. def format_view(self,terse=False):
  906. try:
  907. rpc_init()
  908. blockcount = self.get_blockcount()
  909. except:
  910. blockcount = None
  911. def get_max_mmwid(io):
  912. if io == self.inputs:
  913. sel_f = lambda o: len(o.mmid) + 2 # len('()')
  914. else:
  915. sel_f = lambda o: len(o.mmid) + (2,8)[bool(o.is_chg)] # + len(' (chg)')
  916. return max(max([sel_f(o) for o in io if o.mmid] or [0]),len(nonmm_str))
  917. nonmm_str = '(non-{pnm} address)'.format(pnm=g.proj_name)
  918. max_mmwid = max(get_max_mmwid(self.inputs),get_max_mmwid(self.outputs))
  919. out = (self.txview_hdr_fs,self.txview_hdr_fs_short)[bool(terse)].format(
  920. i=self.txid.hl(),
  921. a=self.send_amt.hl(),
  922. c=g.coin,
  923. t=self.timestamp,
  924. r=(red('False'),green('True'))[self.is_rbf()],
  925. s=self.marked_signed(color=True),
  926. l=(green('None'),orange(strfmt_locktime(self.locktime,terse=True)))[bool(self.locktime)])
  927. if self.chain != 'mainnet':
  928. out += green('Chain: {}\n'.format(self.chain.upper()))
  929. if self.coin_txid:
  930. out += '{} TxID: {}\n'.format(g.coin,self.coin_txid.hl())
  931. enl = ('\n','')[bool(terse)]
  932. out += enl
  933. if self.label:
  934. out += u'Comment: {}\n{}'.format(self.label.hl(),enl)
  935. out += self.format_view_body(blockcount,nonmm_str,max_mmwid,enl,terse=terse)
  936. fs = (
  937. 'Total input: {i} {c}\nTotal output: {o} {c}\nTX fee: {a} {c}{r}\n',
  938. 'In {i} {c} - Out {o} {c}\nFee {a} {c}{r}\n'
  939. )[bool(terse)]
  940. out += fs.format(
  941. i=self.sum_inputs().hl(),
  942. o=self.sum_outputs().hl(),
  943. a=self.format_view_abs_fee(),
  944. r=self.format_view_rel_fee(terse),
  945. c=g.coin)
  946. if opt.verbose: out += self.format_view_verbose_footer()
  947. return out # TX label might contain non-ascii chars
  948. def check_tx_hex_data(self):
  949. self.hex = HexStr(self.hex,on_fail='raise')
  950. def parse_tx_file(self,infile,coin_sym_only=False,silent_open=False):
  951. def eval_io_data(raw_data,desc):
  952. from ast import literal_eval
  953. try:
  954. d = literal_eval(raw_data)
  955. except:
  956. if desc == 'inputs' and not silent_open:
  957. ymsg('Warning: transaction data appears to be in old format')
  958. import re
  959. d = literal_eval(re.sub(r"[A-Za-z]+?\(('.+?')\)",r'\1',raw_data))
  960. assert type(d) == list,'{} data not a list!'.format(desc)
  961. assert len(d),'no {}!'.format(desc)
  962. for e in d: e['amt'] = g.proto.coin_amt(e['amt'])
  963. io,io_list = (
  964. (MMGenTX.MMGenTxOutput,MMGenTX.MMGenTxOutputList),
  965. (MMGenTX.MMGenTxInput,MMGenTX.MMGenTxInputList)
  966. )[desc=='inputs']
  967. return io_list([io(**e) for e in d])
  968. tx_data = get_data_from_file(infile,self.desc+' data',silent=silent_open)
  969. try:
  970. desc = 'data'
  971. assert len(tx_data) <= g.max_tx_file_size,(
  972. 'Transaction file size exceeds limit ({} bytes)'.format(g.max_tx_file_size))
  973. tx_data = tx_data.decode('ascii').splitlines()
  974. assert len(tx_data) >= 5,'number of lines less than 5'
  975. assert len(tx_data[0]) == 6,'invalid length of first line'
  976. self.chksum = HexStr(tx_data.pop(0),on_fail='raise')
  977. assert self.chksum == make_chksum_6(' '.join(tx_data)),'file data does not match checksum'
  978. if len(tx_data) == 6:
  979. assert len(tx_data[-1]) == 64,'invalid coin TxID length'
  980. desc = '{} TxID'.format(g.proto.name.capitalize())
  981. self.coin_txid = CoinTxID(tx_data.pop(-1),on_fail='raise')
  982. if len(tx_data) == 5:
  983. # rough check: allow for 4-byte utf8 characters + base58 (4 * 11 / 8 = 6 (rounded up))
  984. assert len(tx_data[-1]) < MMGenTXLabel.max_len*6,'invalid comment length'
  985. c = tx_data.pop(-1)
  986. if c != '-':
  987. desc = 'encoded comment (not base58)'
  988. comment = baseconv.b58decode(c).decode('utf8')
  989. assert comment != False,'invalid comment'
  990. desc = 'comment'
  991. self.label = MMGenTXLabel(comment,on_fail='raise')
  992. desc = 'number of lines' # four required lines
  993. metadata,self.hex,inputs_data,outputs_data = tx_data
  994. assert len(metadata) < 100,'invalid metadata length' # rough check
  995. metadata = metadata.split()
  996. if metadata[-1].find('LT=') == 0:
  997. desc = 'locktime'
  998. self.locktime = int(metadata.pop()[3:])
  999. self.coin = metadata.pop(0) if len(metadata) == 6 else 'BTC'
  1000. if coin_sym_only: return
  1001. if len(metadata) == 5:
  1002. t = metadata.pop(0)
  1003. self.chain = (t.lower(),None)[t=='Unknown']
  1004. desc = 'metadata (4 items minimum required)'
  1005. self.txid,send_amt,self.timestamp,blockcount = metadata
  1006. desc = 'metadata'
  1007. self.txid = MMGenTxID(self.txid,on_fail='raise')
  1008. self.send_amt = g.proto.coin_amt(send_amt,on_fail='raise')
  1009. desc = 'block count in metadata'
  1010. self.blockcount = int(blockcount)
  1011. desc = 'transaction hex data'
  1012. self.check_tx_hex_data()
  1013. # the following ops will all fail if g.coin doesn't match self.coin
  1014. desc = 'coin type in metadata'
  1015. assert self.coin == g.coin,'invalid coin type: {}'.format(self.coin)
  1016. desc = 'inputs data'
  1017. self.inputs = eval_io_data(inputs_data,'inputs')
  1018. desc = 'outputs data'
  1019. self.outputs = eval_io_data(outputs_data,'outputs')
  1020. except Exception as e:
  1021. die(2,'Invalid {} in transaction file: {}'.format(desc,e[0]))
  1022. # test doesn't work for Ethereum
  1023. if not self.chain and not self.inputs[0].addr.is_for_chain('testnet'):
  1024. self.chain = 'mainnet'
  1025. def process_cmd_args(self,cmd_args,ad_f,ad_w):
  1026. for a in cmd_args:
  1027. if ',' in a:
  1028. a1,a2 = a.split(',',1)
  1029. if is_mmgen_id(a1) or is_coin_addr(a1):
  1030. coin_addr = mmaddr2coinaddr(a1,ad_w,ad_f) if is_mmgen_id(a1) else CoinAddr(a1)
  1031. self.add_output(coin_addr,g.proto.coin_amt(a2))
  1032. else:
  1033. die(2,"{}: invalid subargument in command-line argument '{}'".format(a1,a))
  1034. elif is_mmgen_id(a) or is_coin_addr(a):
  1035. if self.get_chg_output_idx() != None:
  1036. die(2,'ERROR: More than one change address listed on command line')
  1037. coin_addr = mmaddr2coinaddr(a,ad_w,ad_f) if is_mmgen_id(a) else CoinAddr(a)
  1038. self.add_output(coin_addr,g.proto.coin_amt('0'),is_chg=True)
  1039. else:
  1040. die(2,'{}: invalid command-line argument'.format(a))
  1041. if self.get_chg_output_idx() == None:
  1042. die(2,('ERROR: No change output specified',wmsg['no_change_output'])[len(self.outputs) == 1])
  1043. if not segwit_is_active() and self.has_segwit_outputs():
  1044. fs = '{} Segwit address requested on the command line, but Segwit is not active on this chain'
  1045. rdie(2,fs.format(g.proj_name))
  1046. def get_outputs_from_cmdline(self,cmd_args):
  1047. from mmgen.addr import AddrList,AddrData
  1048. addrfiles = [a for a in cmd_args if get_extension(a) == AddrList.ext]
  1049. cmd_args = set(cmd_args) - set(addrfiles)
  1050. ad_f = AddrData()
  1051. for a in addrfiles:
  1052. check_infile(a)
  1053. ad_f.add(AddrList(a))
  1054. ad_w = AddrData(source='tw')
  1055. self.process_cmd_args(cmd_args,ad_f,ad_w)
  1056. if not self.outputs:
  1057. die(2,'At least one output must be specified on the command line')
  1058. self.add_mmaddrs_to_outputs(ad_w,ad_f)
  1059. self.check_dup_addrs('outputs')
  1060. def select_unspent(self,unspent):
  1061. prompt = 'Enter a range or space-separated list of outputs to spend: '
  1062. while True:
  1063. reply = my_raw_input(prompt).strip()
  1064. if reply:
  1065. selected = AddrIdxList(fmt_str=','.join(reply.split()),on_fail='return')
  1066. if selected:
  1067. if selected[-1] <= len(unspent):
  1068. return selected
  1069. msg('Unspent output number must be <= {}'.format(len(unspent)))
  1070. def get_inputs_from_user(self,tw):
  1071. while True:
  1072. sel_nums = self.select_unspent(tw.unspent)
  1073. msg('Selected output{}: {}'.format(suf(sel_nums,'s'),' '.join(map(str,sel_nums))))
  1074. sel_unspent = tw.MMGenTwOutputList([tw.unspent[i-1] for i in sel_nums])
  1075. t_inputs = sum(s.amt for s in sel_unspent)
  1076. if t_inputs < self.send_amt:
  1077. msg(wmsg['not_enough_coin'].format(self.send_amt-t_inputs))
  1078. continue
  1079. non_mmaddrs = [i for i in sel_unspent if i.twmmid.type == 'non-mmgen']
  1080. if non_mmaddrs and self.caller != 'txdo':
  1081. msg(wmsg['non_mmgen_inputs'].format(', '.join(set(sorted([a.addr.hl() for a in non_mmaddrs])))))
  1082. if not keypress_confirm('Accept?'):
  1083. continue
  1084. self.copy_inputs_from_tw(sel_unspent) # makes self.inputs
  1085. self.fee = self.get_fee_from_user()
  1086. change_amt = self.sum_inputs() - self.send_amt - self.fee
  1087. if change_amt >= 0:
  1088. p = self.chg_msg_fs.format(change_amt.hl(),g.coin)
  1089. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1090. if opt.yes: msg(p)
  1091. return change_amt
  1092. else:
  1093. msg(wmsg['not_enough_coin'].format(abs(change_amt)))
  1094. def check_fee(self):
  1095. assert self.sum_inputs() - self.sum_outputs() <= g.proto.max_tx_fee
  1096. def create(self,cmd_args,locktime,do_info=False):
  1097. assert type(locktime) == int
  1098. if opt.comment_file: self.add_comment(opt.comment_file)
  1099. if not do_info: self.get_outputs_from_cmdline(cmd_args)
  1100. do_license_msg()
  1101. from mmgen.tw import TwUnspentOutputs
  1102. tw = TwUnspentOutputs(minconf=opt.minconf)
  1103. tw.view_and_sort(self)
  1104. tw.display_total()
  1105. if do_info: sys.exit(0)
  1106. self.send_amt = self.sum_outputs()
  1107. msg('Total amount to spend: {}'.format(
  1108. ('Unknown','{} {}'.format(self.send_amt.hl(),g.coin))[bool(self.send_amt)]
  1109. ))
  1110. change_amt = self.get_inputs_from_user(tw)
  1111. # only after we have inputs
  1112. if opt.rbf: self.inputs[0].sequence = g.max_int - 2 # handles the locktime case too
  1113. elif locktime: self.inputs[0].sequence = g.max_int - 1
  1114. chg_idx = self.get_chg_output_idx()
  1115. if change_amt == 0:
  1116. msg(self.no_chg_msg)
  1117. self.del_output(chg_idx)
  1118. else:
  1119. self.update_output_amt(chg_idx,g.proto.coin_amt(change_amt))
  1120. if not self.send_amt:
  1121. self.send_amt = change_amt
  1122. if not opt.yes:
  1123. self.add_comment() # edits an existing comment
  1124. self.create_raw() # creates self.hex, self.txid
  1125. if locktime:
  1126. msg('Setting nlocktime to {}!'.format(strfmt_locktime(locktime)))
  1127. self.set_hex_locktime(locktime)
  1128. self.update_txid()
  1129. self.locktime = locktime
  1130. self.add_timestamp()
  1131. self.add_blockcount()
  1132. self.chain = g.chain
  1133. self.check_fee()
  1134. qmsg('Transaction successfully created')
  1135. if not opt.yes:
  1136. self.view_with_prompt('View decoded transaction?')
  1137. class MMGenBumpTX(MMGenTX):
  1138. min_fee = None
  1139. bump_output_idx = None
  1140. def __init__(self,filename,send=False):
  1141. super(type(self),self).__init__(filename)
  1142. if not self.is_rbf():
  1143. die(1,"Transaction '{}' is not replaceable (RBF)".format(self.txid))
  1144. # If sending, require tx to have been signed
  1145. if send:
  1146. if not self.marked_signed():
  1147. die(1,"File '{}' is not a signed {} transaction file".format(filename,g.proj_name))
  1148. if not self.coin_txid:
  1149. die(1,"Transaction '{}' was not broadcast to the network".format(self.txid,g.proj_name))
  1150. self.coin_txid = ''
  1151. self.mark_raw()
  1152. def choose_output(self):
  1153. chg_idx = self.get_chg_output_idx()
  1154. init_reply = opt.output_to_reduce
  1155. while True:
  1156. if init_reply == None:
  1157. m = 'Choose an output to deduct the fee from (Hit ENTER for the change output): '
  1158. reply = my_raw_input(m) or 'c'
  1159. else:
  1160. reply,init_reply = init_reply,None
  1161. if chg_idx == None and not is_int(reply):
  1162. msg("Output must be an integer")
  1163. elif chg_idx != None and not is_int(reply) and reply != 'c':
  1164. msg("Output must be an integer, or 'c' for the change output")
  1165. else:
  1166. idx = chg_idx if reply == 'c' else (int(reply) - 1)
  1167. if idx < 0 or idx >= len(self.outputs):
  1168. msg('Output must be in the range 1-{}'.format(len(self.outputs)))
  1169. else:
  1170. o_amt = self.outputs[idx].amt
  1171. cs = ('',' (change output)')[chg_idx == idx]
  1172. p = 'Fee will be deducted from output {}{} ({} {})'.format(idx+1,cs,o_amt,g.coin)
  1173. if o_amt < self.min_fee:
  1174. msg('Minimum fee ({} {c}) is greater than output amount ({} {c})'.format(
  1175. self.min_fee,o_amt,c=g.coin))
  1176. elif opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1177. if opt.yes: msg(p)
  1178. self.bump_output_idx = idx
  1179. return idx
  1180. def set_min_fee(self):
  1181. self.min_fee = self.sum_inputs() - self.sum_outputs() + self.get_relay_fee()
  1182. def convert_and_check_fee(self,tx_fee,desc):
  1183. ret = super(type(self),self).convert_and_check_fee(tx_fee,desc)
  1184. if ret < self.min_fee:
  1185. msg('{} {c}: {} fee too small. Minimum fee: {} {c} ({} {})'.format(
  1186. ret,desc,self.min_fee,self.fee_abs2rel(self.min_fee),self.rel_fee_desc,c=g.coin))
  1187. return False
  1188. output_amt = self.outputs[self.bump_output_idx].amt
  1189. if ret >= output_amt:
  1190. msg('{} {c}: {} fee too large. Maximum fee: <{} {c}'.format(ret,desc,output_amt,c=g.coin))
  1191. return False
  1192. return ret
  1193. class MMGenSplitTX(MMGenTX):
  1194. def get_outputs_from_cmdline(self,mmid): # TODO: check that addr is empty
  1195. from mmgen.addr import AddrData
  1196. ad_w = AddrData(source='tw')
  1197. if is_mmgen_id(mmid):
  1198. coin_addr = mmaddr2coinaddr(mmid,ad_w,None) if is_mmgen_id(mmid) else CoinAddr(mmid)
  1199. self.add_output(coin_addr,g.proto.coin_amt('0'),is_chg=True)
  1200. else:
  1201. die(2,'{}: invalid command-line argument'.format(mmid))
  1202. self.add_mmaddrs_to_outputs(ad_w,None)
  1203. if not segwit_is_active() and self.has_segwit_outputs():
  1204. fs = '{} Segwit address requested on the command line, but Segwit is not active on this chain'
  1205. rdie(2,fs.format(g.proj_name))
  1206. def get_split_fee_from_user(self):
  1207. if opt.rpc_host2:
  1208. g.rpc_host = opt.rpc_host2
  1209. if opt.tx_fees:
  1210. opt.tx_fee = opt.tx_fees.split(',')[1]
  1211. try:
  1212. rpc_init(reinit=True)
  1213. except:
  1214. ymsg('Connect to {} daemon failed. Network fee estimation unavailable'.format(g.coin))
  1215. return self.get_usr_fee_interactive(opt.tx_fee,'User-selected')
  1216. return super(type(self),self).get_fee_from_user()
  1217. def create_split(self,mmid):
  1218. self.outputs = self.MMGenTxOutputList()
  1219. self.get_outputs_from_cmdline(mmid)
  1220. while True:
  1221. change_amt = self.sum_inputs() - self.get_split_fee_from_user()
  1222. if change_amt >= 0:
  1223. p = 'Transaction produces {} {} in change'.format(change_amt.hl(),g.coin)
  1224. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1225. if opt.yes: msg(p)
  1226. break
  1227. else:
  1228. msg(wmsg['not_enough_coin'].format(abs(change_amt)))
  1229. self.update_output_amt(0,change_amt)
  1230. self.send_amt = change_amt
  1231. if not opt.yes:
  1232. self.add_comment() # edits an existing comment
  1233. self.create_raw() # creates self.hex, self.txid
  1234. self.add_timestamp()
  1235. self.add_blockcount() # TODO
  1236. self.chain = g.chain
  1237. assert self.sum_inputs() - self.sum_outputs() <= g.proto.max_tx_fee
  1238. qmsg('Transaction successfully created')
  1239. if not opt.yes:
  1240. self.view_with_prompt('View decoded transaction?')