tx.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2018 The MMGen Project <mmgen@tuta.io>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. tx.py: Transaction routines for the MMGen suite
  21. """
  22. import sys,os
  23. from stat import *
  24. from binascii import unhexlify
  25. from mmgen.common import *
  26. from mmgen.obj import *
  27. pnm = g.proj_name
  28. wmsg = {
  29. 'addr_in_addrfile_only': """
  30. Warning: output address {mmgenaddr} is not in the tracking wallet, which means
  31. its balance will not be tracked. You're strongly advised to import the address
  32. into your tracking wallet before broadcasting this transaction.
  33. """.strip(),
  34. 'addr_not_found': """
  35. No data for {pnm} address {mmgenaddr} could be found in either the tracking
  36. wallet or the supplied address file. Please import this address into your
  37. tracking wallet, or supply an address file for it on the command line.
  38. """.strip(),
  39. 'addr_not_found_no_addrfile': """
  40. No data for {pnm} address {mmgenaddr} could be found in the tracking wallet.
  41. Please import this address into your tracking wallet or supply an address file
  42. for it on the command line.
  43. """.strip(),
  44. 'non_mmgen_inputs': """
  45. NOTE: This transaction includes non-{pnm} inputs, which makes the signing
  46. process more complicated. When signing the transaction, keys for non-{pnm}
  47. inputs must be supplied to '{pnl}-txsign' in a file with the '--keys-from-file'
  48. option.
  49. Selected non-{pnm} inputs: {{}}
  50. """.strip().format(pnm=pnm,pnl=pnm.lower()),
  51. 'not_enough_coin': """
  52. Selected outputs insufficient to fund this transaction ({{}} {} needed)
  53. """.strip().format(g.coin),
  54. 'no_change_output': """
  55. ERROR: No change address specified. If you wish to create a transaction with
  56. only one output, specify a single output address with no {} amount
  57. """.strip().format(g.coin),
  58. }
  59. def strfmt_locktime(num,terse=False):
  60. # Locktime itself is an unsigned 4-byte integer which can be parsed two ways:
  61. #
  62. # If less than 500 million, locktime is parsed as a block height. The transaction can be
  63. # added to any block which has this height or higher.
  64. # MMGen note: s/this height or higher/a higher block height/
  65. #
  66. # If greater than or equal to 500 million, locktime is parsed using the Unix epoch time
  67. # format (the number of seconds elapsed since 1970-01-01T00:00 UTC). The transaction can be
  68. # added to any block whose block time is greater than the locktime.
  69. if num >= 5 * 10**6:
  70. return ' '.join(time.strftime('%c',time.gmtime(num)).split()[1:])
  71. elif num > 0:
  72. return '{}{}'.format(('block height ','')[terse],num)
  73. elif num == None:
  74. return '(None)'
  75. else:
  76. die(2,"'{}': invalid locktime value!".format(num))
  77. def mmaddr2coinaddr(mmaddr,ad_w,ad_f):
  78. # assume mmaddr has already been checked
  79. coin_addr = ad_w.mmaddr2coinaddr(mmaddr)
  80. if not coin_addr:
  81. if ad_f:
  82. coin_addr = ad_f.mmaddr2coinaddr(mmaddr)
  83. if coin_addr:
  84. msg(wmsg['addr_in_addrfile_only'].format(mmgenaddr=mmaddr))
  85. if not keypress_confirm('Continue anyway?'):
  86. sys.exit(1)
  87. else:
  88. die(2,wmsg['addr_not_found'].format(pnm=pnm,mmgenaddr=mmaddr))
  89. else:
  90. die(2,wmsg['addr_not_found_no_addrfile'].format(pnm=pnm,mmgenaddr=mmaddr))
  91. return CoinAddr(coin_addr)
  92. def segwit_is_active(exit_on_error=False):
  93. d = g.rpch.getblockchaininfo()
  94. if d['chain'] == 'regtest':
  95. return True
  96. if 'segwit' in d['bip9_softforks'] and d['bip9_softforks']['segwit']['status'] == 'active':
  97. return True
  98. if g.skip_segwit_active_check:
  99. return True
  100. if exit_on_error:
  101. die(2,'Segwit not active on this chain. Exiting')
  102. else:
  103. return False
  104. def bytes2int(hex_bytes):
  105. r = hexlify(unhexlify(hex_bytes)[::-1])
  106. if r[0] in '89abcdef':
  107. die(3,"{}: Negative values not permitted in transaction!".format(hex_bytes))
  108. return int(r,16)
  109. def bytes2coin_amt(hex_bytes):
  110. return g.proto.coin_amt(bytes2int(hex_bytes) * g.proto.coin_amt.min_coin_unit)
  111. def scriptPubKey2addr(s):
  112. if len(s) == 50 and s[:6] == '76a914' and s[-4:] == '88ac':
  113. return g.proto.pubhash2addr(s[6:-4],p2sh=False)
  114. elif len(s) == 46 and s[:4] == 'a914' and s[-2:] == '87':
  115. return g.proto.pubhash2addr(s[4:-2],p2sh=True)
  116. elif len(s) == 44 and s[:4] == g.proto.witness_vernum_hex + '14':
  117. return g.proto.pubhash2bech32addr(s[4:])
  118. else:
  119. raise NotImplementedError,'Unknown scriptPubKey ({})'.format(s)
  120. from collections import OrderedDict
  121. class DeserializedTX(OrderedDict,MMGenObject): # need to add MMGen types
  122. def __init__(self,txhex):
  123. tx = list(unhexlify(txhex))
  124. tx_copy = tx[:]
  125. d = { 'raw_tx':'' }
  126. def hshift(l,n,reverse=False,skip=False):
  127. ret = l[:n]
  128. if not skip: d['raw_tx'] += ''.join(ret)
  129. del l[:n]
  130. return hexlify(''.join(ret[::-1] if reverse else ret))
  131. # https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers
  132. # For example, the number 515 is encoded as 0xfd0302.
  133. def readVInt(l,skip=False,sub_null=False):
  134. s = int(hexlify(l[0]),16)
  135. bytes_len = 1 if s < 0xfd else 2 if s == 0xfd else 4 if s == 0xfe else 8
  136. if bytes_len != 1: del l[0]
  137. ret = int(hexlify(''.join(l[:bytes_len][::-1])),16)
  138. if sub_null: d['raw_tx'] += '\0'
  139. elif not skip: d['raw_tx'] += ''.join(l[:bytes_len])
  140. del l[:bytes_len]
  141. return ret
  142. d['version'] = bytes2int(hshift(tx,4))
  143. has_witness = tx[0] == '\x00'
  144. if has_witness:
  145. u = hshift(tx,2,skip=True)[2:]
  146. if u != '01':
  147. die(2,"'{}': Illegal value for flag in transaction!".format(u))
  148. del tx_copy[-len(tx)-2:-len(tx)]
  149. d['num_txins'] = readVInt(tx)
  150. d['txins'] = MMGenList([OrderedDict((
  151. ('txid', hshift(tx,32,reverse=True)),
  152. ('vout', bytes2int(hshift(tx,4))),
  153. ('scriptSig', hshift(tx,readVInt(tx,sub_null=True),skip=True)),
  154. ('nSeq', hshift(tx,4,reverse=True))
  155. )) for i in range(d['num_txins'])])
  156. d['num_txouts'] = readVInt(tx)
  157. d['txouts'] = MMGenList([OrderedDict((
  158. ('amount', bytes2coin_amt(hshift(tx,8))),
  159. ('scriptPubKey', hshift(tx,readVInt(tx)))
  160. )) for i in range(d['num_txouts'])])
  161. for o in d['txouts']:
  162. o['address'] = scriptPubKey2addr(o['scriptPubKey'])
  163. d['witness_size'] = 0
  164. if has_witness:
  165. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  166. # A non-witness program (defined hereinafter) txin MUST be associated with an empty
  167. # witness field, represented by a 0x00.
  168. del tx_copy[-len(tx):-4]
  169. wd,tx = tx[:-4],tx[-4:]
  170. d['witness_size'] = len(wd) + 2 # add marker and flag
  171. for i in range(len(d['txins'])):
  172. if hexlify(wd[0]) == '00':
  173. hshift(wd,1,skip=True)
  174. continue
  175. d['txins'][i]['witness'] = [
  176. hshift(wd,readVInt(wd,skip=True),skip=True) for item in range(readVInt(wd,skip=True))
  177. ]
  178. if wd:
  179. die(3,'More witness data than inputs with witnesses!')
  180. d['lock_time'] = bytes2int(hshift(tx,4))
  181. d['txid'] = hexlify(sha256(sha256(''.join(tx_copy)).digest()).digest()[::-1])
  182. d['unsigned_hex'] = hexlify(d['raw_tx'])
  183. del d['raw_tx']
  184. keys = 'txid','version','lock_time','witness_size','num_txins','txins','num_txouts','txouts','unsigned_hex'
  185. return OrderedDict.__init__(self, ((k,d[k]) for k in keys))
  186. txio_attrs = {
  187. 'vout': MMGenListItemAttr('vout',int,typeconv=False),
  188. 'amt': MMGenImmutableAttr('amt',g.proto.coin_amt,typeconv=False), # require amt to be of proper type
  189. 'label': MMGenListItemAttr('label','TwComment',reassign_ok=True),
  190. 'mmid': MMGenListItemAttr('mmid','MMGenID'),
  191. 'addr': MMGenImmutableAttr('addr','CoinAddr'),
  192. 'confs': MMGenListItemAttr('confs',int,typeconv=True), # long confs exist in the wild, so convert
  193. 'txid': MMGenListItemAttr('txid','CoinTxID'),
  194. 'have_wif': MMGenListItemAttr('have_wif',bool,typeconv=False,delete_ok=True)
  195. }
  196. class MMGenTX(MMGenObject):
  197. ext = 'rawtx'
  198. raw_ext = 'rawtx'
  199. sig_ext = 'sigtx'
  200. txid_ext = 'txid'
  201. desc = 'transaction'
  202. chg_msg_fs = 'Transaction produces {} {} in change'
  203. fee_fail_fs = 'Network fee estimation for {c} confirmations failed ({t})'
  204. no_chg_msg = 'Warning: Change address will be deleted as transaction produces no change'
  205. rel_fee_desc = 'satoshis per byte'
  206. rel_fee_disp = 'satoshis per byte'
  207. txview_hdr_fs = 'TRANSACTION DATA\n\nID={i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  208. txview_hdr_fs_short = 'TX {i} ({a} {c}) UTC={t} RBF={r} Sig={s} Locktime={l}\n'
  209. usr_fee_prompt = 'Enter transaction fee: '
  210. class MMGenTxInput(MMGenListItem):
  211. for k in txio_attrs: locals()[k] = txio_attrs[k] # in lieu of inheritance
  212. scriptPubKey = MMGenListItemAttr('scriptPubKey','HexStr')
  213. sequence = MMGenListItemAttr('sequence',(int,long)[g.platform=='win'],typeconv=False)
  214. class MMGenTxOutput(MMGenListItem):
  215. for k in txio_attrs: locals()[k] = txio_attrs[k]
  216. is_chg = MMGenListItemAttr('is_chg',bool,typeconv=False)
  217. class MMGenTxInputList(list,MMGenObject):
  218. desc = 'transaction inputs'
  219. member_type = 'MMGenTxInput'
  220. def convert_coin(self,verbose=False):
  221. from mmgen.protocol import CoinProtocol
  222. io = getattr(MMGenTX,self.member_type)
  223. if verbose:
  224. msg('{}:'.format(self.desc.capitalize()))
  225. for i in self:
  226. d = i.__dict__
  227. d['amt'] = g.proto.coin_amt(d['amt'])
  228. i = io(**d)
  229. if verbose:
  230. pmsg(i.__dict__)
  231. def check_coin_mismatch(self):
  232. for i in self:
  233. if type(i.amt) != g.proto.coin_amt:
  234. die(2,'Coin mismatch in transaction: amount {} not of type {}!'.format(i.amt,g.proto.coin_amt))
  235. class MMGenTxOutputList(MMGenTxInputList):
  236. desc = 'transaction outputs'
  237. member_type = 'MMGenTxOutput'
  238. def __init__(self,filename=None,md_only=False,caller=None,silent_open=False):
  239. self.inputs = self.MMGenTxInputList()
  240. self.outputs = self.MMGenTxOutputList()
  241. self.send_amt = g.proto.coin_amt('0') # total amt minus change
  242. self.fee = g.proto.coin_amt('0')
  243. self.hex = '' # raw serialized hex transaction
  244. self.label = MMGenTXLabel('')
  245. self.txid = ''
  246. self.coin_txid = ''
  247. self.timestamp = ''
  248. self.chksum = ''
  249. self.fmt_data = ''
  250. self.fn = ''
  251. self.blockcount = 0
  252. self.chain = None
  253. self.coin = None
  254. self.caller = caller
  255. self.locktime = None
  256. if filename:
  257. self.parse_tx_file(filename,md_only=md_only,silent_open=silent_open)
  258. if md_only: return
  259. self.check_sigs() # marks the tx as signed
  260. # repeat with sign and send, because coin daemon could be restarted
  261. self.check_correct_chain(on_fail='die')
  262. def check_correct_chain(self,on_fail='return'):
  263. assert on_fail in ('return','die'),"'{}': invalid value for 'on_fail'".format(on_fail)
  264. m = 'Transaction is for {}, but current chain is {}!'.format(self.chain,g.chain)
  265. bad = self.chain and g.chain and self.chain != g.chain
  266. if bad:
  267. msg(m) if on_fail == 'return' else die(2,m)
  268. return not bad
  269. def add_output(self,coinaddr,amt,is_chg=None):
  270. self.outputs.append(MMGenTX.MMGenTxOutput(addr=coinaddr,amt=amt,is_chg=is_chg))
  271. def get_chg_output_idx(self):
  272. for i in range(len(self.outputs)):
  273. if self.outputs[i].is_chg == True:
  274. return i
  275. return None
  276. def update_output_amt(self,idx,amt):
  277. o = self.outputs[idx].__dict__
  278. o['amt'] = amt
  279. self.outputs[idx] = MMGenTX.MMGenTxOutput(**o)
  280. def del_output(self,idx):
  281. self.outputs.pop(idx)
  282. def sum_outputs(self,exclude=None):
  283. olist = self.outputs if exclude == None else \
  284. self.outputs[:exclude] + self.outputs[exclude+1:]
  285. return g.proto.coin_amt(sum(e.amt for e in olist))
  286. def add_mmaddrs_to_outputs(self,ad_w,ad_f):
  287. a = [e.addr for e in self.outputs]
  288. d = ad_w.make_reverse_dict(a)
  289. if ad_f:
  290. d.update(ad_f.make_reverse_dict(a))
  291. for e in self.outputs:
  292. if e.addr and e.addr in d:
  293. e.mmid,f = d[e.addr]
  294. if f: e.label = f
  295. def check_dup_addrs(self,io_str):
  296. assert io_str in ('inputs','outputs')
  297. io = getattr(self,io_str)
  298. for k in ('mmid','addr'):
  299. old_attr = None
  300. for attr in sorted(getattr(e,k) for e in io):
  301. if attr != None and attr == old_attr:
  302. die(2,'{}: duplicate address in transaction {}'.format(attr,io_str))
  303. old_attr = attr
  304. def update_txid(self):
  305. self.txid = MMGenTxID(make_chksum_6(unhexlify(self.hex)).upper())
  306. def create_raw(self):
  307. i = [{'txid':e.txid,'vout':e.vout} for e in self.inputs]
  308. if self.inputs[0].sequence:
  309. i[0]['sequence'] = self.inputs[0].sequence
  310. o = dict([(e.addr,e.amt) for e in self.outputs])
  311. self.hex = g.rpch.createrawtransaction(i,o)
  312. self.update_txid()
  313. # returns true if comment added or changed
  314. def add_comment(self,infile=None):
  315. if infile:
  316. self.label = MMGenTXLabel(get_data_from_file(infile,'transaction comment'))
  317. else: # get comment from user, or edit existing comment
  318. m = ('Add a comment to transaction?','Edit transaction comment?')[bool(self.label)]
  319. if keypress_confirm(m,default_yes=False):
  320. while True:
  321. s = MMGenTXLabel(my_raw_input('Comment: ',insert_txt=self.label))
  322. if s:
  323. lbl_save = self.label
  324. self.label = s
  325. return (True,False)[lbl_save == self.label]
  326. else:
  327. msg('Invalid comment')
  328. return False
  329. def edit_comment(self):
  330. return self.add_comment(self)
  331. def get_fee_from_tx(self):
  332. return self.sum_inputs() - self.sum_outputs()
  333. def has_segwit_inputs(self):
  334. return any(i.mmid and i.mmid.mmtype in ('S','B') for i in self.inputs)
  335. def compare_size_and_estimated_size(self):
  336. est_vsize = self.estimate_size()
  337. d = g.rpch.decoderawtransaction(self.hex)
  338. vsize = d['vsize'] if 'vsize' in d else d['size']
  339. vmsg('\nSize: {}, Vsize: {} (true) {} (estimated)'.format(d['size'],vsize,est_vsize))
  340. m1 = '\nERROR: Estimated transaction vsize is {:1.2f} times the true vsize\n'
  341. m2 = 'Your transaction fee estimates will be inaccurate\n'
  342. m3 = 'Please re-create and re-sign the transaction using the option --vsize-adj={:1.2f}'
  343. # allow for 5% error
  344. ratio = float(est_vsize) / vsize
  345. if not (0.95 < ratio < 1.05):
  346. die(2,(m1+m2+m3).format(ratio,1/ratio))
  347. # https://bitcoin.stackexchange.com/questions/1195/how-to-calculate-transaction-size-before-sending
  348. # 180: uncompressed, 148: compressed
  349. def estimate_size_old(self):
  350. if not self.inputs or not self.outputs: return None
  351. return len(self.inputs)*180 + len(self.outputs)*34 + 10
  352. # https://bitcoincore.org/en/segwit_wallet_dev/
  353. # vsize: 3 times of the size with original serialization, plus the size with new
  354. # serialization, divide the result by 4 and round up to the next integer.
  355. # TODO: results differ slightly from actual transaction size
  356. def estimate_size(self):
  357. if not self.inputs or not self.outputs: return None
  358. sig_size = 72 # sig in DER format
  359. pubkey_size_uncompressed = 65
  360. pubkey_size_compressed = 33
  361. def get_inputs_size():
  362. # txid vout [scriptSig size (vInt)] scriptSig (<sig> <pubkey>) nSeq
  363. isize_common = 32 + 4 + 1 + 4 # txid vout [scriptSig size] nSeq = 41
  364. input_size = {
  365. 'L': isize_common + sig_size + pubkey_size_uncompressed, # = 180
  366. 'C': isize_common + sig_size + pubkey_size_compressed, # = 148
  367. 'S': isize_common + 23, # = 64
  368. 'B': isize_common + 0 # = 41
  369. }
  370. ret = sum(input_size[i.mmid.mmtype] for i in self.inputs if i.mmid)
  371. # We have no way of knowing whether a non-MMGen addr is compressed or uncompressed until
  372. # we see the key, so assume compressed for fee-estimation purposes. If fee estimate is
  373. # off by more than 5%, sign() aborts and user is instructed to use --vsize-adj option
  374. return ret + sum(input_size['C'] for i in self.inputs if not i.mmid)
  375. def get_outputs_size():
  376. # output bytes = amt: 8, byte_count: 1+, pk_script
  377. # pk_script bytes: p2pkh: 25, p2sh: 23, bech32: 22
  378. return sum({'p2pkh':34,'p2sh':32,'bech32':31}[o.addr.addr_fmt] for o in self.outputs)
  379. # https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
  380. # The witness is a serialization of all witness data of the transaction. Each txin is
  381. # associated with a witness field. A witness field starts with a var_int to indicate the
  382. # number of stack items for the txin. It is followed by stack items, with each item starts
  383. # with a var_int to indicate the length. Witness data is NOT script.
  384. # A non-witness program txin MUST be associated with an empty witness field, represented
  385. # by a 0x00. If all txins are not witness program, a transaction's wtxid is equal to its txid.
  386. def get_witness_size():
  387. if not self.has_segwit_inputs(): return 0
  388. wf_size = 1 + 1 + sig_size + 1 + pubkey_size_compressed # vInt vInt sig vInt pubkey = 108
  389. return sum((1,wf_size)[bool(i.mmid) and i.mmid.mmtype in ('S','B')] for i in self.inputs)
  390. isize = get_inputs_size()
  391. osize = get_outputs_size()
  392. wsize = get_witness_size()
  393. # TODO: compute real varInt sizes instead of assuming 1 byte
  394. # old serialization: [nVersion] [vInt][txins][vInt][txouts] [nLockTime]
  395. old_size = 4 + 1 + isize + 1 + osize + 4
  396. # marker = 0x00, flag = 0x01
  397. # new serialization: [nVersion][marker][flag][vInt][txins][vInt][txouts][witness][nLockTime]
  398. new_size = 4 + 1 + 1 + 1 + isize + 1 + osize + wsize + 4 \
  399. if wsize else old_size
  400. ret = (old_size * 3 + new_size) / 4
  401. dmsg('\nData from estimate_size():')
  402. dmsg(' inputs size: {}, outputs size: {}, witness size: {}'.format(isize,osize,wsize))
  403. dmsg(' size: {}, vsize: {}, old_size: {}'.format(new_size,ret,old_size))
  404. return int(ret * float(opt.vsize_adj)) if hasattr(opt,'vsize_adj') and opt.vsize_adj else ret
  405. # coin-specific fee routines
  406. def get_relay_fee(self):
  407. kb_fee = g.proto.coin_amt(g.rpch.getnetworkinfo()['relayfee'])
  408. ret = kb_fee * self.estimate_size() / 1024
  409. vmsg('Relay fee: {} {c}/kB, for transaction: {} {c}'.format(kb_fee,ret,c=g.coin))
  410. return ret
  411. # convert absolute BTC fee to satoshis-per-byte using estimated size
  412. def fee_abs2rel(self,abs_fee):
  413. return int(abs_fee/g.proto.coin_amt.min_coin_unit/self.estimate_size())
  414. def get_rel_fee_from_network(self): # rel_fee is BTC/kB
  415. try:
  416. ret = g.rpch.estimatesmartfee(opt.tx_confs,on_fail='raise')
  417. rel_fee = ret['feerate'] if 'feerate' in ret else -2
  418. fe_type = 'estimatesmartfee'
  419. except:
  420. rel_fee = g.rpch.estimatefee(opt.tx_confs)
  421. fe_type = 'estimatefee'
  422. return rel_fee,fe_type
  423. # given tx size, rel fee and units, return absolute fee
  424. def convert_fee_spec(self,tx_size,units,amt,unit):
  425. self.usr_rel_fee = None # TODO
  426. return g.proto.coin_amt(int(amt)*tx_size*getattr(g.proto.coin_amt,units[unit])) \
  427. if tx_size else None
  428. # given tx size and absolute fee or fee spec, return absolute fee
  429. # relative fee is N+<first letter of unit name>
  430. def process_fee_spec(self,tx_fee,tx_size,on_fail='throw'):
  431. import re
  432. units = dict((u[0],u) for u in g.proto.coin_amt.units)
  433. pat = r'([1-9][0-9]*)({})'.format('|'.join(units.keys()))
  434. if g.proto.coin_amt(tx_fee,on_fail='silent'):
  435. return g.proto.coin_amt(tx_fee)
  436. elif re.match(pat,tx_fee):
  437. return self.convert_fee_spec(tx_size,units,*re.match(pat,tx_fee).groups())
  438. else:
  439. if on_fail == 'return':
  440. return False
  441. elif on_fail == 'throw':
  442. assert False, "'{}': invalid tx-fee argument".format(tx_fee)
  443. # given network fee estimate in BTC/kB, return absolute fee using estimated tx size
  444. def calculate_fee(self,rel_fee,fe_type=None):
  445. tx_size = self.estimate_size()
  446. ret = g.proto.coin_amt(rel_fee) * opt.tx_fee_adj * tx_size / 1024
  447. if opt.verbose:
  448. msg('{} fee for {} confirmations: {} {}/kB'.format(fe_type.upper(),opt.tx_confs,rel_fee,g.coin))
  449. msg('TX size (estimated): {}'.format(tx_size))
  450. return ret
  451. def convert_and_check_fee(self,tx_fee,desc='Missing description'):
  452. abs_fee = self.process_fee_spec(tx_fee,self.estimate_size(),on_fail='return')
  453. if abs_fee == None:
  454. # we shouldn't be calling this if tx size is unknown
  455. m = "'{}': cannot convert {} to {} because transaction size is unknown"
  456. assert False, m.format(tx_fee,self.rel_fee_desc,g.coin)
  457. elif abs_fee == False:
  458. m = "'{}': invalid TX fee (not a {} amount or {} specification)"
  459. msg(m.format(tx_fee,g.coin,self.rel_fee_desc))
  460. return False
  461. elif abs_fee > g.proto.max_tx_fee:
  462. m = '{} {c}: {} fee too large (maximum fee: {} {c})'
  463. msg(m.format(abs_fee,desc,g.proto.max_tx_fee,c=g.coin))
  464. return False
  465. elif abs_fee < self.get_relay_fee():
  466. m = '{} {c}: {} fee too small (below relay fee of {} {c})'
  467. msg(m.format(str(abs_fee),desc,str(self.get_relay_fee()),c=g.coin))
  468. return False
  469. else:
  470. return abs_fee
  471. # non-coin-specific fee routines
  472. def get_usr_fee_interactive(self,tx_fee=None,desc='Starting'):
  473. abs_fee = None
  474. while True:
  475. if tx_fee:
  476. abs_fee = self.convert_and_check_fee(tx_fee,desc)
  477. if abs_fee:
  478. m = ('',' (after {}x adjustment)'.format(opt.tx_fee_adj))[opt.tx_fee_adj != 1]
  479. p = u'{} TX fee{}: {} {} ({} {})\n'.format(
  480. desc,
  481. m,
  482. abs_fee.hl(),
  483. g.coin,
  484. pink(str(self.fee_abs2rel(abs_fee))),
  485. self.rel_fee_disp)
  486. if opt.yes or keypress_confirm(p+'OK?',default_yes=True):
  487. if opt.yes: msg(p)
  488. return abs_fee
  489. tx_fee = my_raw_input(self.usr_fee_prompt)
  490. desc = 'User-selected'
  491. def get_fee_from_user(self,have_estimate_fail=[]):
  492. if opt.tx_fee:
  493. desc = 'User-selected'
  494. start_fee = opt.tx_fee
  495. else:
  496. desc = 'Network-estimated'
  497. rel_fee,fe_type = self.get_rel_fee_from_network()
  498. if rel_fee < 0:
  499. if not have_estimate_fail:
  500. msg(self.fee_fail_fs.format(c=opt.tx_confs,t=fe_type))
  501. have_estimate_fail.append(True)
  502. start_fee = None
  503. else:
  504. start_fee = self.calculate_fee(rel_fee,fe_type)
  505. return self.get_usr_fee_interactive(start_fee,desc=desc)
  506. def delete_attrs(self,desc,attr):
  507. for e in getattr(self,desc):
  508. if hasattr(e,attr): delattr(e,attr)
  509. def decode_io_oldfmt(self,data):
  510. tr = {'amount':'amt', 'address':'addr', 'confirmations':'confs','comment':'label'}
  511. tr_rev = dict(map(reversed,tr.items()))
  512. copy_keys = [tr_rev[k] if k in tr_rev else k for k in self.MMGenTxInput.__dict__]
  513. ret = MMGenList(self.MMGenTxInput(**dict([(tr[k] if k in tr else k,d[k])
  514. for k in copy_keys if k in d and d[k] != ''])) for d in data)
  515. for i in ret: i.sequence = int('0xffffffff',16)
  516. return ret
  517. # inputs methods
  518. def copy_inputs_from_tw(self,tw_unspent_data):
  519. txi,self.inputs = self.MMGenTxInput,self.MMGenTxInputList()
  520. for d in tw_unspent_data:
  521. t = txi(**dict([(attr,getattr(d,attr)) for attr in d.__dict__ if attr in txi.__dict__]))
  522. if d.twmmid.type == 'mmgen': t.mmid = d.twmmid # twmmid -> mmid
  523. self.inputs.append(t)
  524. def get_input_sids(self):
  525. return set(e.mmid.sid for e in self.inputs if e.mmid)
  526. def get_output_sids(self):
  527. return set(e.mmid.sid for e in self.outputs if e.mmid)
  528. def sum_inputs(self):
  529. return sum(e.amt for e in self.inputs)
  530. def add_timestamp(self):
  531. self.timestamp = make_timestamp()
  532. def get_hex_locktime(self):
  533. return int(hexlify(unhexlify(self.hex[-8:])[::-1]),16)
  534. def set_hex_locktime(self,val):
  535. assert type(val) == int,'locktime value not an integer'
  536. self.hex = self.hex[:-8] + hexlify(unhexlify('{:08x}'.format(val))[::-1])
  537. def get_blockcount(self):
  538. return int(g.rpch.getblockcount())
  539. def add_blockcount(self):
  540. self.blockcount = self.get_blockcount()
  541. def format(self):
  542. self.inputs.check_coin_mismatch()
  543. self.outputs.check_coin_mismatch()
  544. def amt_to_str(d):
  545. return dict([(k,str(d[k]) if k == 'amt' else d[k]) for k in d])
  546. lines = [
  547. '{}{} {} {} {} {}{}'.format(
  548. (g.coin+' ','')[g.coin=='BTC'],
  549. self.chain.upper() if self.chain else 'Unknown',
  550. self.txid,
  551. self.send_amt,
  552. self.timestamp,
  553. self.blockcount,
  554. ('',' LT={}'.format(self.locktime))[bool(self.locktime)]
  555. ),
  556. self.hex,
  557. repr([amt_to_str(e.__dict__) for e in self.inputs]),
  558. repr([amt_to_str(e.__dict__) for e in self.outputs])
  559. ]
  560. if self.label:
  561. lines.append(baseconv.b58encode(self.label.encode('utf8')))
  562. if self.coin_txid:
  563. if not self.label: lines.append('-') # keep old tx files backwards compatible
  564. lines.append(self.coin_txid)
  565. self.chksum = make_chksum_6(' '.join(lines))
  566. self.fmt_data = '\n'.join([self.chksum] + lines)+'\n'
  567. assert len(self.fmt_data) <= g.max_tx_file_size,(
  568. 'Transaction file size exceeds limit ({} bytes)'.format(g.max_tx_file_size))
  569. def get_non_mmaddrs(self,desc):
  570. return list(set(i.addr for i in getattr(self,desc) if not i.mmid))
  571. # return true or false; don't exit
  572. def sign(self,tx_num_str,keys):
  573. if self.marked_signed():
  574. msg('Transaction is already signed!')
  575. return False
  576. if not self.check_correct_chain(on_fail='return'):
  577. return False
  578. if (self.has_segwit_inputs() or self.has_segwit_outputs()) and not g.proto.cap('segwit'):
  579. ymsg("TX has Segwit inputs or outputs, but {} doesn't support Segwit!".format(g.coin))
  580. return False
  581. qmsg('Passing {} key{} to {}'.format(len(keys),suf(keys,'s'),g.proto.daemon_name))
  582. if self.has_segwit_inputs():
  583. from mmgen.addr import KeyGenerator,AddrGenerator
  584. kg = KeyGenerator('std')
  585. ag = AddrGenerator('segwit')
  586. keydict = MMGenDict([(d.addr,d.sec) for d in keys])
  587. sig_data = []
  588. for d in self.inputs:
  589. e = dict([(k,getattr(d,k)) for k in ('txid','vout','scriptPubKey','amt')])
  590. e['amount'] = e['amt']
  591. del e['amt']
  592. if d.mmid and d.mmid.mmtype == 'S':
  593. e['redeemScript'] = ag.to_segwit_redeem_script(kg.to_pubhex(keydict[d.addr]))
  594. sig_data.append(e)
  595. msg_r('Signing transaction{}...'.format(tx_num_str))
  596. wifs = [d.sec.wif for d in keys]
  597. ret = g.rpch.signrawtransaction(self.hex,sig_data,wifs,g.proto.sighash_type,on_fail='return')
  598. from mmgen.rpc import rpc_error,rpc_errmsg
  599. if rpc_error(ret):
  600. errmsg = rpc_errmsg(ret)
  601. if 'Invalid sighash param' in errmsg:
  602. m = 'This is not the BCH chain.'
  603. m += "\nRe-run the script without the --coin=bch option."
  604. else:
  605. m = errmsg
  606. msg(yellow(m))
  607. return False
  608. else:
  609. if ret['complete']:
  610. # Msg(pretty_hexdump(unhexlify(self.hex),cols=16)) # DEBUG
  611. # pmsg(make_chksum_6(unhexlify(self.hex)).upper())
  612. self.hex = ret['hex']
  613. self.compare_size_and_estimated_size()
  614. dt = DeserializedTX(self.hex)
  615. self.check_hex_tx_matches_mmgen_tx(dt)
  616. self.coin_txid = CoinTxID(dt['txid'],on_fail='return')
  617. self.check_sigs(dt)
  618. assert self.coin_txid == g.rpch.decoderawtransaction(self.hex)['txid'],(
  619. 'txid mismatch (after signing)')
  620. msg('OK')
  621. return True
  622. else:
  623. msg('failed\n{} returned the following errors:'.format(g.proto.daemon_name.capitalize()))
  624. msg(repr(ret['errors']))
  625. return False
  626. def mark_raw(self):
  627. self.desc = 'transaction'
  628. self.ext = self.raw_ext
  629. def mark_signed(self): # called ONLY by check_sigs()
  630. self.desc = 'signed transaction'
  631. self.ext = self.sig_ext
  632. def marked_signed(self,color=False):
  633. ret = self.desc == 'signed transaction'
  634. return (red,green)[ret](str(ret)) if color else ret
  635. # check that a malicious, compromised or malfunctioning coin daemon hasn't altered hex tx data:
  636. # does not check witness or signature data
  637. def check_hex_tx_matches_mmgen_tx(self,deserial_tx):
  638. m = 'Fatal error: a malicious or malfunctioning coin daemon or other program may have altered your data!'
  639. lt = deserial_tx['lock_time']
  640. if lt != int(self.locktime or 0):
  641. m2 = '\nTransaction hex locktime ({}) does not match MMGen transaction locktime ({})\n{}'
  642. rdie(3,m2.format(lt,self.locktime,m))
  643. def check_equal(desc,hexio,mmio):
  644. if mmio != hexio:
  645. msg('\nMMGen {}:\n{}'.format(desc,pformat(mmio)))
  646. msg('Hex {}:\n{}'.format(desc,pformat(hexio)))
  647. m2 = '{} in hex transaction data from coin daemon do not match those in MMGen transaction!\n'
  648. rdie(3,(m2+m).format(desc.capitalize()))
  649. seq_hex = map(lambda i: int(i['nSeq'],16),deserial_tx['txins'])
  650. seq_mmgen = map(lambda i: i.sequence or g.max_int,self.inputs)
  651. check_equal('sequence numbers',seq_hex,seq_mmgen)
  652. d_hex = sorted((i['txid'],i['vout']) for i in deserial_tx['txins'])
  653. d_mmgen = sorted((i.txid,i.vout) for i in self.inputs)
  654. check_equal('inputs',d_hex,d_mmgen)
  655. d_hex = sorted((o['address'],g.proto.coin_amt(o['amount'])) for o in deserial_tx['txouts'])
  656. d_mmgen = sorted((o.addr,o.amt) for o in self.outputs)
  657. check_equal('outputs',d_hex,d_mmgen)
  658. uh = deserial_tx['unsigned_hex']
  659. if str(self.txid) != make_chksum_6(unhexlify(uh)).upper():
  660. rdie(3,'MMGen TxID ({}) does not match hex transaction data!\n{}'.format(self.txid,m))
  661. # check signature and witness data
  662. def check_sigs(self,deserial_tx=None): # return False if no sigs, die on error
  663. txins = (deserial_tx or DeserializedTX(self.hex))['txins']
  664. has_ss = any(ti['scriptSig'] for ti in txins)
  665. has_witness = any('witness' in ti and ti['witness'] for ti in txins)
  666. if not (has_ss or has_witness):
  667. return False
  668. fs = "Hex TX has {} scriptSig but input is of type '{}'!"
  669. for n in range(len(txins)):
  670. ti,mmti = txins[n],self.inputs[n]
  671. if ti['scriptSig'] == '' or ( len(ti['scriptSig']) == 46 and # native P2WPKH or P2SH-P2WPKH
  672. ti['scriptSig'][:6] == '16' + g.proto.witness_vernum_hex + '14' ):
  673. assert 'witness' in ti, 'missing witness'
  674. assert type(ti['witness']) == list and len(ti['witness']) == 2, 'malformed witness'
  675. assert len(ti['witness'][1]) == 66, 'incorrect witness pubkey length'
  676. assert mmti.mmid, fs.format('witness-type','non-MMGen')
  677. assert mmti.mmid.mmtype == ('S','B')[ti['scriptSig']==''],fs.format('witness-type',mmti.mmid.mmtype)
  678. else: # non-witness
  679. if mmti.mmid:
  680. assert mmti.mmid.mmtype not in ('S','B'), fs.format('signature in',mmti.mmid.mmtype)
  681. assert not 'witness' in ti, 'non-witness input has witness'
  682. # sig_size 72 (DER format), pubkey_size 'compressed':33, 'uncompressed':65
  683. assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
  684. self.mark_signed()
  685. return True
  686. def has_segwit_outputs(self):
  687. return any(o.mmid and o.mmid.mmtype in ('S','B') for o in self.outputs)
  688. def is_in_mempool(self):
  689. return 'size' in g.rpch.getmempoolentry(self.coin_txid,on_fail='silent')
  690. def is_in_wallet(self):
  691. ret = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  692. if 'confirmations' in ret and ret['confirmations'] > 0:
  693. return ret['confirmations']
  694. else:
  695. return False
  696. def is_replaced(self):
  697. if self.is_in_mempool(): return False
  698. ret = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  699. if not 'bip125-replaceable' in ret or not 'confirmations' in ret or ret['confirmations'] > 0:
  700. return False
  701. return -ret['confirmations'] + 1,ret # 1: replacement in mempool, 2: replacement confirmed
  702. def is_in_utxos(self):
  703. return 'txid' in g.rpch.getrawtransaction(self.coin_txid,True,on_fail='silent')
  704. def get_status(self,status=False):
  705. if self.is_in_mempool():
  706. if status:
  707. d = g.rpch.gettransaction(self.coin_txid,on_fail='silent')
  708. brs = 'bip125-replaceable'
  709. r = '{}replaceable'.format(('NOT ','')[brs in d and d[brs]=='yes'])
  710. t = d['timereceived']
  711. m = 'Sent {} ({} h/m/s ago)'
  712. b = m.format(time.strftime('%c',time.gmtime(t)),secs_to_dhms(int(time.time()-t)))
  713. if opt.quiet:
  714. msg('Transaction is in mempool')
  715. else:
  716. msg('TX status: in mempool, {}\n{}'.format(r,b))
  717. else:
  718. msg('Warning: transaction is in mempool!')
  719. elif self.is_in_wallet():
  720. confs = self.is_in_wallet()
  721. die(0,'Transaction has {} confirmation{}'.format(confs,suf(confs,'s')))
  722. elif self.is_in_utxos():
  723. die(2,red('ERROR: transaction is in the blockchain (but not in the tracking wallet)!'))
  724. else:
  725. ret = self.is_replaced() # ret[0]==1: replacement in mempool, ret[0]==2: replacement confirmed
  726. if ret and ret[0]:
  727. m1 = 'Transaction has been replaced'
  728. m2 = ('',', and the replacement TX is confirmed')[ret[0]==2]
  729. msg('{}{}!'.format(m1,m2))
  730. if not opt.quiet:
  731. msg('Replacing transactions:')
  732. rt = ret[1]['walletconflicts']
  733. for t,s in [(tx,'size' in g.rpch.getmempoolentry(tx,on_fail='silent')) for tx in rt]:
  734. msg(' {}{}'.format(t,('',' in mempool')[s]))
  735. die(0,'')
  736. def send(self,prompt_user=True,exit_on_fail=False):
  737. if not self.marked_signed():
  738. die(1,'Transaction is not signed!')
  739. self.check_correct_chain(on_fail='die')
  740. self.check_hex_tx_matches_mmgen_tx(DeserializedTX(self.hex))
  741. bogus_send = os.getenv('MMGEN_BOGUS_SEND')
  742. if self.has_segwit_outputs() and not segwit_is_active() and not bogus_send:
  743. m = 'Transaction has MMGen Segwit outputs, but this blockchain does not support Segwit'
  744. die(2,m+' at the current height')
  745. if self.get_fee_from_tx() > g.proto.max_tx_fee:
  746. die(2,'Transaction fee ({}) greater than {} max_tx_fee ({} {})!'.format(
  747. self.get_fee_from_tx(),g.proto.name.capitalize(),g.proto.max_tx_fee,g.coin.upper()))
  748. self.get_status()
  749. if prompt_user:
  750. m1 = ("Once this transaction is sent, there's no taking it back!",'')[bool(opt.quiet)]
  751. m2 = 'broadcast this transaction to the {} network'.format(g.chain.upper())
  752. m3 = ('YES, I REALLY WANT TO DO THIS','YES')[bool(opt.quiet or opt.yes)]
  753. confirm_or_exit(m1,m2,m3)
  754. msg('Sending transaction')
  755. ret = None if bogus_send else g.rpch.sendrawtransaction(self.hex,on_fail='return')
  756. from mmgen.rpc import rpc_error,rpc_errmsg
  757. if rpc_error(ret):
  758. errmsg = rpc_errmsg(ret)
  759. if 'Signature must use SIGHASH_FORKID' in errmsg:
  760. m = 'The Aug. 1 2017 UAHF has activated on this chain.'
  761. m += "\nRe-run the script with the --coin=bch option."
  762. elif 'Illegal use of SIGHASH_FORKID' in errmsg:
  763. m = 'The Aug. 1 2017 UAHF is not yet active on this chain.'
  764. m += "\nRe-run the script without the --coin=bch option."
  765. elif '64: non-final' in errmsg:
  766. m2 = "Transaction with locktime '{}' can't be included in this block!"
  767. m = m2.format(strfmt_locktime(self.get_hex_locktime()))
  768. else:
  769. m = errmsg
  770. msg(yellow(m))
  771. msg(red('Send of MMGen transaction {} failed'.format(self.txid)))
  772. if exit_on_fail: sys.exit(1)
  773. return False
  774. else:
  775. if bogus_send:
  776. m = 'BOGUS transaction NOT sent: {}'
  777. else:
  778. assert ret == self.coin_txid, 'txid mismatch (after sending)'
  779. m = 'Transaction sent: {}'
  780. self.desc = 'sent transaction'
  781. msg(m.format(self.coin_txid.hl()))
  782. self.add_timestamp()
  783. self.add_blockcount()
  784. return True
  785. def write_txid_to_file(self,ask_write=False,ask_write_default_yes=True):
  786. fn = '{}[{}].{}'.format(self.txid,self.send_amt,self.txid_ext)
  787. write_data_to_file(fn,self.coin_txid+'\n','transaction ID',
  788. ask_write=ask_write,
  789. ask_write_default_yes=ask_write_default_yes)
  790. def create_fn(self):
  791. tl = self.get_hex_locktime()
  792. self.fn = u'{}{}[{!s}{}{}]{x}.{}'.format(
  793. self.txid,
  794. ('-'+g.coin,'')[g.coin=='BTC'],
  795. self.send_amt,
  796. ('',',{}'.format(self.fee_abs2rel(self.get_fee_from_tx())))[self.is_rbf()],
  797. ('',',tl={}'.format(tl))[bool(tl)],
  798. self.ext,
  799. x=u'-α' if g.debug_utf8 else '')
  800. def write_to_file( self,
  801. add_desc='',
  802. ask_write=True,
  803. ask_write_default_yes=False,
  804. ask_tty=True,
  805. ask_overwrite=True):
  806. if ask_write == False: ask_write_default_yes = True
  807. if not self.fmt_data: self.format()
  808. if not self.fn: self.create_fn()
  809. write_data_to_file(self.fn,self.fmt_data,self.desc+add_desc,
  810. ask_overwrite=ask_overwrite,
  811. ask_write=ask_write,
  812. ask_tty=ask_tty,
  813. ask_write_default_yes=ask_write_default_yes)
  814. def view_with_prompt(self,prompt=''):
  815. prompt += ' (y)es, (N)o, pager (v)iew, (t)erse view'
  816. reply = prompt_and_get_char(prompt,'YyNnVvTt',enter_ok=True)
  817. if reply and reply in 'YyVvTt':
  818. self.view(pager=reply in 'Vv',terse=reply in 'Tt')
  819. def view(self,pager=False,pause=True,terse=False):
  820. o = self.format_view(terse=terse)
  821. if pager: do_pager(o)
  822. else:
  823. msg_r(o)
  824. from mmgen.term import get_char
  825. if pause:
  826. get_char('Press any key to continue: ')
  827. msg('')
  828. # def is_rbf_from_rpc(self):
  829. # dec_tx = g.rpch.decoderawtransaction(self.hex)
  830. # return None < dec_tx['vin'][0]['sequence'] <= g.max_int - 2
  831. def is_rbf(self):
  832. return self.inputs[0].sequence == g.max_int - 2
  833. def format_view_body(self,blockcount,nonmm_str,max_mmwid,enl,terse):
  834. def format_io(desc):
  835. io = getattr(self,desc)
  836. ip = desc == 'inputs'
  837. out = desc.capitalize() + ':\n' + enl
  838. addr_w = max(len(e.addr) for e in io)
  839. confs_per_day = 60*60*24 / g.proto.secs_per_block
  840. for n,e in enumerate(sorted(io,key=lambda o: o.mmid.sort_key if o.mmid else o.addr)):
  841. if ip and blockcount:
  842. confs = e.confs + blockcount - self.blockcount
  843. days = int(confs / confs_per_day)
  844. if e.mmid:
  845. mmid_fmt = e.mmid.fmt(
  846. width=max_mmwid,
  847. encl='()',
  848. color=True,
  849. append_chars=('',' (chg)')[bool(not ip and e.is_chg and terse)],
  850. append_color='green')
  851. else:
  852. mmid_fmt = MMGenID.fmtc(nonmm_str,width=max_mmwid,color=True)
  853. if terse:
  854. out += '{:3} {} {} {} {}\n'.format(n+1,
  855. e.addr.fmt(color=True,width=addr_w),
  856. mmid_fmt,e.amt.hl(),g.coin)
  857. else:
  858. icommon = [
  859. ((n+1,'')[ip],'address:',e.addr.fmt(color=True,width=addr_w) + ' '+mmid_fmt),
  860. ('','comment:',e.label.hl() if e.label else ''),
  861. ('','amount:','{} {}'.format(e.amt.hl(),g.coin))]
  862. items = [(n+1, 'tx,vout:','{},{}'.format(e.txid,e.vout))] + icommon + [
  863. ('','confirmations:','{} (around {} days)'.format(confs,days) if blockcount else '')
  864. ] if ip else icommon + [
  865. ('','change:',green('True') if e.is_chg else '')]
  866. out += '\n'.join([(u'{:>3} {:<8} {}'.format(*d)) for d in items if d[2]]) + '\n\n'
  867. return out
  868. return format_io('inputs') + format_io('outputs')
  869. def format_view_rel_fee(self,terse):
  870. return ' ({} {})\n'.format(
  871. pink(str(self.fee_abs2rel(self.get_fee_from_tx()))),
  872. self.rel_fee_disp)
  873. def format_view_abs_fee(self):
  874. return g.proto.coin_amt(self.get_fee_from_tx()).hl()
  875. def format_view_verbose_footer(self):
  876. ts = len(self.hex)/2 if self.hex else 'unknown'
  877. out = 'Transaction size: Vsize {} (estimated), Total {}'.format(self.estimate_size(),ts)
  878. if self.marked_signed():
  879. ws = DeserializedTX(self.hex)['witness_size']
  880. out += ', Base {}, Witness {}'.format(ts-ws,ws)
  881. return out + '\n'
  882. def format_view(self,terse=False):
  883. try:
  884. rpc_init()
  885. blockcount = self.get_blockcount()
  886. except:
  887. blockcount = None
  888. def get_max_mmwid(io):
  889. if io == self.inputs:
  890. sel_f = lambda o: len(o.mmid) + 2 # len('()')
  891. else:
  892. sel_f = lambda o: len(o.mmid) + (2,8)[bool(o.is_chg)] # + len(' (chg)')
  893. return max(max([sel_f(o) for o in io if o.mmid] or [0]),len(nonmm_str))
  894. nonmm_str = '(non-{pnm} address)'.format(pnm=g.proj_name)
  895. max_mmwid = max(get_max_mmwid(self.inputs),get_max_mmwid(self.outputs))
  896. out = (self.txview_hdr_fs,self.txview_hdr_fs_short)[bool(terse)].format(
  897. i=self.txid.hl(),
  898. a=self.send_amt.hl(),
  899. c=g.coin,
  900. t=self.timestamp,
  901. r=(red('False'),green('True'))[self.is_rbf()],
  902. s=self.marked_signed(color=True),
  903. l=(green('None'),orange(strfmt_locktime(self.locktime,terse=True)))[bool(self.locktime)])
  904. if self.chain != 'mainnet':
  905. out += green('Chain: {}\n'.format(self.chain.upper()))
  906. if self.coin_txid:
  907. out += '{} TxID: {}\n'.format(g.coin,self.coin_txid.hl())
  908. enl = ('\n','')[bool(terse)]
  909. out += enl
  910. if self.label:
  911. out += u'Comment: {}\n{}'.format(self.label.hl(),enl)
  912. out += self.format_view_body(blockcount,nonmm_str,max_mmwid,enl,terse=terse)
  913. fs = (
  914. 'Total input: {i} {c}\nTotal output: {o} {c}\nTX fee: {a} {c}{r}\n',
  915. 'In {i} {c} - Out {o} {c}\nFee {a} {c}{r}\n'
  916. )[bool(terse)]
  917. out += fs.format(
  918. i=self.sum_inputs().hl(),
  919. o=self.sum_outputs().hl(),
  920. a=self.format_view_abs_fee(),
  921. r=self.format_view_rel_fee(terse),
  922. c=g.coin)
  923. if opt.verbose: out += self.format_view_verbose_footer()
  924. return out # TX label might contain non-ascii chars
  925. def check_tx_hex_data(self):
  926. self.hex = HexStr(self.hex,on_fail='raise')
  927. def parse_tx_file(self,infile,md_only=False,silent_open=False):
  928. def eval_io_data(raw_data,desc):
  929. from ast import literal_eval
  930. try:
  931. d = literal_eval(raw_data)
  932. except:
  933. if desc == 'inputs' and not silent_open:
  934. ymsg('Warning: transaction data appears to be in old format')
  935. import re
  936. d = literal_eval(re.sub(r"[A-Za-z]+?\(('.+?')\)",r'\1',raw_data))
  937. assert type(d) == list,'{} data not a list!'.format(desc)
  938. assert len(d),'no {}!'.format(desc)
  939. for e in d: e['amt'] = g.proto.coin_amt(e['amt'])
  940. io,io_list = (
  941. (MMGenTX.MMGenTxOutput,MMGenTX.MMGenTxOutputList),
  942. (MMGenTX.MMGenTxInput,MMGenTX.MMGenTxInputList)
  943. )[desc=='inputs']
  944. return io_list([io(**e) for e in d])
  945. tx_data = get_data_from_file(infile,self.desc+' data',silent=silent_open)
  946. try:
  947. desc = 'data'
  948. assert len(tx_data) <= g.max_tx_file_size,(
  949. 'Transaction file size exceeds limit ({} bytes)'.format(g.max_tx_file_size))
  950. tx_data = tx_data.decode('ascii').splitlines()
  951. assert len(tx_data) >= 5,'number of lines less than 5'
  952. assert len(tx_data[0]) == 6,'invalid length of first line'
  953. self.chksum = HexStr(tx_data.pop(0),on_fail='raise')
  954. assert self.chksum == make_chksum_6(' '.join(tx_data)),'file data does not match checksum'
  955. if len(tx_data) == 6:
  956. assert len(tx_data[-1]) == 64,'invalid coin TxID length'
  957. desc = '{} TxID'.format(g.proto.name.capitalize())
  958. self.coin_txid = CoinTxID(tx_data.pop(-1),on_fail='raise')
  959. if len(tx_data) == 5:
  960. # rough check: allow for 4-byte utf8 characters + base58 (4 * 11 / 8 = 6 (rounded up))
  961. assert len(tx_data[-1]) < MMGenTXLabel.max_len*6,'invalid comment length'
  962. c = tx_data.pop(-1)
  963. if c != '-':
  964. desc = 'encoded comment (not base58)'
  965. comment = baseconv.b58decode(c).decode('utf8')
  966. assert comment != False,'invalid comment'
  967. desc = 'comment'
  968. self.label = MMGenTXLabel(comment,on_fail='raise')
  969. desc = 'number of lines' # four required lines
  970. metadata,self.hex,inputs_data,outputs_data = tx_data
  971. assert len(metadata) < 60,'invalid metadata length' # rough check
  972. metadata = metadata.split()
  973. if metadata[-1].find('LT=') == 0:
  974. desc = 'locktime'
  975. self.locktime = int(metadata.pop()[3:])
  976. self.coin = metadata.pop(0) if len(metadata) == 6 else 'BTC'
  977. if len(metadata) == 5:
  978. t = metadata.pop(0)
  979. self.chain = (t.lower(),None)[t=='Unknown']
  980. desc = 'metadata (4 items minimum required)'
  981. self.txid,send_amt,self.timestamp,blockcount = metadata
  982. desc = 'metadata'
  983. self.txid = MMGenTxID(self.txid,on_fail='raise')
  984. self.send_amt = g.proto.coin_amt(send_amt,on_fail='raise')
  985. desc = 'block count in metadata'
  986. self.blockcount = int(blockcount)
  987. desc = 'transaction hex data'
  988. self.check_tx_hex_data()
  989. if md_only: return # the following ops will all fail if g.coin doesn't match self.coin
  990. desc = 'coin type in metadata'
  991. assert self.coin == g.coin,'invalid coin type'
  992. desc = 'inputs data'
  993. self.inputs = eval_io_data(inputs_data,'inputs')
  994. desc = 'outputs data'
  995. self.outputs = eval_io_data(outputs_data,'outputs')
  996. except Exception as e:
  997. die(2,'Invalid {} in transaction file: {}'.format(desc,e[0]))
  998. if not self.chain and not self.inputs[0].addr.is_for_chain('testnet'):
  999. self.chain = 'mainnet'
  1000. def process_cmd_args(self,cmd_args,ad_f,ad_w):
  1001. for a in cmd_args:
  1002. if ',' in a:
  1003. a1,a2 = a.split(',',1)
  1004. if is_mmgen_id(a1) or is_coin_addr(a1):
  1005. coin_addr = mmaddr2coinaddr(a1,ad_w,ad_f) if is_mmgen_id(a1) else CoinAddr(a1)
  1006. self.add_output(coin_addr,g.proto.coin_amt(a2))
  1007. else:
  1008. die(2,"{}: invalid subargument in command-line argument '{}'".format(a1,a))
  1009. elif is_mmgen_id(a) or is_coin_addr(a):
  1010. if self.get_chg_output_idx() != None:
  1011. die(2,'ERROR: More than one change address listed on command line')
  1012. coin_addr = mmaddr2coinaddr(a,ad_w,ad_f) if is_mmgen_id(a) else CoinAddr(a)
  1013. self.add_output(coin_addr,g.proto.coin_amt('0'),is_chg=True)
  1014. else:
  1015. die(2,'{}: invalid command-line argument'.format(a))
  1016. if self.get_chg_output_idx() == None:
  1017. die(2,('ERROR: No change output specified',wmsg['no_change_output'])[len(self.outputs) == 1])
  1018. if not segwit_is_active() and self.has_segwit_outputs():
  1019. fs = '{} Segwit address requested on the command line, but Segwit is not active on this chain'
  1020. rdie(2,fs.format(g.proj_name))
  1021. def get_outputs_from_cmdline(self,cmd_args):
  1022. from mmgen.addr import AddrList,AddrData
  1023. addrfiles = [a for a in cmd_args if get_extension(a) == AddrList.ext]
  1024. cmd_args = set(cmd_args) - set(addrfiles)
  1025. ad_f = AddrData()
  1026. for a in addrfiles:
  1027. check_infile(a)
  1028. ad_f.add(AddrList(a))
  1029. ad_w = AddrData(source='tw')
  1030. self.process_cmd_args(cmd_args,ad_f,ad_w)
  1031. if not self.outputs:
  1032. die(2,'At least one output must be specified on the command line')
  1033. self.add_mmaddrs_to_outputs(ad_w,ad_f)
  1034. self.check_dup_addrs('outputs')
  1035. def select_unspent(self,unspent):
  1036. prompt = 'Enter a range or space-separated list of outputs to spend: '
  1037. while True:
  1038. reply = my_raw_input(prompt).strip()
  1039. if reply:
  1040. selected = AddrIdxList(fmt_str=','.join(reply.split()),on_fail='return')
  1041. if selected:
  1042. if selected[-1] <= len(unspent):
  1043. return selected
  1044. msg('Unspent output number must be <= {}'.format(len(unspent)))
  1045. def get_inputs_from_user(self,tw):
  1046. while True:
  1047. sel_nums = self.select_unspent(tw.unspent)
  1048. msg('Selected output{}: {}'.format(suf(sel_nums,'s'),' '.join(map(str,sel_nums))))
  1049. sel_unspent = tw.MMGenTwOutputList([tw.unspent[i-1] for i in sel_nums])
  1050. t_inputs = sum(s.amt for s in sel_unspent)
  1051. if t_inputs < self.send_amt:
  1052. msg(wmsg['not_enough_coin'].format(self.send_amt-t_inputs))
  1053. continue
  1054. non_mmaddrs = [i for i in sel_unspent if i.twmmid.type == 'non-mmgen']
  1055. if non_mmaddrs and self.caller != 'txdo':
  1056. msg(wmsg['non_mmgen_inputs'].format(', '.join(set(sorted([a.addr.hl() for a in non_mmaddrs])))))
  1057. if not keypress_confirm('Accept?'):
  1058. continue
  1059. self.copy_inputs_from_tw(sel_unspent) # makes self.inputs
  1060. self.fee = self.get_fee_from_user()
  1061. change_amt = self.sum_inputs() - self.send_amt - self.fee
  1062. if change_amt >= 0:
  1063. p = self.chg_msg_fs.format(change_amt.hl(),g.coin)
  1064. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1065. if opt.yes: msg(p)
  1066. return change_amt
  1067. else:
  1068. msg(wmsg['not_enough_coin'].format(abs(change_amt)))
  1069. def check_fee(self):
  1070. assert self.sum_inputs() - self.sum_outputs() <= g.proto.max_tx_fee
  1071. def create(self,cmd_args,locktime,do_info=False):
  1072. assert type(locktime) == int
  1073. if opt.comment_file: self.add_comment(opt.comment_file)
  1074. if not do_info: self.get_outputs_from_cmdline(cmd_args)
  1075. do_license_msg()
  1076. from mmgen.tw import TwUnspentOutputs
  1077. tw = TwUnspentOutputs(minconf=opt.minconf)
  1078. tw.view_and_sort(self)
  1079. tw.display_total()
  1080. if do_info: sys.exit(0)
  1081. self.send_amt = self.sum_outputs()
  1082. msg('Total amount to spend: {}'.format(
  1083. ('Unknown','{} {}'.format(self.send_amt.hl(),g.coin))[bool(self.send_amt)]
  1084. ))
  1085. change_amt = self.get_inputs_from_user(tw)
  1086. # only after we have inputs
  1087. if locktime: self.inputs[0].sequence = g.max_int - 1
  1088. if opt.rbf: self.inputs[0].sequence = g.max_int - 2
  1089. chg_idx = self.get_chg_output_idx()
  1090. if change_amt == 0:
  1091. msg(self.no_chg_msg)
  1092. self.del_output(chg_idx)
  1093. else:
  1094. self.update_output_amt(chg_idx,g.proto.coin_amt(change_amt))
  1095. if not self.send_amt:
  1096. self.send_amt = change_amt
  1097. if not opt.yes:
  1098. self.add_comment() # edits an existing comment
  1099. self.create_raw() # creates self.hex, self.txid
  1100. if locktime:
  1101. msg('Setting nlocktime to {}!'.format(strfmt_locktime(locktime)))
  1102. self.set_hex_locktime(locktime)
  1103. self.update_txid()
  1104. self.locktime = locktime
  1105. self.add_timestamp()
  1106. self.add_blockcount()
  1107. self.chain = g.chain
  1108. self.check_fee()
  1109. qmsg('Transaction successfully created')
  1110. if not opt.yes:
  1111. self.view_with_prompt('View decoded transaction?')
  1112. class MMGenBumpTX(MMGenTX):
  1113. min_fee = None
  1114. bump_output_idx = None
  1115. def __init__(self,filename,send=False):
  1116. super(type(self),self).__init__(filename)
  1117. if not self.is_rbf():
  1118. die(1,"Transaction '{}' is not replaceable (RBF)".format(self.txid))
  1119. # If sending, require tx to have been signed
  1120. if send:
  1121. if not self.marked_signed():
  1122. die(1,"File '{}' is not a signed {} transaction file".format(filename,g.proj_name))
  1123. if not self.coin_txid:
  1124. die(1,"Transaction '{}' was not broadcast to the network".format(self.txid,g.proj_name))
  1125. self.coin_txid = ''
  1126. self.mark_raw()
  1127. def choose_output(self):
  1128. chg_idx = self.get_chg_output_idx()
  1129. init_reply = opt.output_to_reduce
  1130. while True:
  1131. if init_reply == None:
  1132. m = 'Choose an output to deduct the fee from (Hit ENTER for the change output): '
  1133. reply = my_raw_input(m) or 'c'
  1134. else:
  1135. reply,init_reply = init_reply,None
  1136. if chg_idx == None and not is_int(reply):
  1137. msg("Output must be an integer")
  1138. elif chg_idx != None and not is_int(reply) and reply != 'c':
  1139. msg("Output must be an integer, or 'c' for the change output")
  1140. else:
  1141. idx = chg_idx if reply == 'c' else (int(reply) - 1)
  1142. if idx < 0 or idx >= len(self.outputs):
  1143. msg('Output must be in the range 1-{}'.format(len(self.outputs)))
  1144. else:
  1145. o_amt = self.outputs[idx].amt
  1146. cs = ('',' (change output)')[chg_idx == idx]
  1147. p = 'Fee will be deducted from output {}{} ({} {})'.format(idx+1,cs,o_amt,g.coin)
  1148. if o_amt < self.min_fee:
  1149. msg('Minimum fee ({} {c}) is greater than output amount ({} {c})'.format(
  1150. self.min_fee,o_amt,c=g.coin))
  1151. elif opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1152. if opt.yes: msg(p)
  1153. self.bump_output_idx = idx
  1154. return idx
  1155. def set_min_fee(self):
  1156. self.min_fee = self.sum_inputs() - self.sum_outputs() + self.get_relay_fee()
  1157. def convert_and_check_fee(self,tx_fee,desc):
  1158. ret = super(type(self),self).convert_and_check_fee(tx_fee,desc)
  1159. if ret < self.min_fee:
  1160. msg('{} {c}: {} fee too small. Minimum fee: {} {c} ({} {})'.format(
  1161. ret,desc,self.min_fee,self.fee_abs2rel(self.min_fee),self.rel_fee_desc,c=g.coin))
  1162. return False
  1163. output_amt = self.outputs[self.bump_output_idx].amt
  1164. if ret >= output_amt:
  1165. msg('{} {c}: {} fee too large. Maximum fee: <{} {c}'.format(ret,desc,output_amt,c=g.coin))
  1166. return False
  1167. return ret
  1168. class MMGenSplitTX(MMGenTX):
  1169. def get_outputs_from_cmdline(self,mmid): # TODO: check that addr is empty
  1170. from mmgen.addr import AddrData
  1171. ad_w = AddrData(source='tw')
  1172. if is_mmgen_id(mmid):
  1173. coin_addr = mmaddr2coinaddr(mmid,ad_w,None) if is_mmgen_id(mmid) else CoinAddr(mmid)
  1174. self.add_output(coin_addr,g.proto.coin_amt('0'),is_chg=True)
  1175. else:
  1176. die(2,'{}: invalid command-line argument'.format(mmid))
  1177. self.add_mmaddrs_to_outputs(ad_w,None)
  1178. if not segwit_is_active() and self.has_segwit_outputs():
  1179. fs = '{} Segwit address requested on the command line, but Segwit is not active on this chain'
  1180. rdie(2,fs.format(g.proj_name))
  1181. def get_split_fee_from_user(self):
  1182. if opt.rpc_host2:
  1183. g.rpc_host = opt.rpc_host2
  1184. if opt.tx_fees:
  1185. opt.tx_fee = opt.tx_fees.split(',')[1]
  1186. try:
  1187. rpc_init(reinit=True)
  1188. except:
  1189. ymsg('Connect to {} daemon failed. Network fee estimation unavailable'.format(g.coin))
  1190. return self.get_usr_fee_interactive(opt.tx_fee,'User-selected')
  1191. return super(type(self),self).get_fee_from_user()
  1192. def create_split(self,mmid):
  1193. self.outputs = self.MMGenTxOutputList()
  1194. self.get_outputs_from_cmdline(mmid)
  1195. while True:
  1196. change_amt = self.sum_inputs() - self.get_split_fee_from_user()
  1197. if change_amt >= 0:
  1198. p = 'Transaction produces {} {} in change'.format(change_amt.hl(),g.coin)
  1199. if opt.yes or keypress_confirm(p+'. OK?',default_yes=True):
  1200. if opt.yes: msg(p)
  1201. break
  1202. else:
  1203. msg(wmsg['not_enough_coin'].format(abs(change_amt)))
  1204. self.update_output_amt(0,change_amt)
  1205. self.send_amt = change_amt
  1206. if not opt.yes:
  1207. self.add_comment() # edits an existing comment
  1208. self.create_raw() # creates self.hex, self.txid
  1209. self.add_timestamp()
  1210. self.add_blockcount() # TODO
  1211. self.chain = g.chain
  1212. assert self.sum_inputs() - self.sum_outputs() <= g.proto.max_tx_fee
  1213. qmsg('Transaction successfully created')
  1214. if not opt.yes:
  1215. self.view_with_prompt('View decoded transaction?')