Del golang sha3 a la solidez sha3

Tratar de hacer coincidir la librería "golang.org/x/crypto/sha3" con la solidez sha3() me está costando mucho. Se ha discutido aquí , pero de alguna manera no puedo aplicarlo en go. ¿Cómo manejo un tipo big.Int st i get solidity.sha3(uint256(1))==golang.sha3.Sum256(convertMyBigInt(myBigInt)) ?

Convierto bigInt en una matriz de bytes hexadecimales, luego lleno el sitio izquierdo con ceros, hash y luego salida.

//create a big int for test and set to 1
b1 := new(big.Int)
b1.SetInt64(1)
//create empty array with 32 bytes for padding
empty := make([]byte,32)
//turn the big int into a hex string (let me know if there is a more 
      //elegant way^^)
String := bytes.NewBufferString(b1.Text(16))
copy(empty[len(empty)-len(String.Bytes()):],String.Bytes())
//output of empty : [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49]
res:= new(big.Int)
temp:=sha3.Sum256(empty)
res.SetBytes(temp[:])   
fmt.Println("\nresult ",res.Text(16))

salida: 26502030f0954243c70cb7fa68e0752ce2bf99aabfc0219d5184635d4c61dbd8

la solidez me da:

sha3(uint(1))
b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6

¿Puede alguien darme un breve ejemplo de cómo combinar solidity sha3 con golang sha3 de una manera elegante? te lo agradeceria mucho!

Respuestas (1)

Aquí hay un ejemplo de trabajo completo sobre la generación de hashes sha3 de solidez a partir de uint256:

package main

import (
    "fmt"
    "math/big"

    "github.com/ethereum/go-ethereum/accounts/abi"
    "github.com/ethereum/go-ethereum/crypto/sha3"
)

func main() {
    h := sha3.NewKeccak256()
    h.Write(abi.U256(big.NewInt(1)))
    hash := h.Sum(nil)
    fmt.Printf("%x", hash) // b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6
}

Solidez:

sha3(uint(1))
b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6

Hice la biblioteca go-solidity-sha3 para poder convertir fácilmente los tipos de solidez en hashes de solidez sha3 en Go. Aquí hay un ejemplo:

package main

import (
    "fmt"
    "math/big"

    solsha3 "github.com/miguelmota/go-solidity-sha3"
)

func main() {
    hash := solsha3.SoliditySHA3(
        solsha3.Uint256(big.NewInt(1)),
    )
    fmt.Printf("%x", hash) // b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6
}

Un ejemplo más complejo:

package main

import (
    "encoding/hex"
    "fmt"
    "math/big"

    "github.com/miguelmota/go-solidity-sha3"
)

func main() {
    hash := solsha3.SoliditySHA3(
        solsha3.Address("0x12459c951127e0c374ff9105dda097662a027093"),
        solsha3.Uint256(big.NewInt(100)),
        solsha3.String("foo"),
        solsha3.Bytes32("bar"),
        solsha3.Bool(true),
    )

    fmt.Println(hex.EncodeToString(hash)) // 417a4c44724701ba79bb363151dff48909bc058a2c75a81e9cf5208ae4699369
}