tx.py 55 KB

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