tx.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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,time
  22. from .globalvars import g
  23. from .opts import opt
  24. from .color import *
  25. from .util import (
  26. msg,
  27. ymsg,
  28. dmsg,
  29. vmsg,
  30. qmsg,
  31. msg_r,
  32. die,
  33. is_int,
  34. fmt,
  35. suf,
  36. altcoin_subclass,
  37. confirm_or_raise,
  38. remove_dups,
  39. get_extension,
  40. keypress_confirm,
  41. do_license_msg,
  42. line_input,
  43. make_chksum_6,
  44. make_timestamp,
  45. secs_to_dhms,
  46. )
  47. from .objmethods import MMGenObject
  48. from .obj import (
  49. ImmutableAttr,
  50. ListItemAttr,
  51. MMGenList,
  52. MMGenListItem,
  53. MMGenTxLabel,
  54. HexStr,
  55. MMGenTxID,
  56. MMGenDict,
  57. TwComment,
  58. CoinTxID,
  59. get_obj,
  60. )
  61. from .addr import MMGenID,CoinAddr,is_mmgen_id,is_coin_addr
  62. wmsg = lambda k: {
  63. 'addr_in_addrfile_only': """
  64. Warning: output address {} is not in the tracking wallet, which means
  65. its balance will not be tracked. You're strongly advised to import the address
  66. into your tracking wallet before broadcasting this transaction.
  67. """.strip(),
  68. 'addr_not_found': """
  69. No data for {pnm} address {{}} could be found in either the tracking
  70. wallet or the supplied address file. Please import this address into your
  71. tracking wallet, or supply an address file for it on the command line.
  72. """.strip().format(pnm=g.proj_name),
  73. 'addr_not_found_no_addrfile': """
  74. No data for {pnm} address {{}} could be found in the tracking wallet.
  75. Please import this address into your tracking wallet or supply an address file
  76. for it on the command line.
  77. """.strip().format(pnm=g.proj_name),
  78. }[k]
  79. def strfmt_locktime(num,terse=False):
  80. # Locktime itself is an unsigned 4-byte integer which can be parsed two ways:
  81. #
  82. # If less than 500 million, locktime is parsed as a block height. The transaction can be
  83. # added to any block which has this height or higher.
  84. # MMGen note: s/this height or higher/a higher block height/
  85. #
  86. # If greater than or equal to 500 million, locktime is parsed using the Unix epoch time
  87. # format (the number of seconds elapsed since 1970-01-01T00:00 UTC). The transaction can be
  88. # added to any block whose block time is greater than the locktime.
  89. if num == None:
  90. return '(None)'
  91. elif num >= 5 * 10**6:
  92. return ' '.join(time.strftime('%c',time.gmtime(num)).split()[1:])
  93. elif num > 0:
  94. return '{}{}'.format(('block height ','')[terse],num)
  95. else:
  96. die(2,f'{num!r}: invalid nLockTime value!')
  97. def mmaddr2coinaddr(mmaddr,ad_w,ad_f,proto):
  98. # assume mmaddr has already been checked
  99. coin_addr = ad_w.mmaddr2coinaddr(mmaddr)
  100. if not coin_addr:
  101. if ad_f:
  102. coin_addr = ad_f.mmaddr2coinaddr(mmaddr)
  103. if coin_addr:
  104. msg(wmsg('addr_in_addrfile_only').format(mmaddr))
  105. if not (opt.yes or keypress_confirm('Continue anyway?')):
  106. sys.exit(1)
  107. else:
  108. die(2,wmsg('addr_not_found').format(mmaddr))
  109. else:
  110. die(2,wmsg('addr_not_found_no_addrfile').format(mmaddr))
  111. return CoinAddr(proto,coin_addr)
  112. def addr2pubhash(proto,addr):
  113. ap = proto.parse_addr(addr)
  114. assert ap,f'coin address {addr!r} could not be parsed'
  115. return ap.bytes.hex()
  116. def addr2scriptPubKey(proto,addr):
  117. return {
  118. 'p2pkh': '76a914' + addr2pubhash(proto,addr) + '88ac',
  119. 'p2sh': 'a914' + addr2pubhash(proto,addr) + '87',
  120. 'bech32': proto.witness_vernum_hex + '14' + addr2pubhash(proto,addr)
  121. }[addr.addr_fmt]
  122. def scriptPubKey2addr(proto,s):
  123. if len(s) == 50 and s[:6] == '76a914' and s[-4:] == '88ac':
  124. return proto.pubhash2addr(bytes.fromhex(s[6:-4]),p2sh=False),'p2pkh'
  125. elif len(s) == 46 and s[:4] == 'a914' and s[-2:] == '87':
  126. return proto.pubhash2addr(bytes.fromhex(s[4:-2]),p2sh=True),'p2sh'
  127. elif len(s) == 44 and s[:4] == proto.witness_vernum_hex + '14':
  128. return proto.pubhash2bech32addr(bytes.fromhex(s[4:])),'bech32'
  129. else:
  130. raise NotImplementedError(f'Unknown scriptPubKey ({s})')
  131. class DeserializedTX(dict,MMGenObject):
  132. """
  133. Parse a serialized Bitcoin transaction
  134. For checking purposes, additionally reconstructs the raw (unsigned) tx hex from signed tx hex
  135. """
  136. def __init__(self,proto,txhex):
  137. def bytes2int(bytes_le):
  138. if bytes_le[-1] & 0x80: # sign bit is set
  139. die(3,"{}: Negative values not permitted in transaction!".format(bytes_le[::-1].hex()))
  140. return int(bytes_le[::-1].hex(),16)
  141. def bytes2coin_amt(bytes_le):
  142. return proto.coin_amt(bytes2int(bytes_le) * proto.coin_amt.satoshi)
  143. def bshift(n,skip=False,sub_null=False):
  144. ret = tx[self.idx:self.idx+n]
  145. self.idx += n
  146. if sub_null:
  147. self.raw_tx += b'\x00'
  148. elif not skip:
  149. self.raw_tx += ret
  150. return ret
  151. # https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
  152. # For example, the number 515 is encoded as 0xfd0302.
  153. def readVInt(skip=False):
  154. s = tx[self.idx]
  155. self.idx += 1
  156. if not skip:
  157. self.raw_tx.append(s)
  158. vbytes_len = 1 if s < 0xfd else 2 if s == 0xfd else 4 if s == 0xfe else 8
  159. if vbytes_len == 1:
  160. return s
  161. else:
  162. vbytes = tx[self.idx:self.idx+vbytes_len]
  163. self.idx += vbytes_len
  164. if not skip:
  165. self.raw_tx += vbytes
  166. return int(vbytes[::-1].hex(),16)
  167. def make_txid(tx_bytes):
  168. from hashlib import sha256
  169. return sha256(sha256(tx_bytes).digest()).digest()[::-1].hex()
  170. self.idx = 0
  171. self.raw_tx = bytearray()
  172. tx = bytes.fromhex(txhex)
  173. d = { 'version': bytes2int(bshift(4)) }
  174. has_witness = tx[self.idx] == 0
  175. if has_witness:
  176. u = bshift(2,skip=True).hex()
  177. if u != '0001':
  178. raise IllegalWitnessFlagValue(f'{u!r}: Illegal value for flag in transaction!')
  179. d['num_txins'] = readVInt()
  180. d['txins'] = MMGenList([{
  181. 'txid': bshift(32)[::-1].hex(),
  182. 'vout': bytes2int(bshift(4)),
  183. 'scriptSig': bshift(readVInt(skip=True),sub_null=True).hex(),
  184. 'nSeq': bshift(4)[::-1].hex()
  185. } for i in range(d['num_txins'])])
  186. d['num_txouts'] = readVInt()
  187. d['txouts'] = MMGenList([{
  188. 'amount': bytes2coin_amt(bshift(8)),
  189. 'scriptPubKey': bshift(readVInt()).hex()
  190. } for i in range(d['num_txouts'])])
  191. for o in d['txouts']:
  192. o['address'] = scriptPubKey2addr(proto,o['scriptPubKey'])[0]
  193. if has_witness:
  194. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  195. # A non-witness program (defined hereinafter) txin MUST be associated with an empty
  196. # witness field, represented by a 0x00.
  197. d['txid'] = make_txid(tx[:4] + tx[6:self.idx] + tx[-4:])
  198. d['witness_size'] = len(tx) - self.idx + 2 - 4 # add len(marker+flag), subtract len(locktime)
  199. for txin in d['txins']:
  200. if tx[self.idx] == 0:
  201. bshift(1,skip=True)
  202. continue
  203. txin['witness'] = [
  204. bshift(readVInt(skip=True),skip=True).hex() for item in range(readVInt(skip=True)) ]
  205. else:
  206. d['txid'] = make_txid(tx)
  207. d['witness_size'] = 0
  208. if len(tx) - self.idx != 4:
  209. raise TxHexParseError('TX hex has invalid length: {} extra bytes'.format(len(tx)-self.idx-4))
  210. d['lock_time'] = bytes2int(bshift(4))
  211. d['unsigned_hex'] = self.raw_tx.hex()
  212. dict.__init__(self,d)
  213. class MMGenTxIO(MMGenListItem):
  214. vout = ListItemAttr(int,typeconv=False)
  215. amt = ImmutableAttr(None)
  216. label = ListItemAttr(TwComment,reassign_ok=True)
  217. mmid = ListItemAttr(MMGenID,include_proto=True)
  218. addr = ImmutableAttr(CoinAddr,include_proto=True)
  219. confs = ListItemAttr(int) # confs of type long exist in the wild, so convert
  220. txid = ListItemAttr(CoinTxID)
  221. have_wif = ListItemAttr(bool,typeconv=False,delete_ok=True)
  222. invalid_attrs = {'proto','tw_copy_attrs'}
  223. def __init__(self,proto,**kwargs):
  224. self.__dict__['proto'] = proto
  225. MMGenListItem.__init__(self,**kwargs)
  226. @property
  227. def mmtype(self):
  228. """
  229. Attempt to determine input or output’s MMGenAddrType. For non-MMGen
  230. addresses, infer the type from the address format, returning None for
  231. P2PKH, which could be either 'L' or 'C'.
  232. """
  233. return (
  234. str(self.mmid.mmtype) if self.mmid else
  235. 'B' if self.addr.addr_fmt == 'bech32' else
  236. 'S' if self.addr.addr_fmt == 'p2sh' else
  237. None )
  238. class conv_funcs:
  239. def amt(self,value):
  240. return self.proto.coin_amt(value)
  241. class MMGenTxInput(MMGenTxIO):
  242. scriptPubKey = ListItemAttr(HexStr)
  243. sequence = ListItemAttr(int,typeconv=False)
  244. tw_copy_attrs = { 'scriptPubKey','vout','amt','label','mmid','addr','confs','txid' }
  245. class MMGenTxOutput(MMGenTxIO):
  246. is_chg = ListItemAttr(bool,typeconv=False)
  247. class MMGenTxIOList(list,MMGenObject):
  248. def __init__(self,parent,data=None):
  249. self.parent = parent
  250. if data:
  251. assert isinstance(data,list), 'MMGenTxIOList_check1'
  252. data = data
  253. else:
  254. data = list()
  255. list.__init__(self,data)
  256. class MMGenTxInputList(MMGenTxIOList):
  257. desc = 'transaction inputs'
  258. member_type = 'MMGenTxInput'
  259. # Lexicographical Indexing of Transaction Inputs and Outputs
  260. # https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki
  261. def sort_bip69(self):
  262. def sort_func(a):
  263. return (
  264. bytes.fromhex(a.txid)
  265. + int.to_bytes(a.vout,4,'big') )
  266. self.sort(key=sort_func)
  267. class MMGenTxOutputList(MMGenTxIOList):
  268. desc = 'transaction outputs'
  269. member_type = 'MMGenTxOutput'
  270. def sort_bip69(self):
  271. def sort_func(a):
  272. return (
  273. int.to_bytes(a.amt.to_unit('satoshi'),8,'big')
  274. + bytes.fromhex(addr2scriptPubKey(self.parent.proto,a.addr)) )
  275. self.sort(key=sort_func)
  276. class MMGenTX:
  277. filename_api = True
  278. class Base(MMGenObject):
  279. desc = 'transaction'
  280. hex = '' # raw serialized hex transaction
  281. label = MMGenTxLabel('')
  282. txid = ''
  283. coin_txid = ''
  284. timestamp = ''
  285. blockcount = 0
  286. coin = None
  287. dcoin = None
  288. locktime = None
  289. chain = None
  290. rel_fee_desc = 'satoshis per byte'
  291. rel_fee_disp = 'sat/byte'
  292. non_mmgen_inputs_msg = f"""
  293. This transaction includes inputs with non-{g.proj_name} addresses. When
  294. signing the transaction, private keys for the addresses listed below must
  295. be supplied using the --keys-from-file option. The key file must contain
  296. one key per line. Please note that this transaction cannot be autosigned,
  297. as autosigning does not support the use of key files.
  298. Non-{g.proj_name} addresses found in inputs:
  299. {{}}
  300. """
  301. def __new__(cls,*args,**kwargs):
  302. """
  303. determine correct protocol and pass the proto to altcoin_subclass(), which returns the
  304. transaction object
  305. """
  306. assert args == (), f'MMGenTX.Base_chk1: only keyword args allowed in {cls.__name__} initializer'
  307. if 'proto' in kwargs:
  308. return MMGenObject.__new__(altcoin_subclass(cls,kwargs['proto'],'tx'))
  309. elif 'data' in kwargs:
  310. return MMGenObject.__new__(altcoin_subclass(cls,kwargs['data']['proto'],'tx'))
  311. elif 'filename' in kwargs:
  312. from .txfile import MMGenTxFile
  313. tmp_tx = MMGenObject.__new__(cls)
  314. MMGenTxFile(tmp_tx).parse(
  315. infile = kwargs['filename'],
  316. quiet_open = kwargs.get('quiet_open'),
  317. metadata_only = True )
  318. me = MMGenObject.__new__(altcoin_subclass(cls,tmp_tx.proto,'tx'))
  319. me.proto = tmp_tx.proto
  320. return me
  321. elif cls.__name__ == 'Base' and args == () and kwargs == {}: # allow instantiation of empty Base()
  322. return cls
  323. else:
  324. raise ValueError(
  325. f"MMGenTX.Base: {cls.__name__} must be instantiated with 'proto','data' or 'filename' keyword")
  326. def __init__(self):
  327. self.inputs = MMGenTxInputList(self)
  328. self.outputs = MMGenTxOutputList(self)
  329. self.name = type(self).__name__
  330. @property
  331. def coin(self):
  332. return self.proto.coin
  333. @property
  334. def dcoin(self):
  335. return self.proto.dcoin
  336. def check_correct_chain(self):
  337. if hasattr(self,'rpc'):
  338. if self.chain != self.rpc.chain:
  339. raise TransactionChainMismatch(
  340. f'Transaction is for {self.chain}, but coin daemon chain is {self.rpc.chain}!')
  341. def sum_inputs(self):
  342. return sum(e.amt for e in self.inputs)
  343. def sum_outputs(self,exclude=None):
  344. if exclude == None:
  345. olist = self.outputs
  346. else:
  347. olist = self.outputs[:exclude] + self.outputs[exclude+1:]
  348. if not olist:
  349. return self.proto.coin_amt('0')
  350. return self.proto.coin_amt(sum(e.amt for e in olist))
  351. def get_chg_output_idx(self):
  352. ch_ops = [x.is_chg for x in self.outputs]
  353. try:
  354. return ch_ops.index(True)
  355. except ValueError:
  356. return None
  357. def has_segwit_inputs(self):
  358. return any(i.mmtype in ('S','B') for i in self.inputs)
  359. def has_segwit_outputs(self):
  360. return any(o.mmtype in ('S','B') for o in self.outputs)
  361. # https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
  362. # 180: uncompressed, 148: compressed
  363. def estimate_size_old(self):
  364. if not self.inputs or not self.outputs:
  365. return None
  366. return len(self.inputs)*180 + len(self.outputs)*34 + 10
  367. # https://bitcoincore.org/en/segwit_wallet_dev/
  368. # vsize: 3 times of the size with original serialization, plus the size with new
  369. # serialization, divide the result by 4 and round up to the next integer.
  370. # TODO: results differ slightly from actual transaction size
  371. def estimate_size(self):
  372. if not self.inputs or not self.outputs:
  373. return None
  374. sig_size = 72 # sig in DER format
  375. pubkey_size_uncompressed = 65
  376. pubkey_size_compressed = 33
  377. def get_inputs_size():
  378. # txid vout [scriptSig size (vInt)] scriptSig (<sig> <pubkey>) nSeq
  379. isize_common = 32 + 4 + 1 + 4 # txid vout [scriptSig size] nSeq = 41
  380. input_size = {
  381. 'L': isize_common + sig_size + pubkey_size_uncompressed, # = 180
  382. 'C': isize_common + sig_size + pubkey_size_compressed, # = 148
  383. 'S': isize_common + 23, # = 64
  384. 'B': isize_common + 0 # = 41
  385. }
  386. ret = sum(input_size[i.mmtype] for i in self.inputs if i.mmtype)
  387. # We have no way of knowing whether a non-MMGen P2PKH addr is compressed or uncompressed
  388. # until we see the key, so assume compressed for fee-estimation purposes. If fee estimate
  389. # is off by more than 5%, sign() aborts and user is instructed to use --vsize-adj option.
  390. return ret + sum(input_size['C'] for i in self.inputs if not i.mmtype)
  391. def get_outputs_size():
  392. # output bytes = amt: 8, byte_count: 1+, pk_script
  393. # pk_script bytes: p2pkh: 25, p2sh: 23, bech32: 22
  394. return sum({'p2pkh':34,'p2sh':32,'bech32':31}[o.addr.addr_fmt] for o in self.outputs)
  395. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  396. # The witness is a serialization of all witness data of the transaction. Each txin is
  397. # associated with a witness field. A witness field starts with a var_int to indicate the
  398. # number of stack items for the txin. It is followed by stack items, with each item starts
  399. # with a var_int to indicate the length. Witness data is NOT script.
  400. # A non-witness program txin MUST be associated with an empty witness field, represented
  401. # by a 0x00. If all txins are not witness program, a transaction's wtxid is equal to its txid.
  402. def get_witness_size():
  403. if not self.has_segwit_inputs():
  404. return 0
  405. wf_size = 1 + 1 + sig_size + 1 + pubkey_size_compressed # vInt vInt sig vInt pubkey = 108
  406. return sum((1,wf_size)[i.mmtype in ('S','B')] for i in self.inputs)
  407. isize = get_inputs_size()
  408. osize = get_outputs_size()
  409. wsize = get_witness_size()
  410. # TODO: compute real varInt sizes instead of assuming 1 byte
  411. # old serialization: [nVersion] [vInt][txins][vInt][txouts] [nLockTime]
  412. old_size = 4 + 1 + isize + 1 + osize + 4
  413. # marker = 0x00, flag = 0x01
  414. # new serialization: [nVersion][marker][flag][vInt][txins][vInt][txouts][witness][nLockTime]
  415. new_size = 4 + 1 + 1 + 1 + isize + 1 + osize + wsize + 4 \
  416. if wsize else old_size
  417. ret = (old_size * 3 + new_size) // 4
  418. dmsg('\nData from estimate_size():')
  419. dmsg(f' inputs size: {isize}, outputs size: {osize}, witness size: {wsize}')
  420. dmsg(f' size: {new_size}, vsize: {ret}, old_size: {old_size}')
  421. return int(ret * (opt.vsize_adj or 1))
  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(self.proto.coin_amt,to_unit or 'satoshi')
  425. return int(abs_fee / unit / self.estimate_size())
  426. def get_hex_locktime(self):
  427. return int(bytes.fromhex(self.hex[-8:])[::-1].hex(),16)
  428. def set_hex_locktime(self,val):
  429. assert isinstance(val,int),'locktime value not an integer'
  430. self.hex = self.hex[:-8] + bytes.fromhex('{:08x}'.format(val))[::-1].hex()
  431. def add_timestamp(self):
  432. self.timestamp = make_timestamp()
  433. def add_blockcount(self):
  434. self.blockcount = self.rpc.blockcount
  435. # returns true if comment added or changed
  436. def add_comment(self,infile=None):
  437. if infile:
  438. from .fileutil import get_data_from_file
  439. self.label = MMGenTxLabel(get_data_from_file(infile,'transaction comment'))
  440. else: # get comment from user, or edit existing comment
  441. m = ('Add a comment to transaction?','Edit transaction comment?')[bool(self.label)]
  442. if keypress_confirm(m,default_yes=False):
  443. while True:
  444. s = MMGenTxLabel(line_input('Comment: ',insert_txt=self.label))
  445. if not s:
  446. ymsg('Warning: comment is empty')
  447. lbl_save = self.label
  448. self.label = s
  449. return (True,False)[lbl_save == self.label]
  450. return False
  451. def get_non_mmaddrs(self,desc):
  452. return remove_dups(
  453. (i.addr for i in getattr(self,desc) if not i.mmid),
  454. edesc = 'non-MMGen address',
  455. quiet = True )
  456. def check_non_mmgen_inputs(self,caller,non_mmaddrs=None):
  457. non_mmaddrs = non_mmaddrs or self.get_non_mmaddrs('inputs')
  458. if non_mmaddrs:
  459. indent = ' '
  460. fs = fmt(self.non_mmgen_inputs_msg,strip_char='\t',indent=indent).strip()
  461. m = fs.format('\n '.join(non_mmaddrs))
  462. if caller in ('txdo','txsign'):
  463. if not opt.keys_from_file:
  464. raise UserOptError(f'\n{indent}ERROR: {m}\n')
  465. else:
  466. msg(f'\n{indent}WARNING: {m}\n')
  467. if not (opt.yes or keypress_confirm('Continue?',default_yes=True)):
  468. die(1,'Exiting at user request')
  469. class New(Base):
  470. usr_fee_prompt = 'Enter transaction fee: '
  471. fee_is_approximate = False
  472. fee_fail_fs = 'Network fee estimation for {c} confirmations failed ({t})'
  473. no_chg_msg = 'Warning: Change address will be deleted as transaction produces no change'
  474. msg_wallet_low_coin = 'Wallet has insufficient funds for this transaction ({} {} needed)'
  475. msg_low_coin = 'Selected outputs insufficient to fund this transaction ({} {} needed)'
  476. msg_no_change_output = fmt("""
  477. ERROR: No change address specified. If you wish to create a transaction with
  478. only one output, specify a single output address with no {} amount
  479. """).strip()
  480. def __init__(self,proto,tw=None): # tw required for resolving ERC20 token data
  481. MMGenTX.Base.__init__(self)
  482. self.proto = proto
  483. self.tw = tw
  484. def del_output(self,idx):
  485. self.outputs.pop(idx)
  486. def update_output_amt(self,idx,amt):
  487. o = self.outputs[idx]._asdict()
  488. o['amt'] = amt
  489. self.outputs[idx] = MMGenTxOutput(self.proto,**o)
  490. def add_mmaddrs_to_outputs(self,ad_w,ad_f):
  491. a = [e.addr for e in self.outputs]
  492. d = ad_w.make_reverse_dict(a)
  493. if ad_f:
  494. d.update(ad_f.make_reverse_dict(a))
  495. for e in self.outputs:
  496. if e.addr and e.addr in d:
  497. e.mmid,f = d[e.addr]
  498. if f:
  499. e.label = f
  500. def check_dup_addrs(self,io_str):
  501. assert io_str in ('inputs','outputs')
  502. addrs = [e.addr for e in getattr(self,io_str)]
  503. if len(addrs) != len(set(addrs)):
  504. die(2,f'{addrs}: duplicate address in transaction {io_str}')
  505. # coin-specific fee routines
  506. @property
  507. def relay_fee(self):
  508. kb_fee = self.proto.coin_amt(self.rpc.cached['networkinfo']['relayfee'])
  509. ret = kb_fee * self.estimate_size() / 1024
  510. vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=self.coin))
  511. return ret
  512. async def get_rel_fee_from_network(self):
  513. try:
  514. ret = await self.rpc.call('estimatesmartfee',opt.tx_confs,opt.fee_estimate_mode.upper())
  515. fee_per_kb = ret['feerate'] if 'feerate' in ret else -2
  516. fe_type = 'estimatesmartfee'
  517. except:
  518. args = () if self.coin=='BCH' and self.rpc.daemon_version >= 190100 else (opt.tx_confs,)
  519. fee_per_kb = await self.rpc.call('estimatefee',*args)
  520. fe_type = 'estimatefee'
  521. return fee_per_kb,fe_type
  522. # given tx size, rel fee and units, return absolute fee
  523. def fee_rel2abs(self,tx_size,units,amt,unit):
  524. if tx_size:
  525. return self.proto.coin_amt(amt * tx_size * getattr(self.proto.coin_amt,units[unit]))
  526. else:
  527. return None
  528. # given network fee estimate in BTC/kB, return absolute fee using estimated tx size
  529. def fee_est2abs(self,fee_per_kb,fe_type=None):
  530. from decimal import Decimal
  531. tx_size = self.estimate_size()
  532. ret = self.proto.coin_amt(
  533. fee_per_kb * Decimal(opt.tx_fee_adj) * tx_size / 1024,
  534. from_decimal = True )
  535. if opt.verbose:
  536. msg(fmt(f"""
  537. {fe_type.upper()} fee for {opt.tx_confs} confirmations: {fee_per_kb} {self.coin}/kB
  538. TX size (estimated): {tx_size} bytes
  539. Fee adjustment factor: {opt.tx_fee_adj:.2f}
  540. Absolute fee (fee_per_kb * adj_factor * tx_size / 1024): {ret} {self.coin}
  541. """).strip())
  542. return ret
  543. def convert_and_check_fee(self,tx_fee,desc='Missing description'):
  544. abs_fee = self.feespec2abs(tx_fee,self.estimate_size())
  545. if abs_fee == None:
  546. raise ValueError(f'{tx_fee}: cannot convert {self.rel_fee_desc} to {self.coin}'
  547. + ' because transaction size is unknown')
  548. if abs_fee == False:
  549. err = f'{tx_fee!r}: invalid TX fee (not a {self.coin} amount or {self.rel_fee_desc} specification)'
  550. elif abs_fee > self.proto.max_tx_fee:
  551. err = f'{abs_fee} {self.coin}: {desc} fee too large (maximum fee: {self.proto.max_tx_fee} {self.coin})'
  552. elif abs_fee < self.relay_fee:
  553. err = f'{abs_fee} {self.coin}: {desc} fee too small (less than relay fee of {self.relay_fee} {self.coin})'
  554. else:
  555. return abs_fee
  556. msg(err)
  557. return False
  558. # non-coin-specific fee routines
  559. # given tx size and absolute fee or fee spec, return absolute fee
  560. # relative fee is N+<first letter of unit name>
  561. def feespec2abs(self,tx_fee,tx_size):
  562. fee = get_obj(self.proto.coin_amt,num=tx_fee,silent=True)
  563. if fee:
  564. return fee
  565. else:
  566. import re
  567. units = {u[0]:u for u in self.proto.coin_amt.units}
  568. pat = re.compile(r'([1-9][0-9]*)({})'.format('|'.join(units)))
  569. if pat.match(tx_fee):
  570. amt,unit = pat.match(tx_fee).groups()
  571. return self.fee_rel2abs(tx_size,units,int(amt),unit)
  572. return False
  573. def get_usr_fee_interactive(self,tx_fee=None,desc='Starting'):
  574. abs_fee = None
  575. while True:
  576. if tx_fee:
  577. abs_fee = self.convert_and_check_fee(tx_fee,desc)
  578. if abs_fee:
  579. prompt = '{} TX fee{}: {}{} {} ({} {})\n'.format(
  580. desc,
  581. (f' (after {opt.tx_fee_adj:.2f}X adjustment)'
  582. if opt.tx_fee_adj != 1 and desc.startswith('Network-estimated')
  583. else ''),
  584. ('','≈')[self.fee_is_approximate],
  585. abs_fee.hl(),
  586. self.coin,
  587. pink(str(self.fee_abs2rel(abs_fee))),
  588. self.rel_fee_disp)
  589. if opt.yes or keypress_confirm(prompt+'OK?',default_yes=True):
  590. if opt.yes:
  591. msg(prompt)
  592. return abs_fee
  593. tx_fee = line_input(self.usr_fee_prompt)
  594. desc = 'User-selected'
  595. async def get_fee_from_user(self,have_estimate_fail=[]):
  596. if opt.tx_fee:
  597. desc = 'User-selected'
  598. start_fee = opt.tx_fee
  599. else:
  600. desc = 'Network-estimated ({}, {} conf{})'.format(
  601. opt.fee_estimate_mode.upper(),
  602. pink(str(opt.tx_confs)),
  603. suf(opt.tx_confs) )
  604. fee_per_kb,fe_type = await self.get_rel_fee_from_network()
  605. if fee_per_kb < 0:
  606. if not have_estimate_fail:
  607. msg(self.fee_fail_fs.format(c=opt.tx_confs,t=fe_type))
  608. have_estimate_fail.append(True)
  609. start_fee = None
  610. else:
  611. start_fee = self.fee_est2abs(fee_per_kb,fe_type)
  612. return self.get_usr_fee_interactive(start_fee,desc=desc)
  613. def add_output(self,coinaddr,amt,is_chg=None):
  614. self.outputs.append(MMGenTxOutput(self.proto,addr=coinaddr,amt=amt,is_chg=is_chg))
  615. def process_cmd_arg(self,arg,ad_f,ad_w):
  616. def add_output_chk(addr,amt,err_desc):
  617. if not amt and self.get_chg_output_idx() != None:
  618. die(2,'ERROR: More than one change address listed on command line')
  619. if is_mmgen_id(self.proto,addr) or is_coin_addr(self.proto,addr):
  620. coin_addr = ( mmaddr2coinaddr(addr,ad_w,ad_f,self.proto) if is_mmgen_id(self.proto,addr)
  621. else CoinAddr(self.proto,addr) )
  622. self.add_output(coin_addr,self.proto.coin_amt(amt or '0'),is_chg=not amt)
  623. else:
  624. die(2,f'{addr}: invalid {err_desc} {{!r}}'.format(f'{addr},{amt}' if amt else addr))
  625. if ',' in arg:
  626. addr,amt = arg.split(',',1)
  627. add_output_chk(addr,amt,'coin argument in command-line argument')
  628. else:
  629. add_output_chk(arg,None,'command-line argument')
  630. async def get_cmdline_input_addrs(self):
  631. # Bitcoin full node, call doesn't go to the network, so just call listunspent with addrs=[]
  632. return []
  633. def process_cmd_args(self,cmd_args,ad_f,ad_w):
  634. for a in cmd_args:
  635. self.process_cmd_arg(a,ad_f,ad_w)
  636. if self.get_chg_output_idx() == None:
  637. die(2,( 'ERROR: No change output specified',
  638. self.msg_no_change_output.format(self.dcoin))[len(self.outputs) == 1])
  639. if self.has_segwit_outputs() and not self.rpc.info('segwit_is_active'):
  640. rdie(2,f'{g.proj_name} Segwit address requested on the command line, '
  641. + 'but Segwit is not active on this chain')
  642. if not self.outputs:
  643. die(2,'At least one output must be specified on the command line')
  644. async def get_outputs_from_cmdline(self,cmd_args):
  645. from .addrdata import AddrData,TwAddrData
  646. from .addrlist import AddrList
  647. from .addrfile import AddrFile
  648. addrfiles = remove_dups(
  649. tuple(a for a in cmd_args if get_extension(a) == AddrFile.ext),
  650. desc = 'command line',
  651. edesc = 'argument',
  652. )
  653. cmd_args = remove_dups(
  654. tuple(a for a in cmd_args if a not in addrfiles),
  655. desc = 'command line',
  656. edesc = 'argument',
  657. )
  658. ad_f = AddrData(self.proto)
  659. from .fileutil import check_infile
  660. for a in addrfiles:
  661. check_infile(a)
  662. ad_f.add(AddrList(self.proto,a))
  663. ad_w = await TwAddrData(self.proto,wallet=self.tw)
  664. self.process_cmd_args(cmd_args,ad_f,ad_w)
  665. self.add_mmaddrs_to_outputs(ad_w,ad_f)
  666. self.check_dup_addrs('outputs')
  667. # inputs methods
  668. def select_unspent(self,unspent):
  669. prompt = 'Enter a range or space-separated list of outputs to spend: '
  670. while True:
  671. reply = line_input(prompt).strip()
  672. if reply:
  673. from .addrlist import AddrIdxList
  674. selected = get_obj(AddrIdxList, fmt_str=','.join(reply.split()) )
  675. if selected:
  676. if selected[-1] <= len(unspent):
  677. return selected
  678. msg(f'Unspent output number must be <= {len(unspent)}')
  679. def select_unspent_cmdline(self,unspent):
  680. def idx2num(idx):
  681. uo = unspent[idx]
  682. mmid_disp = f' ({uo.twmmid})' if uo.twmmid.type == 'mmgen' else ''
  683. msg(f'Adding input: {idx + 1} {uo.addr}{mmid_disp}')
  684. return idx + 1
  685. def get_uo_nums():
  686. for addr in opt.inputs.split(','):
  687. if is_mmgen_id(self.proto,addr):
  688. attr = 'twmmid'
  689. elif is_coin_addr(self.proto,addr):
  690. attr = 'addr'
  691. else:
  692. die(1,f'{addr!r}: not an MMGen ID or {self.coin} address')
  693. found = False
  694. for idx in range(len(unspent)):
  695. if getattr(unspent[idx],attr) == addr:
  696. yield idx2num(idx)
  697. found = True
  698. if not found:
  699. die(1,f'{addr!r}: address not found in tracking wallet')
  700. return set(get_uo_nums()) # silently discard duplicates
  701. # we don't know fee yet, so perform preliminary check with fee == 0
  702. async def precheck_sufficient_funds(self,inputs_sum,sel_unspent,outputs_sum):
  703. if self.twuo.total < outputs_sum:
  704. msg(self.msg_wallet_low_coin.format(outputs_sum-inputs_sum,self.dcoin))
  705. return False
  706. if inputs_sum < outputs_sum:
  707. msg(self.msg_low_coin.format(outputs_sum-inputs_sum,self.dcoin))
  708. return False
  709. return True
  710. def copy_inputs_from_tw(self,tw_unspent_data):
  711. def gen_inputs():
  712. for d in tw_unspent_data:
  713. i = MMGenTxInput(
  714. self.proto,
  715. **{attr:getattr(d,attr) for attr in d.__dict__ if attr in MMGenTxInput.tw_copy_attrs} )
  716. if d.twmmid.type == 'mmgen':
  717. i.mmid = d.twmmid # twmmid -> mmid
  718. yield i
  719. self.inputs = MMGenTxInputList(self,list(gen_inputs()))
  720. async def get_funds_left(self,fee,outputs_sum):
  721. return self.sum_inputs() - outputs_sum - fee
  722. def final_inputs_ok_msg(self,funds_left):
  723. return 'Transaction produces {} {} in change'.format(
  724. self.proto.coin_amt(funds_left).hl(),
  725. self.coin
  726. )
  727. def warn_insufficient_funds(self,funds_left):
  728. msg(self.msg_low_coin.format(self.proto.coin_amt(-funds_left).hl(),self.coin))
  729. async def get_inputs_from_user(self,outputs_sum):
  730. while True:
  731. us_f = self.select_unspent_cmdline if opt.inputs else self.select_unspent
  732. sel_nums = us_f(self.twuo.unspent)
  733. msg(f'Selected output{suf(sel_nums)}: {{}}'.format(' '.join(str(n) for n in sel_nums)))
  734. sel_unspent = self.twuo.MMGenTwOutputList([self.twuo.unspent[i-1] for i in sel_nums])
  735. inputs_sum = sum(s.amt for s in sel_unspent)
  736. if not await self.precheck_sufficient_funds(inputs_sum,sel_unspent,outputs_sum):
  737. continue
  738. self.copy_inputs_from_tw(sel_unspent) # makes self.inputs
  739. self.usr_fee = await self.get_fee_from_user()
  740. funds_left = await self.get_funds_left(self.usr_fee,outputs_sum)
  741. if funds_left >= 0:
  742. p = self.final_inputs_ok_msg(funds_left)
  743. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  744. if opt.yes:
  745. msg(p)
  746. return funds_left
  747. else:
  748. self.warn_insufficient_funds(funds_left)
  749. def update_change_output(self,funds_left):
  750. chg_idx = self.get_chg_output_idx()
  751. if funds_left == 0:
  752. msg(self.no_chg_msg)
  753. self.del_output(chg_idx)
  754. else:
  755. self.update_output_amt(chg_idx,self.proto.coin_amt(funds_left))
  756. def check_fee(self):
  757. fee = self.sum_inputs() - self.sum_outputs()
  758. if fee > self.proto.max_tx_fee:
  759. c = self.proto.coin
  760. raise MaxFeeExceeded(f'Transaction fee of {fee} {c} too high! (> {self.proto.max_tx_fee} {c})')
  761. def update_txid(self):
  762. self.txid = MMGenTxID(make_chksum_6(bytes.fromhex(self.hex)).upper())
  763. async def create_raw(self):
  764. i = [{'txid':e.txid,'vout':e.vout} for e in self.inputs]
  765. if self.inputs[0].sequence:
  766. i[0]['sequence'] = self.inputs[0].sequence
  767. o = {e.addr:e.amt for e in self.outputs}
  768. self.hex = HexStr(await self.rpc.call('createrawtransaction',i,o))
  769. self.update_txid()
  770. async def create(self,cmd_args,locktime,do_info=False,caller='txcreate'):
  771. assert isinstance(locktime,int),'locktime must be of type int'
  772. from .twuo import TwUnspentOutputs
  773. if opt.comment_file:
  774. self.add_comment(opt.comment_file)
  775. twuo_addrs = await self.get_cmdline_input_addrs()
  776. self.twuo = await TwUnspentOutputs(self.proto,minconf=opt.minconf,addrs=twuo_addrs)
  777. await self.twuo.get_unspent_data()
  778. if not do_info:
  779. await self.get_outputs_from_cmdline(cmd_args)
  780. do_license_msg()
  781. if not opt.inputs:
  782. await self.twuo.view_and_sort(self)
  783. self.twuo.display_total()
  784. if do_info:
  785. del self.twuo.wallet
  786. sys.exit(0)
  787. outputs_sum = self.sum_outputs()
  788. msg('Total amount to spend: {}'.format(
  789. f'{outputs_sum.hl()} {self.dcoin}' if outputs_sum else 'Unknown'
  790. ))
  791. funds_left = await self.get_inputs_from_user(outputs_sum)
  792. self.check_non_mmgen_inputs(caller)
  793. self.update_change_output(funds_left)
  794. if self.proto.base_proto == 'Bitcoin':
  795. self.inputs.sort_bip69()
  796. self.outputs.sort_bip69()
  797. # do this only after inputs are sorted
  798. if opt.rbf:
  799. self.inputs[0].sequence = self.proto.max_int - 2 # handles the nLockTime case too
  800. elif locktime:
  801. self.inputs[0].sequence = self.proto.max_int - 1
  802. if not opt.yes:
  803. self.add_comment() # edits an existing comment
  804. await self.create_raw() # creates self.hex, self.txid
  805. if self.proto.base_proto == 'Bitcoin' and locktime:
  806. msg(f'Setting nLockTime to {strfmt_locktime(locktime)}!')
  807. self.set_hex_locktime(locktime)
  808. self.update_txid()
  809. self.locktime = locktime
  810. self.add_timestamp()
  811. self.add_blockcount()
  812. self.chain = self.proto.chain_name
  813. self.check_fee()
  814. qmsg('Transaction successfully created')
  815. new = MMGenTX.Unsigned(data=self.__dict__)
  816. if not opt.yes:
  817. new.view_with_prompt('View transaction details?')
  818. del new.twuo.wallet
  819. return new
  820. class Completed(Base):
  821. """
  822. signed or unsigned transaction with associated file
  823. """
  824. fn_fee_unit = 'satoshi'
  825. view_sort_orders = ('addr','raw')
  826. dfl_view_sort_order = 'addr'
  827. txview_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  828. txview_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  829. txview_ftr_fs = fmt("""
  830. Input amount: {i} {d}
  831. Spend amount: {s} {d}
  832. Change: {C} {d}
  833. Fee: {a} {c}{r}
  834. """)
  835. parsed_hex = None
  836. def __init__(self,filename=None,quiet_open=False,data=None):
  837. MMGenTX.Base.__init__(self)
  838. if data:
  839. assert filename is None, 'MMGenTX.Completed_chk1'
  840. assert type(data) is dict, 'MMGenTX.Completed_chk2'
  841. self.__dict__ = data
  842. return
  843. elif filename:
  844. assert data is None, 'MMGenTX.Completed_chk3'
  845. from .txfile import MMGenTxFile
  846. MMGenTxFile(self).parse(filename,quiet_open=quiet_open)
  847. self.check_pubkey_scripts()
  848. # repeat with sign and send, because coin daemon could be restarted
  849. self.check_correct_chain()
  850. # check signature and witness data
  851. def check_sigs(self): # return False if no sigs, raise exception on error
  852. txins = (self.parsed_hex or DeserializedTX(self.proto,self.hex))['txins']
  853. has_ss = any(ti['scriptSig'] for ti in txins)
  854. has_witness = any('witness' in ti and ti['witness'] for ti in txins)
  855. if not (has_ss or has_witness):
  856. return False
  857. fs = "Hex TX has {} scriptSig but input is of type '{}'!"
  858. for n in range(len(txins)):
  859. ti,mmti = txins[n],self.inputs[n]
  860. if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH
  861. ti['scriptSig'][:6] == '16' + self.proto.witness_vernum_hex + '14' ):
  862. assert 'witness' in ti, 'missing witness'
  863. assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness'
  864. assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
  865. assert mmti.mmtype == ('S','B')[ti['scriptSig']==''], fs.format('witness-type',mmti.mmtype)
  866. else: # non-witness
  867. assert mmti.mmtype not in ('S','B'), fs.format('signature in',mmti.mmtype)
  868. assert not 'witness' in ti, 'non-witness input has witness'
  869. # sig_size 72 (DER format), pubkey_size 'compressed':33, 'uncompressed':65
  870. assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
  871. return True
  872. def check_pubkey_scripts(self):
  873. for n,i in enumerate(self.inputs,1):
  874. addr,fmt = scriptPubKey2addr(self.proto,i.scriptPubKey)
  875. if i.addr != addr:
  876. if fmt != i.addr.addr_fmt:
  877. m = 'Address format of scriptPubKey ({}) does not match that of address ({}) in input #{}'
  878. msg(m.format(fmt,i.addr.addr_fmt,n))
  879. m = 'ERROR: Address and scriptPubKey of transaction input #{} do not match!'
  880. die(3,(m+'\n {:23}{}'*3).format(n, 'address:',i.addr,
  881. 'scriptPubKey:',i.scriptPubKey,
  882. 'scriptPubKey->address:',addr ))
  883. # def is_replaceable_from_rpc(self):
  884. # dec_tx = await self.rpc.call('decoderawtransaction',self.hex)
  885. # return None < dec_tx['vin'][0]['sequence'] <= self.proto.max_int - 2
  886. def is_replaceable(self):
  887. return self.inputs[0].sequence == self.proto.max_int - 2
  888. def check_txfile_hex_data(self):
  889. self.hex = HexStr(self.hex)
  890. def parse_txfile_hex_data(self):
  891. pass
  892. def write_to_file(self,*args,**kwargs):
  893. from .txfile import MMGenTxFile
  894. MMGenTxFile(self).write(*args,**kwargs)
  895. def format_view_body(self,blockcount,nonmm_str,max_mmwid,enl,terse,sort):
  896. if sort not in self.view_sort_orders:
  897. die(1,'{!r}: invalid transaction view sort order. Valid options: {}'.format(
  898. sort,
  899. ','.join(self.view_sort_orders) ))
  900. def format_io(desc):
  901. io = getattr(self,desc)
  902. is_input = desc == 'inputs'
  903. yield desc.capitalize() + ':\n' + enl
  904. confs_per_day = 60*60*24 // self.proto.avg_bdi
  905. io_sorted = {
  906. 'addr': lambda: sorted(
  907. io, # prepend '+' (sorts before '0') to ensure non-MMGen addrs are displayed first
  908. key = lambda o: (o.mmid.sort_key if o.mmid else f'+{o.addr}') + f'{o.amt:040.20f}' ),
  909. 'raw': lambda: io
  910. }[sort]
  911. for n,e in enumerate(io_sorted()):
  912. if is_input and blockcount:
  913. confs = e.confs + blockcount - self.blockcount
  914. days = int(confs // confs_per_day)
  915. if e.mmid:
  916. mmid_fmt = e.mmid.fmt(
  917. width=max_mmwid,
  918. encl='()',
  919. color=True,
  920. append_chars=('',' (chg)')[bool(not is_input and e.is_chg and terse)],
  921. append_color='green')
  922. else:
  923. mmid_fmt = MMGenID.fmtc(nonmm_str,width=max_mmwid,color=True)
  924. if terse:
  925. yield '{:3} {} {} {} {}\n'.format(
  926. n+1,
  927. e.addr.fmt(color=True,width=addr_w),
  928. mmid_fmt,
  929. e.amt.hl(),
  930. self.dcoin )
  931. else:
  932. def gen():
  933. if is_input:
  934. yield (n+1, 'tx,vout:', f'{e.txid.hl()},{red(str(e.vout))}')
  935. yield ('', 'address:', f'{e.addr.hl()} {mmid_fmt}')
  936. else:
  937. yield (n+1, 'address:', f'{e.addr.hl()} {mmid_fmt}')
  938. if e.label:
  939. yield ('', 'comment:', e.label.hl())
  940. yield ('', 'amount:', f'{e.amt.hl()} {self.dcoin}')
  941. if is_input and blockcount:
  942. yield ('', 'confirmations:', f'{confs} (around {days} days)')
  943. if not is_input and e.is_chg:
  944. yield ('', 'change:', green('True'))
  945. yield '\n'.join('{:>3} {:<8} {}'.format(*d) for d in gen()) + '\n\n'
  946. addr_w = max(len(e.addr) for f in (self.inputs,self.outputs) for e in f)
  947. return (
  948. 'Displaying inputs and outputs in {} sort order'.format({'raw':'raw','addr':'address'}[sort])
  949. + ('\n\n','\n')[terse]
  950. + ''.join(format_io('inputs'))
  951. + ''.join(format_io('outputs')) )
  952. @property
  953. def send_amt(self):
  954. return self.sum_outputs(
  955. exclude = None if len(self.outputs) == 1 else self.get_chg_output_idx()
  956. )
  957. @property
  958. def fee(self):
  959. return self.sum_inputs() - self.sum_outputs()
  960. @property
  961. def change(self):
  962. return self.sum_outputs() - self.send_amt
  963. def format_view_rel_fee(self,terse):
  964. return ' ({} {}, {} of spend amount)'.format(
  965. pink(str(self.fee_abs2rel(self.fee))),
  966. self.rel_fee_disp,
  967. pink('{:0.6f}%'.format( self.fee / self.send_amt * 100 ))
  968. )
  969. def format_view_abs_fee(self):
  970. return self.proto.coin_amt(self.fee).hl()
  971. def format_view_verbose_footer(self):
  972. tsize = len(self.hex)//2 if self.hex else 'unknown'
  973. out = f'Transaction size: Vsize {self.estimate_size()} (estimated), Total {tsize}'
  974. if self.name == 'Signed':
  975. wsize = DeserializedTX(self.proto,self.hex)['witness_size']
  976. out += f', Base {tsize-wsize}, Witness {wsize}'
  977. return out + '\n'
  978. def format_view(self,terse=False,sort=dfl_view_sort_order):
  979. blockcount = None
  980. if self.proto.base_coin != 'ETH':
  981. try:
  982. blockcount = self.rpc.blockcount
  983. except:
  984. pass
  985. def get_max_mmwid(io):
  986. if io == self.inputs:
  987. sel_f = lambda o: len(o.mmid) + 2 # len('()')
  988. else:
  989. sel_f = lambda o: len(o.mmid) + (2,8)[bool(o.is_chg)] # + len(' (chg)')
  990. return max(max([sel_f(o) for o in io if o.mmid] or [0]),len(nonmm_str))
  991. nonmm_str = f'(non-{g.proj_name} address)'
  992. max_mmwid = max(get_max_mmwid(self.inputs),get_max_mmwid(self.outputs))
  993. def gen_view():
  994. yield (self.txview_hdr_fs_short if terse else self.txview_hdr_fs).format(
  995. i = self.txid.hl(),
  996. a = self.send_amt.hl(),
  997. c = self.dcoin,
  998. t = self.timestamp,
  999. r = (red('False'),green('True'))[self.is_replaceable()],
  1000. s = (red('False'),green('True'))[self.name == 'Signed'],
  1001. l = (green('None'),orange(strfmt_locktime(self.locktime,terse=True)))[bool(self.locktime)] )
  1002. if self.chain != 'mainnet': # if mainnet has a coin-specific name, display it
  1003. yield green(f'Chain: {self.chain.upper()}') + '\n'
  1004. if self.coin_txid:
  1005. yield f'{self.coin} TxID: {self.coin_txid.hl()}\n'
  1006. enl = ('\n','')[bool(terse)]
  1007. yield enl
  1008. if self.label:
  1009. yield f'Comment: {self.label.hl()}\n{enl}'
  1010. yield self.format_view_body(blockcount,nonmm_str,max_mmwid,enl,terse=terse,sort=sort)
  1011. yield self.txview_ftr_fs.format(
  1012. i = self.sum_inputs().hl(),
  1013. o = self.sum_outputs().hl(),
  1014. C = self.change.hl(),
  1015. s = self.send_amt.hl(),
  1016. a = self.format_view_abs_fee(),
  1017. r = self.format_view_rel_fee(terse),
  1018. d = self.dcoin,
  1019. c = self.coin )
  1020. if opt.verbose:
  1021. yield self.format_view_verbose_footer()
  1022. return ''.join(gen_view()) # TX label might contain non-ascii chars
  1023. def view_with_prompt(self,prompt='',pause=True):
  1024. prompt += ' (y)es, (N)o, pager (v)iew, (t)erse view: '
  1025. from .term import get_char
  1026. ok_chars = 'YyNnVvTt'
  1027. while True:
  1028. reply = get_char(prompt,immed_chars=ok_chars).strip('\n\r')
  1029. msg('')
  1030. if reply == '' or reply in 'Nn':
  1031. break
  1032. elif reply in 'YyVvTt':
  1033. self.view(pager=reply in 'Vv',terse=reply in 'Tt',pause=pause)
  1034. break
  1035. else:
  1036. msg('Invalid reply')
  1037. def view(self,pager=False,pause=True,terse=False):
  1038. o = self.format_view(terse=terse)
  1039. if pager:
  1040. do_pager(o)
  1041. else:
  1042. msg_r(o)
  1043. from .term import get_char
  1044. if pause:
  1045. get_char('Press any key to continue: ')
  1046. msg('')
  1047. class Unsigned(Completed):
  1048. desc = 'unsigned transaction'
  1049. ext = 'rawtx'
  1050. def __init__(self,*args,**kwargs):
  1051. super().__init__(*args,**kwargs)
  1052. if self.check_sigs():
  1053. die(1,'Transaction is signed!')
  1054. def delete_attrs(self,desc,attr):
  1055. for e in getattr(self,desc):
  1056. if hasattr(e,attr):
  1057. delattr(e,attr)
  1058. def get_sids(self,desc):
  1059. return remove_dups(
  1060. (e.mmid.sid for e in getattr(self,desc) if e.mmid),
  1061. quiet = True )
  1062. async def sign(self,tx_num_str,keys): # return signed object or False; don't exit or raise exception
  1063. try:
  1064. self.check_correct_chain()
  1065. except TransactionChainMismatch:
  1066. return False
  1067. if (self.has_segwit_inputs() or self.has_segwit_outputs()) and not self.proto.cap('segwit'):
  1068. ymsg(f"TX has Segwit inputs or outputs, but {self.coin} doesn't support Segwit!")
  1069. return False
  1070. self.check_pubkey_scripts()
  1071. qmsg(f'Passing {len(keys)} key{suf(keys)} to {self.rpc.daemon.exec_fn}')
  1072. if self.has_segwit_inputs():
  1073. from .addr import KeyGenerator,AddrGenerator
  1074. kg = KeyGenerator(self.proto,'std')
  1075. ag = AddrGenerator(self.proto,'segwit')
  1076. keydict = MMGenDict([(d.addr,d.sec) for d in keys])
  1077. sig_data = []
  1078. for d in self.inputs:
  1079. e = {k:getattr(d,k) for k in ('txid','vout','scriptPubKey','amt')}
  1080. e['amount'] = e['amt']
  1081. del e['amt']
  1082. if d.mmtype == 'S':
  1083. e['redeemScript'] = ag.to_segwit_redeem_script(kg.gen_data(keydict[d.addr]))
  1084. sig_data.append(e)
  1085. msg_r(f'Signing transaction{tx_num_str}...')
  1086. wifs = [d.sec.wif for d in keys]
  1087. try:
  1088. args = (
  1089. ('signrawtransaction', self.hex,sig_data,wifs,self.proto.sighash_type),
  1090. ('signrawtransactionwithkey',self.hex,wifs,sig_data,self.proto.sighash_type)
  1091. )['sign_with_key' in self.rpc.caps]
  1092. ret = await self.rpc.call(*args)
  1093. except Exception as e:
  1094. msg(yellow((
  1095. e.args[0],
  1096. 'This is not the BCH chain.\nRe-run the script without the --coin=bch option.'
  1097. )['Invalid sighash param' in e.args[0]]))
  1098. return False
  1099. try:
  1100. self.hex = HexStr(ret['hex'])
  1101. self.parsed_hex = dtx = DeserializedTX(self.proto,self.hex)
  1102. new = MMGenTX.Signed(data=self.__dict__)
  1103. tx_decoded = await self.rpc.call('decoderawtransaction',ret['hex'])
  1104. new.compare_size_and_estimated_size(tx_decoded)
  1105. new.check_hex_tx_matches_mmgen_tx(dtx)
  1106. new.coin_txid = CoinTxID(dtx['txid'])
  1107. if not new.coin_txid == tx_decoded['txid']:
  1108. raise BadMMGenTxID('txid mismatch (after signing)')
  1109. msg('OK')
  1110. return new
  1111. except Exception as e:
  1112. try: m = '{}'.format(e.args[0])
  1113. except: m = repr(e.args[0])
  1114. msg('\n'+yellow(m))
  1115. if g.traceback:
  1116. import traceback
  1117. ymsg('\n'+''.join(traceback.format_exception(*sys.exc_info())))
  1118. return False
  1119. class Signed(Completed):
  1120. desc = 'signed transaction'
  1121. ext = 'sigtx'
  1122. def __init__(self,*args,**kwargs):
  1123. if 'tw' in kwargs:
  1124. self.tw = kwargs['tw']
  1125. del kwargs['tw']
  1126. super().__init__(*args,**kwargs)
  1127. if not self.check_sigs():
  1128. die(1,'Transaction is not signed!')
  1129. # check that a malicious, compromised or malfunctioning coin daemon hasn't altered hex tx data:
  1130. # does not check witness or signature data
  1131. def check_hex_tx_matches_mmgen_tx(self,dtx):
  1132. m = 'A malicious or malfunctioning coin daemon or other program may have altered your data!'
  1133. lt = dtx['lock_time']
  1134. if lt != int(self.locktime or 0):
  1135. m2 = 'Transaction hex nLockTime ({}) does not match MMGen transaction nLockTime ({})\n{}'
  1136. raise TxHexMismatch(m2.format(lt,self.locktime,m))
  1137. def check_equal(desc,hexio,mmio):
  1138. if mmio != hexio:
  1139. msg('\nMMGen {}:\n{}'.format(desc,pp_fmt(mmio)))
  1140. msg('Hex {}:\n{}'.format(desc,pp_fmt(hexio)))
  1141. m2 = '{} in hex transaction data from coin daemon do not match those in MMGen transaction!\n'
  1142. raise TxHexMismatch((m2+m).format(desc.capitalize()))
  1143. seq_hex = [int(i['nSeq'],16) for i in dtx['txins']]
  1144. seq_mmgen = [i.sequence or self.proto.max_int for i in self.inputs]
  1145. check_equal('sequence numbers',seq_hex,seq_mmgen)
  1146. d_hex = sorted((i['txid'],i['vout']) for i in dtx['txins'])
  1147. d_mmgen = sorted((i.txid,i.vout) for i in self.inputs)
  1148. check_equal('inputs',d_hex,d_mmgen)
  1149. d_hex = sorted((o['address'],self.proto.coin_amt(o['amount'])) for o in dtx['txouts'])
  1150. d_mmgen = sorted((o.addr,o.amt) for o in self.outputs)
  1151. check_equal('outputs',d_hex,d_mmgen)
  1152. uh = dtx['unsigned_hex']
  1153. if str(self.txid) != make_chksum_6(bytes.fromhex(uh)).upper():
  1154. raise TxHexMismatch(f'MMGen TxID ({self.txid}) does not match hex transaction data!\n{m}')
  1155. def compare_size_and_estimated_size(self,tx_decoded):
  1156. est_vsize = self.estimate_size()
  1157. d = tx_decoded
  1158. vsize = d['vsize'] if 'vsize' in d else d['size']
  1159. vmsg(f'\nVsize: {vsize} (true) {est_vsize} (estimated)')
  1160. ratio = float(est_vsize) / vsize
  1161. if not (0.95 < ratio < 1.05): # allow for 5% error
  1162. from .exception import BadTxSizeEstimate
  1163. raise BadTxSizeEstimate(fmt(f"""
  1164. Estimated transaction vsize is {ratio:1.2f} times the true vsize
  1165. Your transaction fee estimates will be inaccurate
  1166. Please re-create and re-sign the transaction using the option --vsize-adj={1/ratio:1.2f}
  1167. """).strip())
  1168. async def get_status(self,status=False):
  1169. class r(object):
  1170. pass
  1171. async def is_in_wallet():
  1172. try: ret = await self.rpc.call('gettransaction',self.coin_txid)
  1173. except: return False
  1174. if ret.get('confirmations',0) > 0:
  1175. r.confs = ret['confirmations']
  1176. return True
  1177. else:
  1178. return False
  1179. async def is_in_utxos():
  1180. try: return 'txid' in await self.rpc.call('getrawtransaction',self.coin_txid,True)
  1181. except: return False
  1182. async def is_in_mempool():
  1183. try: return 'height' in await self.rpc.call('getmempoolentry',self.coin_txid)
  1184. except: return False
  1185. async def is_replaced():
  1186. if await is_in_mempool():
  1187. return False
  1188. try:
  1189. ret = await self.rpc.call('gettransaction',self.coin_txid)
  1190. except:
  1191. return False
  1192. else:
  1193. if 'bip125-replaceable' in ret and ret.get('confirmations',1) <= 0:
  1194. r.replacing_confs = -ret['confirmations']
  1195. r.replacing_txs = ret['walletconflicts']
  1196. return True
  1197. else:
  1198. return False
  1199. if await is_in_mempool():
  1200. if status:
  1201. d = await self.rpc.call('gettransaction',self.coin_txid)
  1202. rep = ('' if d.get('bip125-replaceable') == 'yes' else 'NOT ') + 'replaceable'
  1203. t = d['timereceived']
  1204. if opt.quiet:
  1205. msg('Transaction is in mempool')
  1206. else:
  1207. msg(f'TX status: in mempool, {rep}')
  1208. msg('Sent {} ({} ago)'.format(
  1209. time.strftime('%c',time.gmtime(t)),
  1210. secs_to_dhms(int(time.time()-t))) )
  1211. else:
  1212. msg('Warning: transaction is in mempool!')
  1213. elif await is_in_wallet():
  1214. die(0,f'Transaction has {r.confs} confirmation{suf(r.confs)}')
  1215. elif await is_in_utxos():
  1216. die(2,red('ERROR: transaction is in the blockchain (but not in the tracking wallet)!'))
  1217. elif await is_replaced():
  1218. msg('Transaction has been replaced')
  1219. msg('Replacement transaction ' + (
  1220. f'has {r.replacing_confs} confirmation{suf(r.replacing_confs)}'
  1221. if r.replacing_confs else
  1222. 'is in mempool' ) )
  1223. if not opt.quiet:
  1224. msg('Replacing transactions:')
  1225. d = []
  1226. for txid in r.replacing_txs:
  1227. try: d.append(await self.rpc.call('getmempoolentry',txid))
  1228. except: d.append({})
  1229. for txid,mp_entry in zip(r.replacing_txs,d):
  1230. msg(f' {txid}' + (' in mempool' if 'height' in mp_entry else '') )
  1231. die(0,'')
  1232. def confirm_send(self):
  1233. confirm_or_raise(
  1234. ('' if opt.quiet else "Once this transaction is sent, there's no taking it back!"),
  1235. f'broadcast this transaction to the {self.proto.coin} {self.proto.network.upper()} network',
  1236. ('YES' if opt.quiet or opt.yes else 'YES, I REALLY WANT TO DO THIS') )
  1237. msg('Sending transaction')
  1238. async def send(self,prompt_user=True,exit_on_fail=False):
  1239. self.check_correct_chain()
  1240. self.check_pubkey_scripts()
  1241. self.check_hex_tx_matches_mmgen_tx(DeserializedTX(self.proto,self.hex))
  1242. if not g.bogus_send:
  1243. if self.has_segwit_outputs() and not self.rpc.info('segwit_is_active'):
  1244. die(2,'Transaction has Segwit outputs, but this blockchain does not support Segwit'
  1245. + ' at the current height')
  1246. if self.fee > self.proto.max_tx_fee:
  1247. die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
  1248. self.fee,
  1249. self.proto.name,
  1250. self.proto.max_tx_fee,
  1251. self.proto.coin ))
  1252. await self.get_status()
  1253. if prompt_user:
  1254. self.confirm_send()
  1255. if g.bogus_send:
  1256. ret = None
  1257. else:
  1258. try:
  1259. ret = await self.rpc.call('sendrawtransaction',self.hex)
  1260. except Exception as e:
  1261. errmsg = e
  1262. ret = False
  1263. if ret == False: # TODO: test send errors
  1264. if errmsg.count('Signature must use SIGHASH_FORKID'):
  1265. m = ('The Aug. 1 2017 UAHF has activated on this chain.\n'
  1266. + 'Re-run the script with the --coin=bch option.' )
  1267. elif errmsg.count('Illegal use of SIGHASH_FORKID'):
  1268. m = ('The Aug. 1 2017 UAHF is not yet active on this chain.\n'
  1269. + 'Re-run the script without the --coin=bch option.' )
  1270. elif errmsg.count('64: non-final'):
  1271. m = "Transaction with nLockTime {!r} can't be included in this block!".format(
  1272. strfmt_locktime(self.get_hex_locktime()) )
  1273. else:
  1274. m = errmsg
  1275. ymsg(m)
  1276. rmsg(f'Send of MMGen transaction {self.txid} failed')
  1277. if exit_on_fail:
  1278. sys.exit(1)
  1279. return False
  1280. else:
  1281. if g.bogus_send:
  1282. m = 'BOGUS transaction NOT sent: {}'
  1283. else:
  1284. m = 'Transaction sent: {}'
  1285. assert ret == self.coin_txid, 'txid mismatch (after sending)'
  1286. msg(m.format(self.coin_txid.hl()))
  1287. self.add_timestamp()
  1288. self.add_blockcount()
  1289. self.desc = 'sent transaction'
  1290. return True
  1291. def print_contract_addr(self):
  1292. pass
  1293. @staticmethod
  1294. async def get_tracking_wallet(filename):
  1295. from .txfile import MMGenTxFile
  1296. tmp_tx = MMGenTX.Base()
  1297. MMGenTxFile(tmp_tx).parse(filename,metadata_only=True)
  1298. if tmp_tx.proto.tokensym:
  1299. from .twctl import TrackingWallet
  1300. return await TrackingWallet(tmp_tx.proto)
  1301. else:
  1302. return None
  1303. class Bump(Completed,New):
  1304. desc = 'fee-bumped transaction'
  1305. ext = 'rawtx'
  1306. min_fee = None
  1307. bump_output_idx = None
  1308. def __init__(self,data,send,tw=None):
  1309. MMGenTX.Completed.__init__(self,data=data)
  1310. self.tw = tw
  1311. if not self.is_replaceable():
  1312. die(1,f'Transaction {self.txid} is not replaceable')
  1313. # If sending, require original tx to be sent
  1314. if send and not self.coin_txid:
  1315. die(1,'Transaction {self.txid!r} was not broadcast to the network')
  1316. self.coin_txid = ''
  1317. def check_sufficient_funds_for_bump(self):
  1318. if not [o.amt for o in self.outputs if o.amt >= self.min_fee]:
  1319. die(1,
  1320. 'Transaction cannot be bumped.\n' +
  1321. f'All outputs contain less than the minimum fee ({self.min_fee} {self.coin})')
  1322. def choose_output(self):
  1323. chg_idx = self.get_chg_output_idx()
  1324. init_reply = opt.output_to_reduce
  1325. def check_sufficient_funds(o_amt):
  1326. if o_amt < self.min_fee:
  1327. msg(f'Minimum fee ({self.min_fee} {self.coin}) is greater than output amount ({o_amt} {self.coin})')
  1328. return False
  1329. return True
  1330. if len(self.outputs) == 1:
  1331. if check_sufficient_funds(self.outputs[0].amt):
  1332. self.bump_output_idx = 0
  1333. return 0
  1334. else:
  1335. die(1,'Insufficient funds to bump transaction')
  1336. while True:
  1337. if init_reply == None:
  1338. m = 'Choose an output to deduct the fee from (Hit ENTER for the change output): '
  1339. reply = line_input(m) or 'c'
  1340. else:
  1341. reply,init_reply = init_reply,None
  1342. if chg_idx == None and not is_int(reply):
  1343. msg('Output must be an integer')
  1344. elif chg_idx != None and not is_int(reply) and reply != 'c':
  1345. msg("Output must be an integer, or 'c' for the change output")
  1346. else:
  1347. idx = chg_idx if reply == 'c' else (int(reply) - 1)
  1348. if idx < 0 or idx >= len(self.outputs):
  1349. msg(f'Output must be in the range 1-{len(self.outputs)}')
  1350. else:
  1351. o_amt = self.outputs[idx].amt
  1352. cm = ' (change output)' if chg_idx == idx else ''
  1353. prompt = f'Fee will be deducted from output {idx+1}{cm} ({o_amt} {self.coin})'
  1354. if check_sufficient_funds(o_amt):
  1355. if opt.yes or keypress_confirm(prompt+'. OK?',default_yes=True):
  1356. if opt.yes:
  1357. msg(prompt)
  1358. self.bump_output_idx = idx
  1359. return idx
  1360. @property
  1361. def min_fee(self):
  1362. return self.sum_inputs() - self.sum_outputs() + self.relay_fee
  1363. def bump_fee(self,idx,fee):
  1364. self.update_output_amt(
  1365. idx,
  1366. self.sum_inputs() - self.sum_outputs(exclude=idx) - fee
  1367. )
  1368. def convert_and_check_fee(self,tx_fee,desc):
  1369. ret = super().convert_and_check_fee(tx_fee,desc)
  1370. if ret < self.min_fee:
  1371. msg('{} {c}: {} fee too small. Minimum fee: {} {c} ({} {})'.format(
  1372. ret.hl(),
  1373. desc,
  1374. self.min_fee,
  1375. self.fee_abs2rel(self.min_fee.hl()),
  1376. self.rel_fee_desc,
  1377. c = self.coin ))
  1378. return False
  1379. output_amt = self.outputs[self.bump_output_idx].amt
  1380. if ret >= output_amt:
  1381. msg('{} {c}: {} fee too large. Maximum fee: <{} {c}'.format(
  1382. ret.hl(),
  1383. desc,
  1384. output_amt.hl(),
  1385. c = self.coin ))
  1386. return False
  1387. return ret
  1388. # NOT MAINTAINED
  1389. # class Split(Base):
  1390. #
  1391. # async def get_outputs_from_cmdline(self,mmid): # TODO: check that addr is empty
  1392. #
  1393. # from .addrdata import TwAddrData
  1394. # ad_w = await TwAddrData()
  1395. #
  1396. # if is_mmgen_id(self.proto,mmid):
  1397. # coin_addr = mmaddr2coinaddr(mmid,ad_w,None) if is_mmgen_id(self.proto,mmid) else CoinAddr(mmid)
  1398. # self.add_output(coin_addr,self.proto.coin_amt('0'),is_chg=True)
  1399. # else:
  1400. # die(2,'{}: invalid command-line argument'.format(mmid))
  1401. #
  1402. # self.add_mmaddrs_to_outputs(ad_w,None)
  1403. #
  1404. # if not segwit_is_active() and self.has_segwit_outputs():
  1405. # fs = '{} Segwit address requested on the command line, but Segwit is not active on this chain'
  1406. # rdie(2,fs.format(g.proj_name))
  1407. #
  1408. # def get_split_fee_from_user(self):
  1409. # if opt.rpc_host2:
  1410. # g.rpc_host = opt.rpc_host2
  1411. # if opt.tx_fees:
  1412. # opt.tx_fee = opt.tx_fees.split(',')[1]
  1413. # return super().get_fee_from_user()
  1414. #
  1415. # async def create_split(self,mmid):
  1416. #
  1417. # self.outputs = self.MMGenTxOutputList(self)
  1418. # await self.get_outputs_from_cmdline(mmid)
  1419. #
  1420. # while True:
  1421. # funds_left = self.sum_inputs() - self.get_split_fee_from_user()
  1422. # if funds_left >= 0:
  1423. # p = 'Transaction produces {} {} in change'.format(funds_left.hl(),self.coin)
  1424. # if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1425. # if opt.yes:
  1426. # msg(p)
  1427. # break
  1428. # else:
  1429. # self.warn_insufficient_funds(funds_left)
  1430. #
  1431. # self.update_output_amt(0,funds_left)
  1432. #
  1433. # if not opt.yes:
  1434. # self.add_comment() # edits an existing comment
  1435. #
  1436. # await self.create_raw() # creates self.hex, self.txid
  1437. #
  1438. # self.add_timestamp()
  1439. # self.add_blockcount() # TODO
  1440. # self.chain = g.chain
  1441. #
  1442. # assert self.sum_inputs() - self.sum_outputs() <= self.proto.max_tx_fee
  1443. #
  1444. # qmsg('Transaction successfully created')
  1445. #
  1446. # if not opt.yes:
  1447. # self.view_with_prompt('View transaction details?')