diff options
Diffstat (limited to 'plugin')
-rw-r--r-- | plugin/evm/export_tx.go | 14 | ||||
-rw-r--r-- | plugin/evm/export_tx_test.go | 144 | ||||
-rw-r--r-- | plugin/evm/service.go | 9 | ||||
-rw-r--r-- | plugin/evm/tx.go | 31 | ||||
-rw-r--r-- | plugin/evm/vm.go | 54 | ||||
-rw-r--r-- | plugin/evm/vm_test.go | 141 |
6 files changed, 363 insertions, 30 deletions
diff --git a/plugin/evm/export_tx.go b/plugin/evm/export_tx.go index f210352..b76e312 100644 --- a/plugin/evm/export_tx.go +++ b/plugin/evm/export_tx.go @@ -56,6 +56,8 @@ func (tx *UnsignedExportTx) Verify( return errWrongChainID case !tx.DestinationChain.Equals(avmID): return errWrongChainID + case len(tx.Ins) == 0: + return errNoExportInputs case len(tx.ExportedOutputs) == 0: return errNoExportOutputs case tx.NetworkID != ctx.NetworkID: @@ -69,6 +71,9 @@ func (tx *UnsignedExportTx) Verify( return err } } + if !IsSortedAndUniqueEVMInputs(tx.Ins) { + return errInputsNotSortedAndUnique + } for _, out := range tx.ExportedOutputs { if err := out.Verify(); err != nil { @@ -160,7 +165,7 @@ func (tx *UnsignedExportTx) Accept(ctx *snow.Context, _ database.Batch) error { return ctx.SharedMemory.Put(tx.DestinationChain, elems) } -// Create a new transaction +// newExportTx returns a new ExportTx func (vm *VM) newExportTx( assetID ids.ID, // AssetID of the tokens to export amount uint64, // Amount of tokens to export @@ -183,14 +188,14 @@ func (vm *VM) newExportTx( toBurn = vm.txFee } // burn AVAX - ins, signers, err := vm.GetSpendableCanonical(keys, vm.ctx.AVAXAssetID, toBurn) + ins, signers, err := vm.GetSpendableFunds(keys, vm.ctx.AVAXAssetID, toBurn) if err != nil { return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err) } // burn non-AVAX if !assetID.Equals(vm.ctx.AVAXAssetID) { - ins2, signers2, err := vm.GetSpendableCanonical(keys, assetID, amount) + ins2, signers2, err := vm.GetSpendableFunds(keys, assetID, amount) if err != nil { return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err) } @@ -210,6 +215,9 @@ func (vm *VM) newExportTx( }, }} + avax.SortTransferableOutputs(exportOuts, vm.codec) + SortEVMInputsAndSigners(ins, signers) + // Create the transaction utx := &UnsignedExportTx{ NetworkID: vm.ctx.NetworkID, diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go new file mode 100644 index 0000000..2af123f --- /dev/null +++ b/plugin/evm/export_tx_test.go @@ -0,0 +1,144 @@ +// (c) 2019-2020, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "testing" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/crypto" + "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" +) + +func TestExportTxVerifyNil(t *testing.T) { + var exportTx UnsignedExportTx + if err := exportTx.Verify(testXChainID, NewContext(), testTxFee, testAvaxAssetID); err == nil { + t.Fatal("Verify should have failed due to nil transaction") + } +} + +func TestExportTxVerify(t *testing.T) { + var exportAmount uint64 = 10000000 + exportTx := &UnsignedExportTx{ + NetworkID: testNetworkID, + BlockchainID: testCChainID, + DestinationChain: testXChainID, + Ins: []EVMInput{ + { + Address: testEthAddrs[0], + Amount: exportAmount, + AssetID: testAvaxAssetID, + Nonce: 0, + }, + { + Address: testEthAddrs[2], + Amount: exportAmount, + AssetID: testAvaxAssetID, + Nonce: 0, + }, + }, + ExportedOutputs: []*avax.TransferableOutput{ + { + Asset: avax.Asset{ID: testAvaxAssetID}, + Out: &secp256k1fx.TransferOutput{ + Amt: exportAmount - testTxFee, + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: 0, + Threshold: 1, + Addrs: []ids.ShortID{testShortIDAddrs[0]}, + }, + }, + }, + { + Asset: avax.Asset{ID: testAvaxAssetID}, + Out: &secp256k1fx.TransferOutput{ + Amt: exportAmount, // only subtract fee from one output + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: 0, + Threshold: 1, + Addrs: []ids.ShortID{testShortIDAddrs[1]}, + }, + }, + }, + }, + } + + // Sort the inputs and outputs to ensure the transaction is canonical + avax.SortTransferableOutputs(exportTx.ExportedOutputs, Codec) + // Pass in a list of signers here with the appropriate length + // to avoid causing a nil-pointer error in the helper method + emptySigners := make([][]*crypto.PrivateKeySECP256K1R, 2) + SortEVMInputsAndSigners(exportTx.Ins, emptySigners) + + ctx := NewContext() + + // Test Valid Export Tx + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err != nil { + t.Fatalf("Failed to verify valid ExportTx: %w", err) + } + + exportTx.syntacticallyVerified = false + exportTx.NetworkID = testNetworkID + 1 + + // Test Incorrect Network ID Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to incorrect network ID") + } + + exportTx.syntacticallyVerified = false + exportTx.NetworkID = testNetworkID + exportTx.BlockchainID = nonExistentID + // Test Incorrect Blockchain ID Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to incorrect blockchain ID") + } + + exportTx.syntacticallyVerified = false + exportTx.BlockchainID = testCChainID + exportTx.DestinationChain = nonExistentID + // Test Incorrect Destination Chain ID Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to incorrect destination chain") + } + + exportTx.syntacticallyVerified = false + exportTx.DestinationChain = testXChainID + exportedOuts := exportTx.ExportedOutputs + exportTx.ExportedOutputs = nil + // Test No Exported Outputs Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to no exported outputs") + } + + exportTx.syntacticallyVerified = false + exportTx.ExportedOutputs = []*avax.TransferableOutput{exportedOuts[1], exportedOuts[0]} + // Test Unsorted outputs Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to no exported outputs") + } + + exportTx.syntacticallyVerified = false + exportTx.ExportedOutputs = exportedOuts + inputs := exportTx.Ins + exportTx.Ins = nil + // Test No Exported Outputs Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to no inputs") + } + + exportTx.syntacticallyVerified = false + exportTx.Ins = []EVMInput{inputs[1], inputs[0]} + // Test unsorted EVM Inputs Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to unsorted inputs") + } + + exportTx.syntacticallyVerified = false + exportTx.Ins = []EVMInput{inputs[0], inputs[0]} + // Test non-unique EVM Inputs Errors + if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err == nil { + t.Fatal("ExportTx should have failed verification due to non-unique inputs") + } +} diff --git a/plugin/evm/service.go b/plugin/evm/service.go index 8ede1b0..6c56631 100644 --- a/plugin/evm/service.go +++ b/plugin/evm/service.go @@ -151,7 +151,7 @@ type ExportKeyReply struct { func (service *AvaxAPI) ExportKey(r *http.Request, args *ExportKeyArgs, reply *ExportKeyReply) error { log.Info("EVM: ExportKey called") - address, err := service.vm.ParseEthAddress(args.Address) + address, err := ParseEthAddress(args.Address) if err != nil { return fmt.Errorf("couldn't parse %s to address: %s", args.Address, err) } @@ -200,10 +200,7 @@ func (service *AvaxAPI) ImportKey(r *http.Request, args *ImportKeyArgs, reply *a sk := skIntf.(*crypto.PrivateKeySECP256K1R) // TODO: return eth address here - reply.Address, err = service.vm.FormatEthAddress(GetEthAddress(sk)) - if err != nil { - return fmt.Errorf("problem formatting address: %w", err) - } + reply.Address = FormatEthAddress(GetEthAddress(sk)) db, err := service.vm.ctx.Keystore.GetDatabase(args.Username, args.Password) if err != nil { @@ -244,7 +241,7 @@ func (service *AvaxAPI) Import(_ *http.Request, args *ImportArgs, response *api. return fmt.Errorf("problem parsing chainID %q: %w", args.SourceChain, err) } - to, err := service.vm.ParseEthAddress(args.To) + to, err := ParseEthAddress(args.To) if err != nil { // Parse address return fmt.Errorf("couldn't parse argument 'to' to an address: %w", err) } diff --git a/plugin/evm/tx.go b/plugin/evm/tx.go index 9580bc0..fd52222 100644 --- a/plugin/evm/tx.go +++ b/plugin/evm/tx.go @@ -4,14 +4,17 @@ package evm import ( + "bytes" "errors" "fmt" + "sort" "github.com/ava-labs/coreth/core/state" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/codec" "github.com/ava-labs/avalanchego/utils/crypto" "github.com/ava-labs/avalanchego/utils/hashing" @@ -115,3 +118,31 @@ func (tx *Tx) Sign(c codec.Codec, signers [][]*crypto.PrivateKeySECP256K1R) erro tx.Initialize(unsignedBytes, signedBytes) return nil } + +// innerSortInputs implements sort.Interface for EVMInput +type innerSortInputs struct { + inputs []EVMInput + signers [][]*crypto.PrivateKeySECP256K1R +} + +func (ins *innerSortInputs) Less(i, j int) bool { + return bytes.Compare(ins.inputs[i].Address.Bytes(), ins.inputs[j].Address.Bytes()) < 0 +} + +func (ins *innerSortInputs) Len() int { return len(ins.inputs) } + +func (ins *innerSortInputs) Swap(i, j int) { + ins.inputs[j], ins.inputs[i] = ins.inputs[i], ins.inputs[j] + ins.signers[j], ins.signers[i] = ins.signers[i], ins.signers[j] +} + +// SortEVMInputsAndSigners sorts the list of EVMInputs based solely on the address of the input +func SortEVMInputsAndSigners(inputs []EVMInput, signers [][]*crypto.PrivateKeySECP256K1R) { + sort.Sort(&innerSortInputs{inputs: inputs, signers: signers}) +} + +// IsSortedAndUniqueEVMInputs returns true if the EVM Inputs are sorted and unique +// based on the account addresses +func IsSortedAndUniqueEVMInputs(inputs []EVMInput) bool { + return utils.IsSortedAndUnique(&innerSortInputs{inputs: inputs}) +} diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 9ad7411..bf43492 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -109,6 +109,8 @@ var ( errInsufficientFunds = errors.New("insufficient funds") errNoExportOutputs = errors.New("no export outputs") errOutputsNotSorted = errors.New("outputs not sorted") + errNoExportInputs = errors.New("no inputs to export") + errInputsNotSortedAndUnique = errors.New("inputs not sorted and unique") errOverflowExport = errors.New("overflow when computing export amount + txFee") errInvalidNonce = errors.New("invalid nonce") ) @@ -772,17 +774,6 @@ func (vm *VM) getLastAccepted() *Block { return vm.lastAccepted } -func (vm *VM) ParseEthAddress(addrStr string) (common.Address, error) { - if !common.IsHexAddress(addrStr) { - return common.Address{}, errInvalidAddr - } - return common.HexToAddress(addrStr), nil -} - -func (vm *VM) FormatEthAddress(addr common.Address) (string, error) { - return addr.Hex(), nil -} - // ParseAddress takes in an address and produces the ID of the chain it's for // the ID of the address func (vm *VM) ParseAddress(addrStr string) (ids.ID, ids.ShortID, error) { @@ -871,16 +862,11 @@ func (vm *VM) GetAtomicUTXOs( return utxos, lastAddrID, lastUTXOID, nil } -func GetEthAddress(privKey *crypto.PrivateKeySECP256K1R) common.Address { - return PublicKeyToEthAddress(privKey.PublicKey()) -} - -func PublicKeyToEthAddress(pubKey crypto.PublicKey) common.Address { - return ethcrypto.PubkeyToAddress( - (*pubKey.(*crypto.PublicKeySECP256K1R).ToECDSA())) -} - -func (vm *VM) GetSpendableCanonical(keys []*crypto.PrivateKeySECP256K1R, assetID ids.ID, amount uint64) ([]EVMInput, [][]*crypto.PrivateKeySECP256K1R, error) { +// GetSpendableFunds returns a list of EVMInputs and keys (in corresponding order) +// to total [amount] of [assetID] owned by [keys] +// TODO switch to returning a list of private keys +// since there are no multisig inputs in Ethereum +func (vm *VM) GetSpendableFunds(keys []*crypto.PrivateKeySECP256K1R, assetID ids.ID, amount uint64) ([]EVMInput, [][]*crypto.PrivateKeySECP256K1R, error) { // NOTE: should we use HEAD block or lastAccepted? state, err := vm.chain.BlockState(vm.lastAccepted.ethBlock) if err != nil { @@ -920,9 +906,11 @@ func (vm *VM) GetSpendableCanonical(keys []*crypto.PrivateKeySECP256K1R, assetID signers = append(signers, []*crypto.PrivateKeySECP256K1R{key}) amount -= balance } + if amount > 0 { return nil, nil, errInsufficientFunds } + return inputs, signers, nil } @@ -933,3 +921,27 @@ func (vm *VM) GetAcceptedNonce(address common.Address) (uint64, error) { } return state.GetNonce(address), nil } + +// ParseEthAddress parses [addrStr] and returns an Ethereum address +func ParseEthAddress(addrStr string) (common.Address, error) { + if !common.IsHexAddress(addrStr) { + return common.Address{}, errInvalidAddr + } + return common.HexToAddress(addrStr), nil +} + +// FormatEthAddress formats [addr] into a string +func FormatEthAddress(addr common.Address) string { + return addr.Hex() +} + +// GetEthAddress returns the ethereum address derived from [privKey] +func GetEthAddress(privKey *crypto.PrivateKeySECP256K1R) common.Address { + return PublicKeyToEthAddress(privKey.PublicKey()) +} + +// PublicKeyToEthAddress returns the ethereum address derived from [pubKey] +func PublicKeyToEthAddress(pubKey crypto.PublicKey) common.Address { + return ethcrypto.PubkeyToAddress( + (*pubKey.(*crypto.PublicKeySECP256K1R).ToECDSA())) +} diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go new file mode 100644 index 0000000..2002c93 --- /dev/null +++ b/plugin/evm/vm_test.go @@ -0,0 +1,141 @@ +// (c) 2019-2020, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package evm + +import ( + "encoding/json" + "testing" + + "github.com/ava-labs/avalanchego/api/keystore" + "github.com/ava-labs/avalanchego/chains/atomic" + "github.com/ava-labs/avalanchego/database/memdb" + "github.com/ava-labs/avalanchego/database/prefixdb" + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow" + engCommon "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/utils/crypto" + "github.com/ava-labs/avalanchego/utils/formatting" + "github.com/ava-labs/avalanchego/utils/logging" + "github.com/ava-labs/coreth/core" + "github.com/ethereum/go-ethereum/common" +) + +var ( + testNetworkID uint32 = 10 + testCChainID = ids.NewID([32]byte{'c', 'c', 'h', 'a', 'i', 'n', 't', 'e', 's', 't'}) + testXChainID = ids.NewID([32]byte{'t', 'e', 's', 't', 'x'}) + nonExistentID = ids.NewID([32]byte{'F'}) + testTxFee = uint64(1000) + startBalance = uint64(50000) + testKeys []*crypto.PrivateKeySECP256K1R + testEthAddrs []common.Address // testEthAddrs[i] corresponds to testKeys[i] + testShortIDAddrs []ids.ShortID + testAvaxAssetID = ids.NewID([32]byte{1, 2, 3}) + username = "Johns" + password = "CjasdjhiPeirbSenfeI13" // #nosec G101 + ethChainID uint32 = 43112 +) + +func init() { + cb58 := formatting.CB58{} + factory := crypto.FactorySECP256K1R{} + + for _, key := range []string{ + "24jUJ9vZexUM6expyMcT48LBx27k1m7xpraoV62oSQAHdziao5", + "2MMvUMsxx6zsHSNXJdFD8yc5XkancvwyKPwpw4xUK3TCGDuNBY", + "cxb7KpGWhDMALTjNNSJ7UQkkomPesyWAPUaWRGdyeBNzR6f35", + } { + _ = cb58.FromString(key) + pk, _ := factory.ToPrivateKey(cb58.Bytes) + secpKey := pk.(*crypto.PrivateKeySECP256K1R) + testKeys = append(testKeys, secpKey) + testEthAddrs = append(testEthAddrs, GetEthAddress(secpKey)) + testShortIDAddrs = append(testShortIDAddrs, pk.PublicKey().Address()) + } +} + +// BuildGenesisTest returns the genesis bytes for Coreth VM to be used in testing +func BuildGenesisTest(t *testing.T) []byte { + ss := StaticService{} + + genesisJSON := "{\"config\":{\"chainId\":43112,\"homesteadBlock\":0,\"daoForkBlock\":0,\"daoForkSupport\":true,\"eip150Block\":0,\"eip150Hash\":\"0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0\",\"eip155Block\":0,\"eip158Block\":0,\"byzantiumBlock\":0,\"constantinopleBlock\":0,\"petersburgBlock\":0,\"istanbulBlock\":0,\"muirGlacierBlock\":0},\"nonce\":\"0x0\",\"timestamp\":\"0x0\",\"extraData\":\"0x00\",\"gasLimit\":\"0x5f5e100\",\"difficulty\":\"0x0\",\"mixHash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"coinbase\":\"0x0000000000000000000000000000000000000000\",\"alloc\":{\"0100000000000000000000000000000000000000\":{\"code\":\"0x7300000000000000000000000000000000000000003014608060405260043610603d5760003560e01c80631e010439146042578063b6510bb314606e575b600080fd5b605c60048036036020811015605657600080fd5b503560b1565b60408051918252519081900360200190f35b818015607957600080fd5b5060af60048036036080811015608e57600080fd5b506001600160a01b03813516906020810135906040810135906060013560b6565b005b30cd90565b836001600160a01b031681836108fc8690811502906040516000604051808303818888878c8acf9550505050505015801560f4573d6000803e3d6000fd5b505050505056fea26469706673582212201eebce970fe3f5cb96bf8ac6ba5f5c133fc2908ae3dcd51082cfee8f583429d064736f6c634300060a0033\",\"balance\":\"0x0\"}},\"number\":\"0x0\",\"gasUsed\":\"0x0\",\"parentHash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\"}" + + genesis := &core.Genesis{} + if err := json.Unmarshal([]byte(genesisJSON), genesis); err != nil { + t.Fatalf("Problem unmarshaling genesis JSON: %w", err) + } + genesisReply, err := ss.BuildGenesis(nil, genesis) + if err != nil { + t.Fatalf("Failed to create test genesis") + } + return genesisReply.Bytes +} + +func NewContext() *snow.Context { + ctx := snow.DefaultContextTest() + ctx.NetworkID = testNetworkID + ctx.ChainID = testCChainID + ctx.AVAXAssetID = testAvaxAssetID + ctx.XChainID = ids.Empty.Prefix(0) + aliaser := ctx.BCLookup.(*ids.Aliaser) + aliaser.Alias(testCChainID, "C") + aliaser.Alias(testCChainID, testCChainID.String()) + aliaser.Alias(testXChainID, "X") + aliaser.Alias(testXChainID, testXChainID.String()) + + // SNLookup might be required here??? + return ctx +} + +// GenesisVM creates a VM instance with the genesis test bytes and returns +// the channel use to send messages to the engine, the vm, and atomic memory +func GenesisVM(t *testing.T) (chan engCommon.Message, *VM, *atomic.Memory) { + genesisBytes := BuildGenesisTest(t) + ctx := NewContext() + + baseDB := memdb.New() + + m := &atomic.Memory{} + m.Initialize(logging.NoLog{}, prefixdb.New([]byte{0}, baseDB)) + ctx.SharedMemory = m.NewSharedMemory(ctx.ChainID) + + // NB: this lock is intentionally left locked when this function returns. + // The caller of this function is responsible for unlocking. + ctx.Lock.Lock() + + userKeystore := keystore.CreateTestKeystore() + if err := userKeystore.AddUser(username, password); err != nil { + t.Fatal(err) + } + ctx.Keystore = userKeystore.NewBlockchainKeyStore(ctx.ChainID) + + issuer := make(chan engCommon.Message, 1) + vm := &VM{ + txFee: testTxFee, + } + err := vm.Initialize( + ctx, + prefixdb.New([]byte{1}, baseDB), + genesisBytes, + issuer, + []*engCommon.Fx{}, + ) + if err != nil { + t.Fatal(err) + } + + if err := vm.Bootstrapping(); err != nil { + t.Fatal(err) + } + + if err := vm.Bootstrapped(); err != nil { + t.Fatal(err) + } + + return issuer, vm, m +} + +func TestVMGenesis(t *testing.T) { + _, _, _ = GenesisVM(t) +} |