tx.py 55 KB

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