contract.py 5.8 KB

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