file.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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.file: Transaction file operations for the MMGen suite
  20. """
  21. from ..common import *
  22. from ..obj import MMGenObject,HexStr,MMGenTxID,CoinTxID,MMGenTxComment
  23. class MMGenTxFile(MMGenObject):
  24. def __init__(self,tx):
  25. self.tx = tx
  26. self.chksum = None
  27. self.fmt_data = None
  28. self.filename = None
  29. def parse(self,infile,metadata_only=False,quiet_open=False):
  30. tx = self.tx
  31. def eval_io_data(raw_data,desc):
  32. from ast import literal_eval
  33. try:
  34. d = literal_eval(raw_data)
  35. except:
  36. if desc == 'inputs' and not quiet_open:
  37. ymsg('Warning: transaction data appears to be in old format')
  38. import re
  39. d = literal_eval(re.sub(r"[A-Za-z]+?\(('.+?')\)",r'\1',raw_data))
  40. assert type(d) == list, f'{desc} data not a list!'
  41. if not (desc == 'outputs' and tx.proto.base_coin == 'ETH'): # ETH txs can have no outputs
  42. assert len(d), f'no {desc}!'
  43. for e in d:
  44. e['amt'] = tx.proto.coin_amt(e['amt'])
  45. if 'label' in e:
  46. e['comment'] = e['label']
  47. del e['label']
  48. io,io_list = {
  49. 'inputs': ( tx.Input, tx.InputList ),
  50. 'outputs': ( tx.Output, tx.OutputList ),
  51. }[desc]
  52. return io_list( parent=tx, data=[io(tx.proto,**e) for e in d] )
  53. from ..fileutil import get_data_from_file
  54. tx_data = get_data_from_file(infile,tx.desc+' data',quiet=quiet_open)
  55. try:
  56. desc = 'data'
  57. if len(tx_data) > g.max_tx_file_size:
  58. die( 'MaxFileSizeExceeded', f'Transaction file size exceeds limit ({g.max_tx_file_size} bytes)' )
  59. tx_data = tx_data.splitlines()
  60. assert len(tx_data) >= 5,'number of lines less than 5'
  61. assert len(tx_data[0]) == 6,'invalid length of first line'
  62. self.chksum = HexStr(tx_data.pop(0))
  63. assert self.chksum == make_chksum_6(' '.join(tx_data)),'file data does not match checksum'
  64. if len(tx_data) == 6:
  65. assert len(tx_data[-1]) == 64,'invalid coin TxID length'
  66. desc = f'coin TxID'
  67. tx.coin_txid = CoinTxID(tx_data.pop(-1))
  68. if len(tx_data) == 5:
  69. # rough check: allow for 4-byte utf8 characters + base58 (4 * 11 / 8 = 6 (rounded up))
  70. assert len(tx_data[-1]) < MMGenTxComment.max_len*6,'invalid comment length'
  71. c = tx_data.pop(-1)
  72. if c != '-':
  73. desc = 'encoded comment (not base58)'
  74. from ..baseconv import baseconv
  75. comment = baseconv('b58').tobytes(c).decode()
  76. assert comment != False,'invalid comment'
  77. desc = 'comment'
  78. tx.comment = MMGenTxComment(comment)
  79. desc = 'number of lines' # four required lines
  80. ( metadata, tx.serialized, inputs_data, outputs_data ) = tx_data
  81. assert len(metadata) < 100,'invalid metadata length' # rough check
  82. metadata = metadata.split()
  83. if metadata[-1].startswith('LT='):
  84. desc = 'locktime'
  85. tx.locktime = int(metadata.pop()[3:])
  86. desc = 'coin token in metadata'
  87. coin = metadata.pop(0) if len(metadata) == 6 else 'BTC'
  88. coin,tokensym = coin.split(':') if ':' in coin else (coin,None)
  89. desc = 'chain token in metadata'
  90. tx.chain = metadata.pop(0).lower() if len(metadata) == 5 else 'mainnet'
  91. from ..protocol import CoinProtocol,init_proto
  92. network = CoinProtocol.Base.chain_name_to_network(coin,tx.chain)
  93. desc = 'initialization of protocol'
  94. tx.proto = init_proto(coin,network=network,need_amt=True)
  95. if tokensym:
  96. tx.proto.tokensym = tokensym
  97. desc = 'metadata (4 items)'
  98. txid,send_amt,tx.timestamp,blockcount = metadata
  99. desc = 'TxID in metadata'
  100. tx.txid = MMGenTxID(txid)
  101. desc = 'block count in metadata'
  102. tx.blockcount = int(blockcount)
  103. if metadata_only:
  104. return
  105. desc = 'transaction file hex data'
  106. tx.check_txfile_hex_data()
  107. desc = 'Ethereum RLP or JSON data'
  108. tx.parse_txfile_serialized_data()
  109. desc = 'inputs data'
  110. tx.inputs = eval_io_data(inputs_data,'inputs')
  111. desc = 'outputs data'
  112. tx.outputs = eval_io_data(outputs_data,'outputs')
  113. desc = 'send amount in metadata'
  114. from decimal import Decimal
  115. assert Decimal(send_amt) == tx.send_amt, f'{send_amt} != {tx.send_amt}'
  116. except Exception as e:
  117. die(2,f'Invalid {desc} in transaction file: {e!s}')
  118. def make_filename(self):
  119. tx = self.tx
  120. def gen_filename():
  121. yield tx.txid
  122. if tx.coin != 'BTC':
  123. yield '-' + tx.dcoin
  124. yield f'[{tx.send_amt!s}'
  125. if tx.is_replaceable():
  126. yield ',{}'.format(tx.fee_abs2rel(tx.fee,to_unit=tx.fn_fee_unit))
  127. if tx.get_serialized_locktime():
  128. yield ',tl={}'.format(tx.get_serialized_locktime())
  129. yield ']'
  130. if g.debug_utf8:
  131. yield '-α'
  132. if tx.proto.testnet:
  133. yield '.' + tx.proto.network
  134. yield '.' + tx.ext
  135. return ''.join(gen_filename())
  136. def format(self):
  137. tx = self.tx
  138. def amt_to_str(d):
  139. return {k: (str(d[k]) if k == 'amt' else d[k]) for k in d}
  140. coin_id = '' if tx.coin == 'BTC' else tx.coin + ('' if tx.coin == tx.dcoin else ':'+tx.dcoin)
  141. lines = [
  142. '{}{} {} {} {} {}{}'.format(
  143. (coin_id+' ' if coin_id else ''),
  144. tx.chain.upper(),
  145. tx.txid,
  146. tx.send_amt,
  147. tx.timestamp,
  148. tx.blockcount,
  149. (f' LT={tx.locktime}' if tx.locktime else ''),
  150. ),
  151. tx.serialized,
  152. ascii([amt_to_str(e._asdict()) for e in tx.inputs]),
  153. ascii([amt_to_str(e._asdict()) for e in tx.outputs])
  154. ]
  155. if tx.comment:
  156. from ..baseconv import baseconv
  157. lines.append(baseconv('b58').frombytes(tx.comment.encode(),tostr=True))
  158. if tx.coin_txid:
  159. if not tx.comment:
  160. lines.append('-') # keep old tx files backwards compatible
  161. lines.append(tx.coin_txid)
  162. self.chksum = make_chksum_6(' '.join(lines))
  163. fmt_data = '\n'.join([self.chksum] + lines) + '\n'
  164. if len(fmt_data) > g.max_tx_file_size:
  165. die( 'MaxFileSizeExceeded', f'Transaction file size exceeds limit ({g.max_tx_file_size} bytes)' )
  166. return fmt_data
  167. def write(self,
  168. add_desc = '',
  169. ask_write = True,
  170. ask_write_default_yes = False,
  171. ask_tty = True,
  172. ask_overwrite = True ):
  173. if ask_write == False:
  174. ask_write_default_yes = True
  175. if not self.filename:
  176. self.filename = self.make_filename()
  177. if not self.fmt_data:
  178. self.fmt_data = self.format()
  179. from ..fileutil import write_data_to_file
  180. write_data_to_file(
  181. outfile = self.filename,
  182. data = self.fmt_data,
  183. desc = self.tx.desc + add_desc,
  184. ask_overwrite = ask_overwrite,
  185. ask_write = ask_write,
  186. ask_tty = ask_tty,
  187. ask_write_default_yes = ask_write_default_yes )
  188. @classmethod
  189. def get_proto(cls,filename,quiet_open=False):
  190. from . import BaseTX
  191. tmp_tx = BaseTX()
  192. cls(tmp_tx).parse(filename,metadata_only=True,quiet_open=quiet_open)
  193. return tmp_tx.proto