Skip to content

Commit

Permalink
offchain - json marshal fix for generic addresses (#546)
Browse files Browse the repository at this point in the history
# Motivation
The `common.Address` json representation is all in lower-case while the
new `cciptypes.Address` is eip55.
This leads to some incompatibility issues and nodes not reaching
consensus due to seeing different results.

# Solution
Make cciptypes.Address json marshal/unmarshal behave similar to
common.ADdress
  • Loading branch information
dimkouv authored Feb 22, 2024
1 parent 761560c commit 15fa388
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/services/ocr2/plugins/ccip/cciptypes/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,29 @@ package cciptypes

import (
"encoding/hex"
"fmt"
"strings"

"github.com/ethereum/go-ethereum/common"
)

type Address string

// TODO: make JSON marshal/unmarshal non-evm specific.
// Make sure we have casing compatibility with old versions.
func (a *Address) UnmarshalJSON(bytes []byte) error {
vStr := strings.Trim(string(bytes), `"`)
if !common.IsHexAddress(vStr) {
return fmt.Errorf("invalid address: %s", vStr)
}
*a = Address(common.HexToAddress(vStr).String())
return nil
}

func (a *Address) MarshalJSON() ([]byte, error) {
return []byte(`"` + strings.ToLower(string(*a)) + `"`), nil
}

type Hash [32]byte

func (h Hash) String() string {
Expand Down
33 changes: 33 additions & 0 deletions core/services/ocr2/plugins/ccip/cciptypes/models_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package cciptypes

import (
"encoding/json"
"fmt"
"strings"
"testing"

"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/assert"

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

func TestHash_String(t *testing.T) {
Expand Down Expand Up @@ -34,3 +42,28 @@ func TestHash_String(t *testing.T) {
})
}
}

func TestAddress_JSON(t *testing.T) {
addr1 := utils.RandomAddress()

addrArr := []Address{Address(addr1.String())}
evmAddrArr := []common.Address{addr1}

b, err := json.Marshal(addrArr)
assert.NoError(t, err)
assert.Equal(t, fmt.Sprintf(`["%s"]`, strings.ToLower(addr1.String())), string(b))

b2, err := json.Marshal(evmAddrArr)
assert.NoError(t, err)
assert.Equal(t, string(b), string(b2), "marshal should produce the same result for common.Address and cciptypes.Address")

var unmarshalledAddr []Address
err = json.Unmarshal(b, &unmarshalledAddr)
assert.NoError(t, err)
assert.Equal(t, addrArr[0], unmarshalledAddr[0])

var unmarshalledEvmAddr []common.Address
err = json.Unmarshal(b, &unmarshalledEvmAddr)
assert.NoError(t, err)
assert.Equal(t, evmAddrArr[0], unmarshalledEvmAddr[0])
}

0 comments on commit 15fa388

Please sign in to comment.