其他分享
首页 > 其他分享> > go eth 踩坑 crypto.Sign 与 eth.account.signHash 或者 web3Process.web3.eth.personal.sign 签名结果不同 除了最后一位 都匹配

go eth 踩坑 crypto.Sign 与 eth.account.signHash 或者 web3Process.web3.eth.personal.sign 签名结果不同 除了最后一位 都匹配

作者:互联网

从 go-ethereum 实现 Ethereum personal_sign (EIP-191) 给出了与
ethers.js web3.py web3.js solidy.sgin不同的签名
原文 https://stackoverflow.com/questions/69762108/implementing-ethereum-personal-sign-eip-191-from-go-ethereum-gives-different-s

 

js 签名消息代码

const accounts = await web3Process.web3.eth.getAccounts()
this.imtContract = new web3Process.web3.eth.Contract(imtAbi, paymentErc20)
const decimals = await this.imtContract.methods.decimals().call({
  from: accounts[0]
})
const heroPrice = price * Math.pow(10, decimals)
console.log(web3Process.heroAddress, tokenId, paymentErc20, heroPrice, saltNonce)
let messageHash = web3Process.web3.utils.soliditySha3(web3Process.heroAddress, tokenId, paymentErc20, heroPrice, saltNonce)
console.log("messageHash", messageHash)
// messageHash = "\x19Ethereum Signed Message:\n32" + messageHash
// messageHash = web3Process.web3.eth.accounts.hashMessage(messageHash)
try {
  const signature = await web3Process.web3.eth.personal.sign(messageHash, accounts[0])
  console.log("signature", signature)
  const hash = web3Process.web3.eth.accounts.hashMessage(messageHash)
  return [signature, hash]
} catch (e) {
  throw(e)
}

  

 python 签名代码

hash_data = w3.soliditySha3(abi_types=["address", "uint256", "address", "uint256", "uint256"],
                values=["address", token_id, "address",
                        amount, time])
print(w3.toHex(hash_data))
sign_data = w3.eth.account.signHash(defunct_hash_message(hexstr=w3.toHex(hash_data)),
                                        private_key="private_key")

  

package main

import (
    "fmt"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "encoding/hex"
    "encoding/json"
    "log"
)

func signHash(data []byte) common.Hash {
    msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
    return crypto.Keccak256Hash([]byte(msg))
}

func main() {

    hexPrivateKey := "8da4ef21b864d2cc526dbdb2a120bd2874c36c9d0a1fb7f8c63d7f7a8b41de8f"
    dataMap := map[string]string{"data1":"value1","data2":"value2"}
    dataToSign, _ := json.Marshal(dataMap)

    privateKey, err := crypto.HexToECDSA(hexPrivateKey)
    if err != nil {
            log.Fatal(err)
    }

    dataHash := crypto.Keccak256Hash(dataToSign) //0x8d218fc37d2fd952b2d115046b786b787e44d105cccf156882a2e74ad993ee13

    signHash := signHash(dataHash.Bytes())

    signatureBytes, err := crypto.Sign(signHash.Bytes(), privateKey)
    if err != nil {
            log.Fatal(err)
    }
    
    fmt.Println("0x" + hex.EncodeToString(signatureBytes))
}

  

标签:account,personal,web3Process,web3,ethereum,messageHash,eth,data
来源: https://www.cnblogs.com/Sunbreaker/p/16326262.html