Skip to content

Commit

Permalink
improve bytes of bytes hashing (#249)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimkouv authored Nov 3, 2023
1 parent c4cacc3 commit e1fb3ba
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1227,7 +1227,7 @@ func Test_calculateObservedMessagesConsensus(t *testing.T) {
f: 1,
},
want: []ObservedMessage{
{SeqNr: 1, MsgData: MsgData{TokenData: [][]byte{{0x1}}}},
{SeqNr: 1, MsgData: MsgData{TokenData: [][]byte{{0x3}}}},
},
},
}
Expand Down
17 changes: 13 additions & 4 deletions core/services/ocr2/plugins/ccip/internal/hashlib/common.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package hashlib

import (
"strconv"

"github.com/smartcontractkit/chainlink/v2/core/utils"
)

Expand All @@ -10,9 +12,16 @@ func BytesOfBytesKeccak(b [][]byte) ([32]byte, error) {
return [32]byte{}, nil
}

h := utils.Keccak256Fixed(b[0])
for _, v := range b[1:] {
h = utils.Keccak256Fixed(append(h[:], v...))
joinedBytes := make([]byte, 0)
joinedBytes = append(joinedBytes, intToBytes(int64(len(b)))...)
for i := range b {
joinedBytes = append(joinedBytes, intToBytes(int64(len(b[i])))...)
joinedBytes = append(joinedBytes, b[i]...)
}
return h, nil

return utils.Keccak256Fixed(joinedBytes), nil
}

func intToBytes(v int64) []byte {
return []byte(strconv.FormatInt(v, 10))
}
39 changes: 30 additions & 9 deletions core/services/ocr2/plugins/ccip/internal/hashlib/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,37 @@ import (
"testing"

"github.com/stretchr/testify/assert"

"github.com/smartcontractkit/chainlink/v2/core/utils"
)

func TestBytesOfBytesKeccak(t *testing.T) {
h, err := BytesOfBytesKeccak(nil)
assert.NoError(t, err)
assert.Equal(t, [32]byte{}, h)

h1, err := BytesOfBytesKeccak([][]byte{{0x1}, {0x1}})
assert.NoError(t, err)
h2, err := BytesOfBytesKeccak([][]byte{{0x1, 0x1}})
assert.NoError(t, err)
assert.NotEqual(t, h1, h2)
t.Run("simple case", func(t *testing.T) {
h, err := BytesOfBytesKeccak(nil)
assert.NoError(t, err)
assert.Equal(t, [32]byte{}, h)

h1, err := BytesOfBytesKeccak([][]byte{{0x1}, {0x1}})
assert.NoError(t, err)
h2, err := BytesOfBytesKeccak([][]byte{{0x1, 0x1}})
assert.NoError(t, err)
assert.NotEqual(t, h1, h2)
})

t.Run("should not have collision", func(t *testing.T) {
s1 := utils.RandomBytes32()
s2 := utils.RandomBytes32()

hs1, err := BytesOfBytesKeccak([][]byte{s1[:]})
assert.NoError(t, err)

h1, err := BytesOfBytesKeccak([][]byte{s1[:], s2[:]})
assert.NoError(t, err)

h2, err := BytesOfBytesKeccak([][]byte{append(hs1[:], s2[:]...)})
assert.NoError(t, err)

assert.NotEqual(t, h1, h2)
})

}

0 comments on commit e1fb3ba

Please sign in to comment.