美文网首页区块链区块链虚拟币开发
以太坊ERC20代币在线钱包对接-python版

以太坊ERC20代币在线钱包对接-python版

作者: 十三流 | 来源:发表于2018-01-22 16:38 被阅读3224次

    前面实验了一下ETH对接的接口,今天打算试一下ERC20代币的对接,说白了就是将以太坊区块中的transtraction数据解析出来,单纯ETH的转账很简单,所有的信息都是明文(以太坊现在据称是支持了零知识证明,不知道那种记录长啥样,暂时无法分析)。

    在私链中转移一个代币,根据返回的tx号,我们到console中得到完整信息如下


    ERC20代币transaction

    前面ETH转账时,from、to、value即为转账双方和金额,这里对了一下信息
    form:事务发起者
    to:合约地址
    查询了一下资料,https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI 这里有对合约数据的详细说明,也就是这里的input,大意是前10个字节是合约函数的hash,后面是输入参数经过编码后拼接起来的,wiki中讲述了每种格式的编码规则,按照这个规则即可实现编解码。

    JS版本解码

    js不愧是web3支持的最好的,可以参考如下资料
    https://lab.miguelmota.com/ethereum-input-data-decoder/example/ -- 在线解析input数据
    https://github.com/ConsenSys/abi-decoder -- 一个解析input数据的js库

    python版本

    由于平时是使用python居多,去看了web3.py,没有找到解析input的函数,倒是有个decode_abi,可以将参数解析出来,函数名无法得到,后面想了想还是根据js的版本改写一个python版本吧,如果有其他的朋友正好需要可以拿去使用,上代码

    # -*- coding: utf-8 -*- 
    from web3 import HTTPProvider  
    from web3 import Web3
    from eth_abi import decode_abi
    
    ETH_HTTP_PROVIDER_DB="http://127.0.0.1:8200"
    ETH_HTTP_PROVIDER_ACCOUNT="http://127.0.0.1:8200"
    
    false=False
    true=True
    abi=[{"constant":false,"inputs":[{"name":"newSellPrice","type":"uint256"},{"name":"newBuyPrice","type":"uint256"}],"name":"setPrices","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"sellPrice","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"target","type":"address"},{"name":"mintedAmount","type":"uint256"}],"name":"mintToken","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"}],"name":"burnFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"buyPrice","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"buy","outputs":[{"name":"amount","type":"uint256"}],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"frozenAccount","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"ptransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"sell","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"target","type":"address"},{"name":"freeze","type":"bool"}],"name":"freezeAccount","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"initialSupply","type":"uint256"},{"name":"tokenName","type":"string"},{"name":"decimalUnits","type":"uint8"},{"name":"tokenSymbol","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"target","type":"address"},{"indexed":false,"name":"frozen","type":"bool"}],"name":"FrozenFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"target","type":"address"},{"indexed":false,"name":"val","type":"uint256"},{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"balance","type":"uint256"}],"name":"PayETHEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"target","type":"address"},{"indexed":false,"name":"val","type":"uint256"},{"indexed":false,"name":"from","type":"address"},{"indexed":false,"name":"balance","type":"uint256"}],"name":"BuyEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"target","type":"address"},{"indexed":false,"name":"val","type":"uint256"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"BuyEventCalc","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"target","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"balance","type":"uint256"},{"indexed":false,"name":"calc","type":"uint256"}],"name":"SellEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"}]
    input="0xa9059cbb000000000000000000000000855ecc6b1c1cd332ea87e0f77189e8318deadc9d000000000000000000000000000000000000000000000000000000000000c350"
    contract_address="0x9650bd781FbbE71bC65583B5205E2Fe69B1611c2"
    
    web3=Web3(HTTPProvider(ETH_HTTP_PROVIDER_ACCOUNT))
    contract=web3.eth.contract(abi,contract_address)
    
    def getFunctionHashes(web3,abi):
        hashes = [];
        for i in range(0,len(abi)):
            item = abi[i]
            if (item['type'] != "function"):
                continue
            signature = item['name'] + "(" + ",".join(map(lambda input:input['type'],item['inputs'])) + ")"
            hash = web3.sha3(signature.encode("hex"))
            hashes.append({'name': item['name'], 'hash': hash, 'inputs':[(x['name'],x['type']) for x in item['inputs']]})
      
        return hashes
    
    def findFunctionByHash(hashes, functionHash):
        for i in range(0,len(hashes)):
            if hashes[i]['hash'][:10] == functionHash[:10]:
                return hashes[i]['name'],hashes[i]['inputs']
        return None,None
    
    if __name__=="__main__":
        hashes=getFunctionHashes(web3,abi)
        func,name_and_type=findFunctionByHash(hashes,input)
        print func,decode_abi([x[1] for x in name_and_type], input[10:].decode('hex'))
        print func,zip([x[0] for x in name_and_type],decode_abi([x[1] for x in name_and_type], input[10:].decode('hex')))
    
    

    运行结果如下


    图片.png

    可以看到,这个transaction对应的函数以及参数,后面要做的就是自己的入账处理了,这里不再啰嗦了

    相关文章

      网友评论

      • 8337ea5e8883:您好,看到您的文章质量非常高,想邀请您成为虫洞社区的首批优质内容签约作者。虫洞社区是专业的区块链技术学习社区。虫洞社区鼓励内容生产者产生高质量内容,并给予合理的回报,也希望能帮助内容消费者获得高质量的区块链内容,并让数字货币投资者获得有价值的投资洞见。同时,虫洞社区已经积累了大量的区块链深度从业者,便于作者建立个人品牌。不知道是否方便加您微信细聊?
      • 编程狂魔:安利个python开发以太坊区块链的教程(web3.py):
        http://xc.hubwiz.com/course/5b40462cc02e6b6a59171de4?affid=810jianshu

      本文标题:以太坊ERC20代币在线钱包对接-python版

      本文链接:https://www.haomeiwen.com/subject/tqolaxtx.html