contract.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. altcoins.eth.contract: Ethereum contract and token classes for the MMGen suite
  20. """
  21. from decimal import Decimal
  22. from . import rlp
  23. from mmgen.util import msg,pp_msg
  24. from mmgen.globalvars import g
  25. from mmgen.base_obj import AsyncInit
  26. from mmgen.obj import MMGenObject,CoinTxID
  27. from mmgen.addr import CoinAddr,TokenAddr
  28. from .obj import ETHAmt
  29. def parse_abi(s):
  30. return [s[:8]] + [s[8+x*64:8+(x+1)*64] for x in range(len(s[8:])//64)]
  31. class TokenBase(MMGenObject): # ERC20
  32. def create_method_id(self,sig):
  33. return self.keccak_256(sig.encode()).hexdigest()[:8]
  34. def transferdata2sendaddr(self,data): # online
  35. return CoinAddr(self.proto,parse_abi(data)[1][-40:])
  36. def transferdata2amt(self,data): # online
  37. return ETHAmt(int(parse_abi(data)[-1],16) * self.base_unit)
  38. async def do_call(self,method_sig,method_args='',toUnit=False):
  39. data = self.create_method_id(method_sig) + method_args
  40. if g.debug:
  41. msg('ETH_CALL {}: {}'.format(
  42. method_sig,
  43. '\n '.join(parse_abi(data)) ))
  44. ret = await self.rpc.call('eth_call',{ 'to': '0x'+self.addr, 'data': '0x'+data },'pending')
  45. if self.proto.network == 'regtest' and g.daemon_id == 'erigon': # ERIGON
  46. import asyncio
  47. await asyncio.sleep(5)
  48. if toUnit:
  49. return int(ret,16) * self.base_unit
  50. else:
  51. return ret
  52. async def get_balance(self,acct_addr):
  53. return ETHAmt(await self.do_call('balanceOf(address)',acct_addr.rjust(64,'0'),toUnit=True))
  54. def strip(self,s):
  55. return ''.join([chr(b) for b in s if 32 <= b <= 127]).strip()
  56. async def get_name(self):
  57. return self.strip(bytes.fromhex((await self.do_call('name()'))[2:]))
  58. async def get_symbol(self):
  59. return self.strip(bytes.fromhex((await self.do_call('symbol()'))[2:]))
  60. async def get_decimals(self):
  61. ret = await self.do_call('decimals()')
  62. try:
  63. assert ret[:2] == '0x'
  64. return int(ret,16)
  65. except:
  66. msg(f'RPC call to decimals() failed (returned {ret!r})')
  67. return None
  68. async def get_total_supply(self):
  69. return await self.do_call('totalSupply()',toUnit=True)
  70. async def info(self):
  71. return ('{:15}{}\n' * 5).format(
  72. 'token address:', self.addr,
  73. 'token symbol:', await self.get_symbol(),
  74. 'token name:', await self.get_name(),
  75. 'decimals:', self.decimals,
  76. 'total supply:', await self.get_total_supply() )
  77. async def code(self):
  78. return (await self.rpc.call('eth_getCode','0x'+self.addr))[2:]
  79. def create_data(self,to_addr,amt,method_sig='transfer(address,uint256)',from_addr=None):
  80. from_arg = from_addr.rjust(64,'0') if from_addr else ''
  81. to_arg = to_addr.rjust(64,'0')
  82. amt_arg = '{:064x}'.format( int(amt / self.base_unit) )
  83. return self.create_method_id(method_sig) + from_arg + to_arg + amt_arg
  84. def make_tx_in( self,from_addr,to_addr,amt,start_gas,gasPrice,nonce,
  85. method_sig='transfer(address,uint256)',from_addr2=None):
  86. data = self.create_data(to_addr,amt,method_sig=method_sig,from_addr=from_addr2)
  87. return {'to': bytes.fromhex(self.addr),
  88. 'startgas': start_gas.toWei(),
  89. 'gasprice': gasPrice.toWei(),
  90. 'value': 0,
  91. 'nonce': nonce,
  92. 'data': bytes.fromhex(data) }
  93. async def txsign(self,tx_in,key,from_addr,chain_id=None):
  94. from .pyethereum.transactions import Transaction
  95. if chain_id is None:
  96. res = await self.rpc.call('eth_chainId')
  97. chain_id = None if res == None else int(res,16)
  98. tx = Transaction(**tx_in).sign(key,chain_id)
  99. hex_tx = rlp.encode(tx).hex()
  100. coin_txid = CoinTxID(tx.hash.hex())
  101. if tx.sender.hex() != from_addr:
  102. die(3,f'Sender address {from_addr!r} does not match address of key {tx.sender.hex()!r}!')
  103. if g.debug:
  104. msg('TOKEN DATA:')
  105. pp_msg(tx.to_dict())
  106. msg('PARSED ABI DATA:\n {}'.format(
  107. '\n '.join(parse_abi(tx.data.hex())) ))
  108. return hex_tx,coin_txid
  109. # The following are used for token deployment only:
  110. async def txsend(self,hex_tx):
  111. return (await self.rpc.call('eth_sendRawTransaction','0x'+hex_tx)).replace('0x','',1)
  112. async def transfer( self,from_addr,to_addr,amt,key,start_gas,gasPrice,
  113. method_sig='transfer(address,uint256)',
  114. from_addr2=None,
  115. return_data=False):
  116. tx_in = self.make_tx_in(
  117. from_addr,to_addr,amt,
  118. start_gas,gasPrice,
  119. nonce = int(await self.rpc.call('eth_getTransactionCount','0x'+from_addr,'pending'),16),
  120. method_sig = method_sig,
  121. from_addr2 = from_addr2 )
  122. (hex_tx,coin_txid) = await self.txsign(tx_in,key,from_addr)
  123. return await self.txsend(hex_tx)
  124. class Token(TokenBase):
  125. def __init__(self,proto,addr,decimals,rpc=None):
  126. if type(self).__name__ == 'Token':
  127. from mmgen.util import get_keccak
  128. self.keccak_256 = get_keccak()
  129. self.proto = proto
  130. self.addr = TokenAddr(proto,addr)
  131. assert isinstance(decimals,int),f'decimals param must be int instance, not {type(decimals)}'
  132. self.decimals = decimals
  133. self.base_unit = Decimal('10') ** -self.decimals
  134. self.rpc = rpc
  135. class TokenResolve(TokenBase,metaclass=AsyncInit):
  136. async def __init__(self,proto,rpc,addr):
  137. from mmgen.util import get_keccak
  138. self.keccak_256 = get_keccak()
  139. self.proto = proto
  140. self.rpc = rpc
  141. self.addr = TokenAddr(proto,addr)
  142. decimals = await self.get_decimals() # requires self.addr!
  143. if not decimals:
  144. raise TokenNotInBlockchain(f'Token {addr!r} not in blockchain')
  145. Token.__init__(self,proto,addr,decimals,rpc)