Skip to content

Commit

Permalink
Merge pull request erigontech#4 from calmbeing/bep-171
Browse files Browse the repository at this point in the history
Support bep-171: add ics23 proof support for cross chain packages
  • Loading branch information
setunapo authored Mar 17, 2023
2 parents 996f742 + 39fe0bd commit 468b4a7
Show file tree
Hide file tree
Showing 11 changed files with 502 additions and 49 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/bind/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1849,7 +1849,7 @@ func TestGolangBindings(t *testing.T) {
t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out)
}

replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/tendermint/[email protected]", "-replace", "github.com/tendermint/tendermint=github.com/bnb-chain/[email protected].12") // Repo root
replacer = exec.Command(gocmd, "mod", "edit", "-x", "-require", "github.com/tendermint/[email protected]", "-replace", "github.com/tendermint/tendermint=github.com/bnb-chain/[email protected].15") // Repo root
replacer.Dir = pkg
if out, err := replacer.CombinedOutput(); err != nil {
t.Fatalf("failed to replace tendermint dependency to bnb-chain source: %v\n%s", err, out)
Expand Down
76 changes: 75 additions & 1 deletion core/systemcontracts/upgrade.go

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions core/vm/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,23 @@ var PrecompiledContractsBLS = map[libcommon.Address]PrecompiledContract{
libcommon.BytesToAddress([]byte{18}): &bls12381MapG2{},
}

var PrecompiledContractsPlanck = map[libcommon.Address]PrecompiledContract{
libcommon.BytesToAddress([]byte{1}): &ecrecover{},
libcommon.BytesToAddress([]byte{2}): &sha256hash{},
libcommon.BytesToAddress([]byte{3}): &ripemd160hash{},
libcommon.BytesToAddress([]byte{4}): &dataCopy{},
libcommon.BytesToAddress([]byte{5}): &bigModExp{},
libcommon.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
libcommon.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
libcommon.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
libcommon.BytesToAddress([]byte{9}): &blake2F{},

libcommon.BytesToAddress([]byte{100}): &tmHeaderValidate{},
libcommon.BytesToAddress([]byte{101}): &iavlMerkleProofValidatePlanck{},
}

var (
PrecompiledAddressesPlanck []libcommon.Address
PrecompiledAddressesMoran []libcommon.Address
PrecompiledAddressesNano []libcommon.Address
PrecompiledAddressesBerlin []libcommon.Address
Expand Down Expand Up @@ -187,11 +203,16 @@ func init() {
for k := range PrecompiledContractsIsMoran {
PrecompiledAddressesMoran = append(PrecompiledAddressesMoran, k)
}
for k := range PrecompiledContractsPlanck {
PrecompiledAddressesPlanck = append(PrecompiledAddressesPlanck, k)
}
}

// ActivePrecompiles returns the precompiles enabled with the current configuration.
func ActivePrecompiles(rules *chain.Rules) []libcommon.Address {
switch {
case rules.IsPlanck:
return PrecompiledAddressesPlanck
case rules.IsMoran:
return PrecompiledAddressesMoran
case rules.IsNano:
Expand Down
90 changes: 86 additions & 4 deletions core/vm/contracts_lightclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package vm
import (
"encoding/binary"
"fmt"
"net/url"
"strings"

"github.com/ledgerwatch/erigon/core/vm/lightclient/iavl"
cmn "github.com/tendermint/tendermint/libs/common"

Expand Down Expand Up @@ -152,8 +155,38 @@ func (c *iavlMerkleProofValidateMoran) Run(input []byte) (result []byte, err err
return c.basicIavlMerkleProofValidate.Run(input)
}

type iavlMerkleProofValidatePlanck struct {
basicIavlMerkleProofValidate
}

func (c *iavlMerkleProofValidatePlanck) RequiredGas(_ []byte) uint64 {
return params.IAVLMerkleProofValidateGas
}

func (c *iavlMerkleProofValidatePlanck) Run(input []byte) (result []byte, err error) {
c.basicIavlMerkleProofValidate.proofRuntime = lightclient.Ics23CompatibleProofRuntime()
c.basicIavlMerkleProofValidate.verifiers = []merkle.ProofOpVerifier{
forbiddenAbsenceOpVerifier,
singleValueOpVerifier,
multiStoreOpVerifier,
forbiddenSimpleValueOpVerifier,
}
c.basicIavlMerkleProofValidate.keyVerifier = keyVerifier
c.basicIavlMerkleProofValidate.opsVerifier = proofOpsVerifier
return c.basicIavlMerkleProofValidate.Run(input)
}

func successfulMerkleResult() []byte {
result := make([]byte, merkleProofValidateResultLength)
binary.BigEndian.PutUint64(result[merkleProofValidateResultLength-uint64TypeLength:], 0x01)
return result
}

type basicIavlMerkleProofValidate struct {
verifiers []merkle.ProofOpVerifier
keyVerifier lightclient.KeyVerifier
opsVerifier merkle.ProofOpsVerifier
verifiers []merkle.ProofOpVerifier
proofRuntime *merkle.ProofRuntime
}

func (c *basicIavlMerkleProofValidate) Run(input []byte) (result []byte, err error) {
Expand All @@ -177,15 +210,21 @@ func (c *basicIavlMerkleProofValidate) Run(input []byte) (result []byte, err err
return nil, err
}

if c.proofRuntime == nil {
kvmp.SetProofRuntime(lightclient.DefaultProofRuntime())
} else {
kvmp.SetProofRuntime(c.proofRuntime)
}
kvmp.SetVerifiers(c.verifiers)
kvmp.SetOpsVerifier(c.opsVerifier)
kvmp.SetKeyVerifier(c.keyVerifier)

valid := kvmp.Validate()
if !valid {
return nil, fmt.Errorf("invalid merkle proof")
}

result = make([]byte, merkleProofValidateResultLength)
binary.BigEndian.PutUint64(result[merkleProofValidateResultLength-uint64TypeLength:], 0x01)
return result, nil
return successfulMerkleResult(), nil
}
func forbiddenAbsenceOpVerifier(op merkle.ProofOperator) error {
if op == nil {
Expand Down Expand Up @@ -240,3 +279,46 @@ func singleValueOpVerifier(op merkle.ProofOperator) error {
}
return nil
}

func proofOpsVerifier(poz merkle.ProofOperators) error {
if len(poz) != 2 {
return cmn.NewError("proof ops should be 2")
}

// for legacy proof type
if _, ok := poz[1].(lightclient.MultiStoreProofOp); ok {
if _, ok := poz[0].(iavl.IAVLValueOp); !ok {
return cmn.NewError("invalid proof op")
}
return nil
}

// for ics23 proof type
if op2, ok := poz[1].(lightclient.CommitmentOp); ok {
if op2.Type != lightclient.ProofOpSimpleMerkleCommitment {
return cmn.NewError("invalid proof op")
}

op1, ok := poz[0].(lightclient.CommitmentOp)
if !ok {
return cmn.NewError("invalid proof op")
}

if op1.Type != lightclient.ProofOpIAVLCommitment {
return cmn.NewError("invalid proof op")
}
return nil
}

return cmn.NewError("invalid proof type")
}

func keyVerifier(key string) error {
// https://github.com/bnb-chain/tendermint/blob/72375a6f3d4a72831cc65e73363db89a0073db38/crypto/merkle/proof_key_path.go#L88
// since the upper function is ambiguous, `x:00` can be decoded to both kind of key type
// we check the key here to make sure the key will not start from `x:`
if strings.HasPrefix(url.PathEscape(key), "x:") {
return cmn.NewError("key should not start with x:")
}
return nil
}
118 changes: 117 additions & 1 deletion core/vm/contracts_lightclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ package vm
import (
"encoding/binary"
"encoding/hex"
"github.com/stretchr/testify/assert"
"testing"

"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/crypto/merkle"
cmn "github.com/tendermint/tendermint/libs/common"

"github.com/stretchr/testify/require"

"github.com/ledgerwatch/erigon/core/vm/lightclient"
"github.com/ledgerwatch/erigon/core/vm/lightclient/iavl"
)

const (
Expand Down Expand Up @@ -113,6 +117,43 @@ func TestTmHeaderValidateAndMerkleProofValidate(t *testing.T) {
require.Equal(t, expectedResult, success)
}

func TestIcs23Proof(t *testing.T) {
appHash, err := hex.DecodeString("ae6d1123fc362b3297bfb19c9f9fabbcbd1e2555b923dead261905b8a2ff6db6")
require.NoError(t, err)
key, err := hex.DecodeString("77696e64")
require.NoError(t, err)
value, err := hex.DecodeString("626c6f7773")
require.NoError(t, err)
proofBytes, err := hex.DecodeString("0a300a0a69637332333a6961766c120477696e641a1c0a1a0a0477696e641205626c6f77731a0b0801180120012a030002040a9d010a0c69637332333a73696d706c6512036962631a87010a84010a036962631220141acb8632cfb808f293f2649cb9aabaca74fc18640900ffd0d48e2994b2a1521a090801180120012a0100222708011201011a205f0ba08283de309300409486e978a3ea59d82bccc838b07c7d39bd87c16a5034222708011201011a20455b81ef5591150bd24d3e57a769f65518b16de93487f0fab02271b3d69e2852")
require.NoError(t, err)

merkleProofInput := make([]byte, 32+32+len(key)+32+len(value)+32+len(proofBytes))
copy(merkleProofInput[:32], "ibc")
binary.BigEndian.PutUint64(merkleProofInput[32+24:32+32], uint64(len(key)))
copy(merkleProofInput[32+32:32+32+len(key)], key)

binary.BigEndian.PutUint64(merkleProofInput[32+32+len(key)+24:32+32+len(key)+32], uint64(len(value)))
copy(merkleProofInput[32+32+len(key)+32:32+32+len(key)+32+len(value)], value)

copy(merkleProofInput[32+32+len(key)+32+len(value):32+32+len(key)+32+len(value)+32], appHash)
copy(merkleProofInput[32+32+len(key)+32+len(value)+32:], proofBytes)

totalLengthPrefix := make([]byte, 32)
binary.BigEndian.PutUint64(totalLengthPrefix[0:8], 0)
binary.BigEndian.PutUint64(totalLengthPrefix[8:16], 0)
binary.BigEndian.PutUint64(totalLengthPrefix[16:24], 0)
binary.BigEndian.PutUint64(totalLengthPrefix[24:], uint64(len(merkleProofInput)))

input := append(totalLengthPrefix, merkleProofInput...)

validator := iavlMerkleProofValidatePlanck{}
success, err := validator.Run(input)
require.NoError(t, err)
expectedResult := make([]byte, 32)
binary.BigEndian.PutUint64(expectedResult[24:], 0x01)
require.Equal(t, expectedResult, success)
}

func TestMerkleProofValidateMoran(t *testing.T) {
// Bytest1 is the inputs of exploit tx 0x05356fd06ce56a9ec5b4eaf9c075abd740cae4c21eab1676440ab5cd2fe5c57a
bytest1, _ := hex.DecodeString("00000000000000000000000000000000000000000000000000000000000005086962630000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e00000100380200000000010dd9ac0000000000000000000000000000000000000000000000000000000000000093000000000000000000000000000000000000000000000000000000000000000000f870a0424e4200000000000000000000000000000000000000000000000000000000009400000000000000000000000000000000000000008ad3c21bcecceda100000094489a8756c18c0b8b24ec2a2b9ff3d4d447f79bec94489a8756c18c0b8b24ec2a2b9ff3d4d447f79bec846553f10072cda827a83531ca0fd7ac917a6b65649719aab0836722caafe0603147a523180a8d020a066961766c3a76120e00000100380200000000010dd9ac1af201f0010aed010a2b0802100318b091c73422200c10f902d266c238a4ca9e26fa9bc36483cd3ebee4e263012f5e7f40c22ee4d20a4d0801100218b091c7342220e4fd47bffd1c06e67edad92b2bf9ca63631978676288a2aa99f95c459436ef632a20121a1f9c4eca726c725796c5375fc4158986ced08e498dc8268ef94d8ed1891612001a370a0e0000010038020000000000000002122011056c6919f02d966991c10721684a8d1542e44003f9ffb47032c18995d4ac7f18b091c7341a340a0e00000100380200000000010dd9ac12202c3a561458f8527b002b5ec3cab2d308662798d6245d4588a4e6a80ebdfe30ac18010ad4050a0a6d756c746973746f726512036962631ac005be050abb050a110a066f7261636c6512070a0508b891c7340a0f0a046d61696e12070a0508b891c7340a350a08736c617368696e6712290a2708b891c7341220c8ccf341e6e695e7e1cb0ce4bf347eea0cc16947d8b4e934ec400b57c59d6f860a380a0b61746f6d69635f7377617012290a2708b891c734122042d4ecc9468f71a70288a95d46564bfcaf2c9f811051dcc5593dbef152976b010a110a0662726964676512070a0508b891c7340a300a0364657812290a2708b891c73412201773be443c27f61075cecdc050ce22eb4990c54679089e90afdc4e0e88182a230a2f0a02736312290a2708b891c7341220df7a0484b7244f76861b1642cfb7a61d923794bd2e076c8dbd05fc4ee29f3a670a330a06746f6b656e7312290a2708b891c734122064958c2f76fec1fa5d1828296e51264c259fa264f499724795a740f48fc4731b0a320a057374616b6512290a2708b891c734122015d2c302143bdf029d58fe381cc3b54cedf77ecb8834dfc5dc3e1555d68f19ab0a330a06706172616d7312290a2708b891c734122050abddcb7c115123a5a4247613ab39e6ba935a3d4f4b9123c4fedfa0895c040a0a300a0361636312290a2708b891c734122079fb5aecc4a9b87e56231103affa5e515a1bdf3d0366490a73e087980b7f1f260a0e0a0376616c12070a0508b891c7340a300a0369626312290a2708b891c7341220e09159530585455058cf1785f411ea44230f39334e6e0f6a3c54dbf069df2b620a300a03676f7612290a2708b891c7341220db85ddd37470983b14186e975a175dfb0bf301b43de685ced0aef18d28b4e0420a320a05706169727312290a2708b891c7341220a78b556bc9e73d86b4c63ceaf146db71b12ac80e4c10dd0ce6eb09c99b0c7cfe0a360a0974696d655f6c6f636b12290a2708b891c73412204775dbe01d41cab018c21ba5c2af94720e4d7119baf693670e70a40ba2a52143")
Expand Down Expand Up @@ -195,3 +236,78 @@ func TestMultiStore(t *testing.T) {
err = multiStoreOpVerifier(badProof)
assert.Error(t, err, "duplicated store")
}

func TestProofOpsVerifier(t *testing.T) {
tests := []struct {
ops merkle.ProofOperators
err error
}{
{
merkle.ProofOperators{
iavl.IAVLValueOp{},
},
cmn.NewError("proof ops should be 2"),
},
{
merkle.ProofOperators{
lightclient.MultiStoreProofOp{},
lightclient.MultiStoreProofOp{},
},
cmn.NewError("invalid proof op"),
},
{
merkle.ProofOperators{
iavl.IAVLValueOp{},
lightclient.MultiStoreProofOp{},
},
nil,
},
{
merkle.ProofOperators{
lightclient.CommitmentOp{Type: lightclient.ProofOpIAVLCommitment},
lightclient.CommitmentOp{Type: lightclient.ProofOpSimpleMerkleCommitment},
},
nil,
},
{
merkle.ProofOperators{
lightclient.CommitmentOp{Type: lightclient.ProofOpSimpleMerkleCommitment},
lightclient.CommitmentOp{Type: lightclient.ProofOpSimpleMerkleCommitment},
},
cmn.NewError("invalid proof op"),
},
{
merkle.ProofOperators{
lightclient.MultiStoreProofOp{},
iavl.IAVLValueOp{},
},
cmn.NewError("invalid proof type"),
},
}

for _, testCase := range tests {
err := proofOpsVerifier(testCase.ops)
assert.Equal(t, err, testCase.err)
}
}

func TestKeyVerifier(t *testing.T) {
tests := []struct {
key string
err error
}{
{
"x:sdfdfdsd",
cmn.NewError("key should not start with x:"),
},
{
"sdfxdfxs",
nil,
},
}

for _, testCase := range tests {
err := keyVerifier(testCase.key)
assert.Equal(t, err, testCase.err)
}
}
2 changes: 2 additions & 0 deletions core/vm/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ var emptyCodeHash = crypto.Keccak256Hash(nil)
func (evm *EVM) precompile(addr libcommon.Address) (PrecompiledContract, bool) {
var precompiles map[libcommon.Address]PrecompiledContract
switch {
case evm.chainRules.IsPlanck:
precompiles = PrecompiledContractsPlanck
case evm.chainRules.IsMoran:
precompiles = PrecompiledContractsIsMoran
case evm.chainRules.IsNano:
Expand Down
Loading

0 comments on commit 468b4a7

Please sign in to comment.