txfile.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. txfile.py: Transaction file operations for the MMGen suite
  20. """
  21. from .common import *
  22. from .obj import HexStr,MMGenTxID,CoinTxID,MMGenTxLabel
  23. from .tx import MMGenTxOutput,MMGenTxOutputList,MMGenTxInput,MMGenTxInputList
  24. from .amt import UnknownCoinAmt
  25. from .exception import MaxFileSizeExceeded
  26. class MMGenTxFile:
  27. def __init__(self,tx):
  28. self.tx = tx
  29. self.chksum = None
  30. self.fmt_data = None
  31. self.filename = None
  32. def parse(self,infile,metadata_only=False,quiet_open=False):
  33. tx = self.tx
  34. def eval_io_data(raw_data,desc):
  35. from ast import literal_eval
  36. try:
  37. d = literal_eval(raw_data)
  38. except:
  39. if desc == 'inputs' and not quiet_open:
  40. ymsg('Warning: transaction data appears to be in old format')
  41. import re
  42. d = literal_eval(re.sub(r"[A-Za-z]+?\(('.+?')\)",r'\1',raw_data))
  43. assert type(d) == list, f'{desc} data not a list!'
  44. if not (desc == 'outputs' and tx.proto.base_coin == 'ETH'): # ETH txs can have no outputs
  45. assert len(d), f'no {desc}!'
  46. for e in d:
  47. e['amt'] = tx.proto.coin_amt(e['amt'])
  48. io,io_list = (
  49. (MMGenTxOutput,MMGenTxOutputList),
  50. (MMGenTxInput,MMGenTxInputList)
  51. )[desc=='inputs']
  52. return io_list(tx,[io(tx.proto,**e) for e in d])
  53. tx_data = get_data_from_file(infile,tx.desc+' data',quiet=quiet_open)
  54. try:
  55. desc = 'data'
  56. if len(tx_data) > g.max_tx_file_size:
  57. raise MaxFileSizeExceeded(f'Transaction file size exceeds limit ({g.max_tx_file_size} bytes)')
  58. tx_data = tx_data.splitlines()
  59. assert len(tx_data) >= 5,'number of lines less than 5'
  60. assert len(tx_data[0]) == 6,'invalid length of first line'
  61. self.chksum = HexStr(tx_data.pop(0))
  62. assert self.chksum == make_chksum_6(' '.join(tx_data)),'file data does not match checksum'
  63. if len(tx_data) == 6:
  64. assert len(tx_data[-1]) == 64,'invalid coin TxID length'
  65. desc = f'coin TxID'
  66. tx.coin_txid = CoinTxID(tx_data.pop(-1))
  67. if len(tx_data) == 5:
  68. # rough check: allow for 4-byte utf8 characters + base58 (4 * 11 / 8 = 6 (rounded up))
  69. assert len(tx_data[-1]) < MMGenTxLabel.max_len*6,'invalid comment length'
  70. c = tx_data.pop(-1)
  71. if c != '-':
  72. desc = 'encoded comment (not base58)'
  73. from .baseconv import baseconv
  74. comment = baseconv('b58').tobytes(c).decode()
  75. assert comment != False,'invalid comment'
  76. desc = 'comment'
  77. tx.label = MMGenTxLabel(comment)
  78. desc = 'number of lines' # four required lines
  79. metadata,tx.hex,inputs_data,outputs_data = tx_data
  80. assert len(metadata) < 100,'invalid metadata length' # rough check
  81. metadata = metadata.split()
  82. if metadata[-1].startswith('LT='):
  83. desc = 'locktime'
  84. tx.locktime = int(metadata.pop()[3:])
  85. desc = 'coin token in metadata'
  86. coin = metadata.pop(0) if len(metadata) == 6 else 'BTC'
  87. coin,tokensym = coin.split(':') if ':' in coin else (coin,None)
  88. desc = 'chain token in metadata'
  89. tx.chain = metadata.pop(0).lower() if len(metadata) == 5 else 'mainnet'
  90. from .protocol import CoinProtocol,init_proto
  91. network = CoinProtocol.Base.chain_name_to_network(coin,tx.chain)
  92. desc = 'initialization of protocol'
  93. tx.proto = init_proto(coin,network=network)
  94. if tokensym:
  95. tx.proto.tokensym = tokensym
  96. desc = 'metadata (4 items)'
  97. txid,send_amt,tx.timestamp,blockcount = metadata
  98. desc = 'TxID in metadata'
  99. tx.txid = MMGenTxID(txid)
  100. desc = 'block count in metadata'
  101. tx.blockcount = int(blockcount)
  102. if metadata_only:
  103. return
  104. desc = 'transaction file hex data'
  105. tx.check_txfile_hex_data()
  106. desc = 'Ethereum transaction file hex or json data'
  107. tx.parse_txfile_hex_data()
  108. desc = 'inputs data'
  109. tx.inputs = eval_io_data(inputs_data,'inputs')
  110. desc = 'outputs data'
  111. tx.outputs = eval_io_data(outputs_data,'outputs')
  112. desc = 'send amount in metadata'
  113. assert Decimal(send_amt) == tx.send_amt, f'{send_amt} != {tx.send_amt}'
  114. except Exception as e:
  115. die(2,f'Invalid {desc} in transaction file: {e!s}')
  116. def make_filename(self):
  117. tx = self.tx
  118. def gen_filename():
  119. yield tx.txid
  120. if tx.coin != 'BTC':
  121. yield '-' + tx.dcoin
  122. yield f'[{tx.send_amt!s}'
  123. if tx.is_replaceable():
  124. yield ',{}'.format(tx.fee_abs2rel(tx.fee,to_unit=tx.fn_fee_unit))
  125. if tx.get_hex_locktime():
  126. yield ',tl={}'.format(tx.get_hex_locktime())
  127. yield ']'
  128. if g.debug_utf8:
  129. yield '-α'
  130. if tx.proto.testnet:
  131. yield '.' + tx.proto.network
  132. yield '.' + tx.ext
  133. return ''.join(gen_filename())
  134. def format(self):
  135. tx = self.tx
  136. def amt_to_str(d):
  137. return {k: (str(d[k]) if k == 'amt' else d[k]) for k in d}
  138. coin_id = '' if tx.coin == 'BTC' else tx.coin + ('' if tx.coin == tx.dcoin else ':'+tx.dcoin)
  139. lines = [
  140. '{}{} {} {} {} {}{}'.format(
  141. (coin_id+' ' if coin_id else ''),
  142. tx.chain.upper(),
  143. tx.txid,
  144. tx.send_amt,
  145. tx.timestamp,
  146. tx.blockcount,
  147. (f' LT={tx.locktime}' if tx.locktime else ''),
  148. ),
  149. tx.hex,
  150. ascii([amt_to_str(e._asdict()) for e in tx.inputs]),
  151. ascii([amt_to_str(e._asdict()) for e in tx.outputs])
  152. ]
  153. if tx.label:
  154. from .baseconv import baseconv
  155. lines.append(baseconv('b58').frombytes(tx.label.encode(),tostr=True))
  156. if tx.coin_txid:
  157. if not tx.label:
  158. lines.append('-') # keep old tx files backwards compatible
  159. lines.append(tx.coin_txid)
  160. self.chksum = make_chksum_6(' '.join(lines))
  161. fmt_data = '\n'.join([self.chksum] + lines) + '\n'
  162. if len(fmt_data) > g.max_tx_file_size:
  163. raise MaxFileSizeExceeded(f'Transaction file size exceeds limit ({g.max_tx_file_size} bytes)')
  164. return fmt_data
  165. def write(self,
  166. add_desc = '',
  167. ask_write = True,
  168. ask_write_default_yes = False,
  169. ask_tty = True,
  170. ask_overwrite = True ):
  171. if ask_write == False:
  172. ask_write_default_yes = True
  173. if not self.filename:
  174. self.filename = self.make_filename()
  175. if not self.fmt_data:
  176. self.fmt_data = self.format()
  177. write_data_to_file(
  178. outfile = self.filename,
  179. data = self.fmt_data,
  180. desc = self.tx.desc + add_desc,
  181. ask_overwrite = ask_overwrite,
  182. ask_write = ask_write,
  183. ask_tty = ask_tty,
  184. ask_write_default_yes = ask_write_default_yes )
  185. @classmethod
  186. def get_proto(cls,filename,quiet_open=False):
  187. from .tx import MMGenTX
  188. tmp_tx = MMGenTX.Base()
  189. cls(tmp_tx).parse(filename,metadata_only=True,quiet_open=quiet_open)
  190. return tmp_tx.proto