Skip to content

Commit

Permalink
chore(eth): minor optimisation in EthHashFromCid
Browse files Browse the repository at this point in the history
  • Loading branch information
rvagg committed Sep 13, 2024
1 parent 6c63df6 commit cadc89d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion chain/types/ethtypes/eth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,13 @@ func handleHexStringPrefix(s string) string {
}

func EthHashFromCid(c cid.Cid) (EthHash, error) {
return ParseEthHash(c.Hash().HexString()[8:])
b := c.Hash()
if len(b) != EthHashLength+4 {
return EthHash{}, fmt.Errorf("CID hash length is not 32 bytes")
}
var h EthHash
copy(h[:], b[4:])
return h, nil
}

func ParseEthHash(s string) (EthHash, error) {
Expand Down
21 changes: 21 additions & 0 deletions chain/types/ethtypes/eth_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strings"
"testing"

"github.com/ipfs/go-cid"
"github.com/stretchr/testify/require"

"github.com/filecoin-project/go-address"
Expand Down Expand Up @@ -105,6 +106,15 @@ func TestEthHash(t *testing.T) {
require.NoError(t, err)
require.Equal(t, hash, string(jm))
}

_, err := EthHashFromCid(cid.Undef)
require.ErrorContains(t, err, "not 32 bytes")

_, err = EthHashFromCid(cid.MustParse("bafkqaaa"))
require.ErrorContains(t, err, "not 32 bytes")

_, err = EthHashFromCid(cid.MustParse("bafyrgqhai26anf3i7pips7q22coa4sz2fr4gk4q4sqdtymvvjyginfzaqewveaeqdh524nsktaq43j65v22xxrybrtertmcfxufdam3da3hbk"))
require.ErrorContains(t, err, "not 32 bytes")
}

func TestEthFilterID(t *testing.T) {
Expand Down Expand Up @@ -525,3 +535,14 @@ func TestFilecoinAddressToEthAddressParams(t *testing.T) {
func stringPtr(s string) *string {
return &s
}

func BenchmarkEthHashFromCid(b *testing.B) {
c := cid.MustParse("bafy2bzacedwviarjtjraqakob5pslltmuo5n3xev3nt5zylezofkbbv5jclyu")

for i := 0; i < b.N; i++ {
_, err := EthHashFromCid(c)
if err != nil {
b.Fatalf("Error in EthHashFromCid: %v", err)
}
}
}

0 comments on commit cadc89d

Please sign in to comment.