From 811d5ead9753f785edecebc0b5606c9ecd533cd5 Mon Sep 17 00:00:00 2001 From: Maksym Hrynenko Date: Mon, 9 Dec 2024 16:43:56 +0200 Subject: [PATCH] fix: build message digest with solidity abi encoding --- .../service/api/handlers/get_signed_state.go | 49 +++++++++++++++---- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/internal/service/api/handlers/get_signed_state.go b/internal/service/api/handlers/get_signed_state.go index d97d917..f07919f 100644 --- a/internal/service/api/handlers/get_signed_state.go +++ b/internal/service/api/handlers/get_signed_state.go @@ -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" @@ -66,11 +67,30 @@ 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, @@ -78,18 +98,27 @@ func signState(state data.State, r *http.Request) ([]byte, error) { // 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 }