tx.py 49 KB

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