Skip to content

Commit

Permalink
fix: build message digest with solidity abi encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
mhrynenko committed Dec 9, 2024
1 parent 74af7c5 commit 811d5ea
Showing 1 changed file with 39 additions and 10 deletions.
49 changes: 39 additions & 10 deletions internal/service/api/handlers/get_signed_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"math/big"
"net/http"

"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/crypto"
"github.com/rarimo/proof-verification-relayer/internal/data"
"github.com/rarimo/proof-verification-relayer/internal/service/api/requests"
Expand Down Expand Up @@ -66,30 +67,58 @@ func GetSignedState(w http.ResponseWriter, r *http.Request) {
}

func signState(state data.State, r *http.Request) ([]byte, error) {
digest, err := buildMessageDigest(state, r)
if err != nil {
return nil, errors.Wrap(err, "failed to build message digest")
}

signature, err := crypto.Sign(digest, Config(r).NetworkConfig().PrivateKey)
if err != nil {
return nil, errors.Wrap(err, "failed to sign state")
}

return signature, nil
}

func buildMessageDigest(state data.State, r *http.Request) ([]byte, error) {
rootBytes, err := hex.DecodeString(state.Root)
if err != nil {
return nil, errors.Wrap(err, "failed to decode signature digest", logan.F{"root": state.Root})
}

uint256Ty, _ := abi.NewType("uint256", "uint256", nil)
bytes32Ty, _ := abi.NewType("bytes32", "bytes32", nil)
addressTy, _ := abi.NewType("address", "address", nil)
stringTy, _ := abi.NewType("string", "string", nil)

//keccak256(abi.encodePacked(
// REGISTRATION_ROOT_PREFIX,
// sourceSMT,
// address(this),
// newRoot_,
// transitionTimestamp_
//));
digest := crypto.Keccak256(
[]byte(Config(r).Replicator().RootPrefix),
Config(r).Replicator().SourceSMT.Bytes(),
Config(r).Replicator().Address.Bytes(),
rootBytes,
new(big.Int).SetUint64(state.Timestamp).Bytes(),
)

signature, err := crypto.Sign(digest, Config(r).NetworkConfig().PrivateKey)
args := abi.Arguments{
{Type: stringTy},
{Type: addressTy},
{Type: addressTy},
{Type: bytes32Ty},
{Type: uint256Ty},
}

rootBytes32 := [32]byte{}
copy(rootBytes32[:], rootBytes[:32])
packed, err := args.Pack(
Config(r).Replicator().RootPrefix,
Config(r).Replicator().SourceSMT,
Config(r).Replicator().Address,
rootBytes32,
new(big.Int).SetUint64(state.Timestamp),
)
if err != nil {
return nil, errors.Wrap(err, "failed to sign state")
return nil, errors.Wrap(err, "failed to pack signature msg digest")
}

return signature, nil
return crypto.Keccak256(packed), nil
}

0 comments on commit 811d5ea

Please sign in to comment.