txfile.py 7.0 KB

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