tx.py 55 KB

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