tx.py 55 KB

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