Skip to content

Commit

Permalink
feat(utils): add IsMessageSignatureCorrect
Browse files Browse the repository at this point in the history
  • Loading branch information
danijelTxFusion committed Jul 27, 2024
1 parent 98e7825 commit 001cfef
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
16 changes: 16 additions & 0 deletions utils/signature.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package utils

import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)

// IsMessageSignatureCorrect checks whether the message ECDSA signature is correct.
func IsMessageSignatureCorrect(address common.Address, msg, sig []byte) (bool, error) {
publicKey, err := crypto.SigToPub(accounts.TextHash(msg), sig)
if err != nil {
return false, err
}
return address == crypto.PubkeyToAddress(*publicKey), nil
}
25 changes: 25 additions & 0 deletions utils/signature_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package utils

import (
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/assert"
"testing"
)

func TestIsMessageSignatureCorrect(t *testing.T) {
const message = "Hello, world!"
const signature = "0xb04f825363596418c630425916f73447d636094a75e47b45e2eb59d8a6c7d5035355f03b903b84700376f0efa23f3b095815776c5c6daf2b371a0a61b5f7034500"
address := common.HexToAddress("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049")
actual, err := IsMessageSignatureCorrect(address, []byte(message), common.FromHex(signature))
assert.NoError(t, err, "Should throw error for valid message signature")
assert.True(t, actual, "Message signature should be valid")
}

func TestIsMessageSignatureCorrectInvalidSignature(t *testing.T) {
const message = "Hello world"
const signature = "0xb04f825363596418c630425916f73447d636094a75e47b45e2eb59d8a6c7d5035355f03b903b84700376f0efa23f3b095815776c5c6daf2b371a0a61b5f7034500"
address := common.HexToAddress("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049")
actual, err := IsMessageSignatureCorrect(address, []byte(message), common.FromHex(signature))
assert.NoError(t, err, "Should throw error for valid message signature")
assert.False(t, actual, "Message signature should be invalid")
}

0 comments on commit 001cfef

Please sign in to comment.