doupang9614 2018-06-09 09:29
浏览 3024
已采纳

如何在Golang中获得与solidity`abi.encodePacked`相同的返回值

How can i run abi.encodePacked in golang?

in solidity i use keccak256(abi.encodePacked(a, b)) to calc the signature of the params.

here is my contract.

pragma solidity ^0.4.24;

import "openzeppelin-solidity/contracts/ECRecovery.sol";


contract MyContract {
    using ECRecovery for bytes32;
    address permittedSinger;

    function doSomething(
    bytes32 id, uint256 amount, bytes sig
    ) {
        bytes32 hash = getHash(msg.sender, id, amount);
        address msgSigner = hash.recover(sig);
        require(msgSigner == permittedSinger);
    }

    function getMsgSigner(bytes32 proveHash, bytes sig) public pure returns (address) {
        return proveHash.recover(sig);
    }

    function getHash(
    address receiver, bytes32 id, uint256 amount
    ) pure returns (bytes32) {
        return keccak256(abi.encodePacked(receiver, id, amount));
    }
}
  • 写回答

1条回答 默认 最新

  • dounong5373 2018-06-09 15:45
    关注

    finally I managed to do it. :)

    package main
    
    import (
        "math/big"
        "github.com/ethereum/go-ethereum/common/hexutil"
        "github.com/ethereum/go-ethereum/accounts/abi"
        "log"
        "github.com/ethereum/go-ethereum/common"
        "github.com/ethereum/go-ethereum/crypto/sha3"
    )
    
    func main() {
        uint256Ty, _ := abi.NewType("uint256")
        bytes32Ty, _ := abi.NewType("bytes32")
        addressTy, _ := abi.NewType("address")
    
        arguments := abi.Arguments{
            {
                Type: addressTy,
            },
            {
                Type: bytes32Ty,
            },
            {
                Type: uint256Ty,
            },
        }
    
        bytes, _ := arguments.Pack(
            common.HexToAddress("0x0000000000000000000000000000000000000000"),
            [32]byte{'I','D','1'},
            big.NewInt(42),
        )
    
        var buf []byte
        hash := sha3.NewKeccak256()
        hash.Write(bytes)
        buf = hash.Sum(buf)
    
        log.Println(hexutil.Encode(buf))
        // output:
        // 0x1f214438d7c061ad56f98540db9a082d372df1ba9a3c96367f0103aa16c2fe9a
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错