From fb469ce424a487765c9490743af0e4c3f8de434a Mon Sep 17 00:00:00 2001 From: Marcin Gorzynski Date: Fri, 16 Feb 2024 12:21:30 +0100 Subject: [PATCH] add IsEIP191Message & MessageToEIP191 --- signature.go | 15 +++++++++++++++ signature_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/signature.go b/signature.go index b283a9d4..2d42ce20 100644 --- a/signature.go +++ b/signature.go @@ -1,6 +1,7 @@ package sequence import ( + "bytes" "context" "fmt" "math/big" @@ -218,6 +219,20 @@ func IsValidUndeployedSignature(walletAddress common.Address, digest common.Hash return V2IsValidUndeployedSignature(walletAddress, digest, seqSig, walletContext, chainID, provider) } +func IsEIP191Message(msg []byte) bool { + return len(msg) > 0 && msg[0] == 0x19 +} + +func MessageToEIP191(msg []byte) []byte { + if !IsEIP191Message(msg) { + return bytes.Join([][]byte{ + []byte("\x19Ethereum Signed Message:\n"), + []byte(fmt.Sprintf("%v", len(msg))), + msg}, nil) + } + return msg +} + func MessageDigest(message []byte) common.Hash { return common.BytesToHash(ethcoder.Keccak256(message)) } diff --git a/signature_test.go b/signature_test.go index 24530b2f..49450ded 100644 --- a/signature_test.go +++ b/signature_test.go @@ -1,5 +1,12 @@ package sequence_test +import ( + "testing" + + "github.com/0xsequence/go-sequence" + "github.com/stretchr/testify/assert" +) + /* const message = "hi!" @@ -547,3 +554,42 @@ func areSignaturesIsomorphic(a *signature, b *signature) bool { return true } */ + +func TestIsEIP191Message(t *testing.T) { + t.Run("EIP191", func(t *testing.T) { + // EIP191 message + msg := []byte("\x19Ethereum Signed Message:\n5hello") + ok := sequence.IsEIP191Message(msg) + if !ok { + t.Error("expected EIP191 message") + } + }) + + t.Run("non-EIP191", func(t *testing.T) { + // non-EIP191 message + msg := []byte("hello") + ok := sequence.IsEIP191Message(msg) + if ok { + t.Error("expected non-EIP191 message") + } + }) +} + +func TestMessageToEIP191(t *testing.T) { + t.Run("EIP191_none", func(t *testing.T) { + // EIP191 message + msg := []byte("hello") + expectedEIP191 := []byte("\x19Ethereum Signed Message:\n5hello") + + eip191 := sequence.MessageToEIP191(msg) + assert.Equal(t, eip191, expectedEIP191) + }) + + t.Run("EIP191_already", func(t *testing.T) { + // EIP191 message + msg := []byte("\x19Ethereum Signed Message:\n5hello") + eip191 := sequence.MessageToEIP191(msg) + + assert.Equal(t, msg, eip191) + }) +}