Skip to content

Commit

Permalink
Eth JSON-RPC: use ToFilecoinAddress() to get f4 addr and validate v s…
Browse files Browse the repository at this point in the history
…ig + cleanups (#9970)

Co-authored-by: raulk <raul@protocol.ai>
  • Loading branch information
ychiaoli18 and raulk authored Jan 12, 2023
1 parent c61edd1 commit 105a125
Show file tree
Hide file tree
Showing 15 changed files with 141 additions and 114 deletions.
8 changes: 4 additions & 4 deletions api/docgen/docgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,10 +375,10 @@ func init() {

addExample(ethint)
addExample(&ethint)
ethaddr, _ := ethtypes.EthAddressFromHex("0x5CbEeCF99d3fDB3f25E309Cc264f240bb0664031")
ethaddr, _ := ethtypes.ParseEthAddress("0x5CbEeCF99d3fDB3f25E309Cc264f240bb0664031")
addExample(ethaddr)
addExample(&ethaddr)
ethhash, _ := ethtypes.NewEthHashFromCid(c)
ethhash, _ := ethtypes.EthHashFromCid(c)
addExample(ethhash)
addExample(&ethhash)

Expand All @@ -387,10 +387,10 @@ func init() {

addExample(&uuid.UUID{})

filterid, _ := ethtypes.NewEthHashFromHex("0x5CbEeC012345673f25E309Cc264f240bb0664031")
filterid, _ := ethtypes.ParseEthHash("0x5CbEeC012345673f25E309Cc264f240bb0664031")
addExample(ethtypes.EthFilterID(filterid))

subid, _ := ethtypes.NewEthHashFromHex("0x5CbEeCF99d3fDB301234567c264f240bb0664031")
subid, _ := ethtypes.ParseEthHash("0x5CbEeCF99d3fDB301234567c264f240bb0664031")
addExample(ethtypes.EthSubscriptionID(subid))

pstring := func(s string) *string { return &s }
Expand Down
2 changes: 1 addition & 1 deletion chain/gen/genesis/genesis_eth.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func SetupEthNullAddresses(ctx context.Context, st *state.StateTree, nv network.

var ethAddresses []ethtypes.EthAddress
for _, addr := range EthNullAddresses {
a, err := ethtypes.EthAddressFromHex(addr)
a, err := ethtypes.ParseEthAddress(addr)
if err != nil {
return nil, xerrors.Errorf("failed to represent the 0x0 as an EthAddress: %w", err)
}
Expand Down
16 changes: 14 additions & 2 deletions chain/types/ethtypes/eth_transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,12 @@ func (tx *EthTxArgs) Sender() (address.Address, error) {
return address.Undef, err
}

return address.NewDelegatedAddress(builtintypes.EthereumAddressManagerActorID, ethAddr)
ea, err := CastEthAddress(ethAddr)
if err != nil {
return address.Undef, err
}

return ea.ToFilecoinAddress()
}

func RecoverSignature(sig typescrypto.Signature) (r, s, v EthBigInt, err error) {
Expand Down Expand Up @@ -445,6 +450,13 @@ func parseEip1559Tx(data []byte) (*EthTxArgs, error) {
return nil, err
}

// EIP-1559 and EIP-2930 transactions only support 0 or 1 for v
// Legacy and EIP-155 transactions support other values
// https://github.com/ethers-io/ethers.js/blob/56fabe987bb8c1e4891fdf1e5d3fe8a4c0471751/packages/transactions/src.ts/index.ts#L333
if !v.Equals(big.NewInt(0)) && !v.Equals(big.NewInt(1)) {
return nil, fmt.Errorf("EIP-1559 transactions only support 0 or 1 for v")
}

args := EthTxArgs{
ChainID: chainId,
Nonce: nonce,
Expand Down Expand Up @@ -575,7 +587,7 @@ func parseEthAddr(v interface{}) (*EthAddress, error) {
if len(b) == 0 {
return nil, nil
}
addr, err := EthAddressFromBytes(b)
addr, err := CastEthAddress(b)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion chain/types/ethtypes/eth_transactions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func TestDelegatedSigner(t *testing.T) {
addrHash, err := EthAddressFromPubKey(pubk)
require.NoError(t, err)

from, err := address.NewDelegatedAddress(builtintypes.EthereumAddressManagerActorID, addrHash[12:])
from, err := address.NewDelegatedAddress(builtintypes.EthereumAddressManagerActorID, addrHash)
require.NoError(t, err)

sig := append(r, s...)
Expand Down
125 changes: 63 additions & 62 deletions chain/types/ethtypes/eth_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"strings"

"github.com/ipfs/go-cid"
"github.com/minio/blake2b-simd"
"github.com/multiformats/go-multihash"
"github.com/multiformats/go-varint"
"golang.org/x/crypto/sha3"
Expand Down Expand Up @@ -228,6 +227,62 @@ func (n *EthNonce) UnmarshalJSON(b []byte) error {

type EthAddress [EthAddressLength]byte

// EthAddressFromPubKey returns the Ethereum address corresponding to an
// uncompressed secp256k1 public key.
func EthAddressFromPubKey(pubk []byte) ([]byte, error) {
// if we get an uncompressed public key (that's what we get from the library,
// but putting this check here for defensiveness), strip the prefix
const pubKeyLen = 65
if len(pubk) != pubKeyLen {
return nil, fmt.Errorf("public key should have %d in length, but got %d", pubKeyLen, len(pubk))
}
if pubk[0] != 0x04 {
return nil, fmt.Errorf("expected first byte of secp256k1 to be 0x04 (uncompressed)")
}
pubk = pubk[1:]

// Calculate the Ethereum address based on the keccak hash of the pubkey.
hasher := sha3.NewLegacyKeccak256()
hasher.Write(pubk)
ethAddr := hasher.Sum(nil)[12:]
return ethAddr, nil
}

func EthAddressFromFilecoinAddress(addr address.Address) (EthAddress, error) {
ethAddr, ok, err := TryEthAddressFromFilecoinAddress(addr, true)
if err != nil {
return EthAddress{}, xerrors.Errorf("failed to try converting filecoin to eth addr: %w", err)
}

if !ok {
return EthAddress{}, xerrors.Errorf("failed to convert filecoin address %s to an equivalent eth address", addr)
}

return ethAddr, nil
}

// ParseEthAddress parses an Ethereum address from a hex string.
func ParseEthAddress(s string) (EthAddress, error) {
handlePrefix(&s)
b, err := decodeHexString(s, EthAddressLength)
if err != nil {
return EthAddress{}, err
}
var h EthAddress
copy(h[EthAddressLength-len(b):], b)
return h, nil
}

// CastEthAddress interprets bytes as an EthAddress, performing some basic checks.
func CastEthAddress(b []byte) (EthAddress, error) {
var a EthAddress
if len(b) != EthAddressLength {
return EthAddress{}, xerrors.Errorf("cannot parse bytes into an EthAddress: incorrect input length")
}
copy(a[:], b[:])
return a, nil
}

func (ea EthAddress) String() string {
return "0x" + hex.EncodeToString(ea[:])
}
Expand All @@ -241,7 +296,7 @@ func (ea *EthAddress) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &s); err != nil {
return err
}
addr, err := EthAddressFromHex(s)
addr, err := ParseEthAddress(s)
if err != nil {
return err
}
Expand Down Expand Up @@ -291,46 +346,13 @@ func TryEthAddressFromFilecoinAddress(addr address.Address, allowId bool) (EthAd
}
payload = payload[n:]
if namespace == builtintypes.EthereumAddressManagerActorID {
addr, err := EthAddressFromBytes(payload)
addr, err := CastEthAddress(payload)
return addr, err == nil, err
}
}
return EthAddress{}, false, nil
}

func EthAddressFromFilecoinAddress(addr address.Address) (EthAddress, error) {
ethAddr, ok, err := TryEthAddressFromFilecoinAddress(addr, true)
if err != nil {
return EthAddress{}, xerrors.Errorf("failed to try converting filecoin to eth addr: %w", err)
}

if !ok {
return EthAddress{}, xerrors.Errorf("failed to convert filecoin address %s to an equivalent eth address", addr)
}

return ethAddr, nil
}

func EthAddressFromHex(s string) (EthAddress, error) {
handlePrefix(&s)
b, err := decodeHexString(s, EthAddressLength)
if err != nil {
return EthAddress{}, err
}
var h EthAddress
copy(h[EthAddressLength-len(b):], b)
return h, nil
}

func EthAddressFromBytes(b []byte) (EthAddress, error) {
var a EthAddress
if len(b) != EthAddressLength {
return EthAddress{}, xerrors.Errorf("cannot parse bytes into an EthAddress: incorrect input length")
}
copy(a[:], b[:])
return a, nil
}

type EthHash [EthHashLength]byte

func (h EthHash) MarshalJSON() ([]byte, error) {
Expand All @@ -342,7 +364,7 @@ func (h *EthHash) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &s); err != nil {
return err
}
hash, err := NewEthHashFromHex(s)
hash, err := ParseEthHash(s)
if err != nil {
return err
}
Expand Down Expand Up @@ -372,11 +394,11 @@ func decodeHexString(s string, length int) ([]byte, error) {
return b, nil
}

func NewEthHashFromCid(c cid.Cid) (EthHash, error) {
return NewEthHashFromHex(c.Hash().HexString()[8:])
func EthHashFromCid(c cid.Cid) (EthHash, error) {
return ParseEthHash(c.Hash().HexString()[8:])
}

func NewEthHashFromHex(s string) (EthHash, error) {
func ParseEthHash(s string) (EthHash, error) {
handlePrefix(&s)
b, err := decodeHexString(s, EthHashLength)
if err != nil {
Expand All @@ -387,10 +409,6 @@ func NewEthHashFromHex(s string) (EthHash, error) {
return h, nil
}

func EthHashData(b []byte) EthHash {
return EthHash(blake2b.Sum256(b))
}

func (h EthHash) String() string {
return "0x" + hex.EncodeToString(h[:])
}
Expand Down Expand Up @@ -614,27 +632,10 @@ func GetContractEthAddressFromCode(sender EthAddress, salt [32]byte, initcode []
hasher.Write(salt[:])
hasher.Write(inithash)

ethAddr, err := EthAddressFromBytes(hasher.Sum(nil)[12:])
ethAddr, err := CastEthAddress(hasher.Sum(nil)[12:])
if err != nil {
return [20]byte{}, err
}

return ethAddr, nil
}

// EthAddressFromPubKey returns the Ethereum address corresponding to an
// uncompressed secp256k1 public key.
func EthAddressFromPubKey(pubk []byte) ([]byte, error) {
// if we get an uncompressed public key (that's what we get from the library,
// but putting this check here for defensiveness), strip the prefix
if pubk[0] != 0x04 {
return nil, fmt.Errorf("expected first byte of secp256k1 to be 0x04 (uncompressed)")
}
pubk = pubk[1:]

// Calculate the Ethereum address based on the keccak hash of the pubkey.
hasher := sha3.NewLegacyKeccak256()
hasher.Write(pubk)
ethAddr := hasher.Sum(nil)[12:]
return ethAddr, nil
}
22 changes: 11 additions & 11 deletions chain/types/ethtypes/eth_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func TestEthHash(t *testing.T) {
require.Equal(t, h.String(), strings.Replace(hash, `"`, "", -1))

c := h.ToCid()
h1, err := NewEthHashFromCid(c)
h1, err := EthHashFromCid(c)
require.Nil(t, err)
require.Equal(t, h, h1)
}
Expand Down Expand Up @@ -158,13 +158,13 @@ func TestUnmarshalEthBytes(t *testing.T) {
}

func TestEthFilterResultMarshalJSON(t *testing.T) {
hash1, err := NewEthHashFromHex("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
hash1, err := ParseEthHash("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
require.NoError(t, err, "eth hash")

hash2, err := NewEthHashFromHex("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
hash2, err := ParseEthHash("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
require.NoError(t, err, "eth hash")

addr, err := EthAddressFromHex("d4c5fb16488Aa48081296299d54b0c648C9333dA")
addr, err := ParseEthAddress("d4c5fb16488Aa48081296299d54b0c648C9333dA")
require.NoError(t, err, "eth address")

log := EthLog{
Expand Down Expand Up @@ -223,13 +223,13 @@ func TestEthFilterResultMarshalJSON(t *testing.T) {
}

func TestEthFilterSpecUnmarshalJSON(t *testing.T) {
hash1, err := NewEthHashFromHex("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
hash1, err := ParseEthHash("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
require.NoError(t, err, "eth hash")

hash2, err := NewEthHashFromHex("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
hash2, err := ParseEthHash("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
require.NoError(t, err, "eth hash")

addr, err := EthAddressFromHex("d4c5fb16488Aa48081296299d54b0c648C9333dA")
addr, err := ParseEthAddress("d4c5fb16488Aa48081296299d54b0c648C9333dA")
require.NoError(t, err, "eth address")

pstring := func(s string) *string { return &s }
Expand Down Expand Up @@ -305,10 +305,10 @@ func TestEthFilterSpecUnmarshalJSON(t *testing.T) {
}

func TestEthAddressListUnmarshalJSON(t *testing.T) {
addr1, err := EthAddressFromHex("d4c5fb16488Aa48081296299d54b0c648C9333dA")
addr1, err := ParseEthAddress("d4c5fb16488Aa48081296299d54b0c648C9333dA")
require.NoError(t, err, "eth address")

addr2, err := EthAddressFromHex("abbbfb16488Aa48081296299d54b0c648C9333dA")
addr2, err := ParseEthAddress("abbbfb16488Aa48081296299d54b0c648C9333dA")
require.NoError(t, err, "eth address")

testcases := []struct {
Expand Down Expand Up @@ -348,10 +348,10 @@ func TestEthAddressListUnmarshalJSON(t *testing.T) {
}

func TestEthHashListUnmarshalJSON(t *testing.T) {
hash1, err := NewEthHashFromHex("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
hash1, err := ParseEthHash("013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184")
require.NoError(t, err, "eth hash")

hash2, err := NewEthHashFromHex("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
hash2, err := ParseEthHash("ab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738")
require.NoError(t, err, "eth hash")

testcases := []struct {
Expand Down
8 changes: 6 additions & 2 deletions chain/wallet/key/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"golang.org/x/xerrors"

"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/crypto"

"github.com/filecoin-project/lotus/chain/types"
Expand Down Expand Up @@ -59,7 +58,12 @@ func NewKey(keyinfo types.KeyInfo) (*Key, error) {
return nil, xerrors.Errorf("failed to calculate Eth address from public key: %w", err)
}

k.Address, err = address.NewDelegatedAddress(builtin.EthereumAddressManagerActorID, ethAddr)
ea, err := ethtypes.CastEthAddress(ethAddr)
if err != nil {
return nil, xerrors.Errorf("failed to create ethereum address from bytes: %w", err)
}

k.Address, err = ea.ToFilecoinAddress()
if err != nil {
return nil, xerrors.Errorf("converting Delegated to address: %w", err)
}
Expand Down
Loading

0 comments on commit 105a125

Please sign in to comment.