tx.py 55 KB

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