tx.py 56 KB

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