From 5b12d3fa21635145cb8a752b56477e22fca77a5b Mon Sep 17 00:00:00 2001 From: Dan Laine Date: Fri, 30 Oct 2020 12:55:53 -0400 Subject: remove these ID calls: Key(), Bytes(), Equals(), NewID(), IsZero() --- plugin/evm/vm.go | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 1f7e501..09e2ad5 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -309,7 +309,7 @@ func (vm *VM) Initialize( log.Trace("EVM sealed a block") blk := &Block{ - id: ids.NewID(block.Hash()), + id: ids.ID(block.Hash()), ethBlock: block, vm: vm, } @@ -318,7 +318,7 @@ func (vm *VM) Initialize( return errInvalidBlock } vm.newBlockChan <- blk - vm.updateStatus(ids.NewID(block.Hash()), choices.Processing) + vm.updateStatus(ids.ID(block.Hash()), choices.Processing) vm.txPoolStabilizedLock.Lock() vm.txPoolStabilizedHead = block.Hash() vm.txPoolStabilizedLock.Unlock() @@ -385,7 +385,7 @@ func (vm *VM) Initialize( lastAccepted = chain.GetGenesisBlock() } vm.lastAccepted = &Block{ - id: ids.NewID(lastAccepted.Hash()), + id: ids.ID(lastAccepted.Hash()), ethBlock: lastAccepted, vm: vm, } @@ -437,7 +437,7 @@ func (vm *VM) BuildBlock() (snowman.Block, error) { vm.blockDelayTimer.SetTimeoutIn(minBlockTime) vm.bdlock.Unlock() - log.Debug(fmt.Sprintf("built block 0x%x", block.ID().Bytes())) + log.Debug(fmt.Sprintf("built block %s", block.ID())) // make sure Tx Pool is updated <-vm.txPoolStabilizedOk return block, nil @@ -462,7 +462,7 @@ func (vm *VM) ParseBlock(b []byte) (snowman.Block, error) { return nil, errInvalidBlock } block := &Block{ - id: ids.NewID(blockHash), + id: ids.ID(blockHash), ethBlock: ethBlock, vm: vm, } @@ -484,7 +484,7 @@ func (vm *VM) GetBlock(id ids.ID) (snowman.Block, error) { // SetPreference sets what the current tail of the chain is func (vm *VM) SetPreference(blkID ids.ID) { - err := vm.chain.SetTail(blkID.Key()) + err := vm.chain.SetTail(common.Hash(blkID)) vm.ctx.Log.AssertNoError(err) } @@ -630,7 +630,7 @@ func (vm *VM) getCachedStatus(blockID ids.ID) choices.Status { if acceptedID, err := ids.ToID(acceptedIDBytes); err != nil { log.Error(fmt.Sprintf("snowman-eth: acceptedID bytes didn't match expected value: %s", err)) } else { - if acceptedID.Equals(blockID) { + if acceptedID == blockID { vm.blockStatusCache.Put(blockID, choices.Accepted) return choices.Accepted } @@ -641,14 +641,14 @@ func (vm *VM) getCachedStatus(blockID ids.ID) choices.Status { status := vm.getUncachedStatus(blk) if status == choices.Accepted { - err := vm.acceptedDB.Put(heightKey, blockID.Bytes()) + err := vm.acceptedDB.Put(heightKey, blockID[:]) if err != nil { log.Error(fmt.Sprintf("snowman-eth: failed to write back acceptedID bytes: %s", err)) } tempBlock := wrappedBlk for tempBlock.ethBlock != nil { - parentID := ids.NewID(tempBlock.ethBlock.ParentHash()) + parentID := ids.ID(tempBlock.ethBlock.ParentHash()) tempBlock = vm.getBlock(parentID) if tempBlock == nil || tempBlock.ethBlock == nil { break @@ -660,7 +660,7 @@ func (vm *VM) getCachedStatus(blockID ids.ID) choices.Status { break } - if err := vm.acceptedDB.Put(heightKey, parentID.Bytes()); err != nil { + if err := vm.acceptedDB.Put(heightKey, parentID[:]); err != nil { log.Error(fmt.Sprintf("snowman-eth: failed to write back acceptedID bytes: %s", err)) } } @@ -681,7 +681,7 @@ func (vm *VM) getUncachedStatus(blk *types.Block) choices.Status { highBlock, lowBlock = lowBlock, highBlock } for highBlock.Number().Cmp(lowBlock.Number()) > 0 { - parentBlock := vm.getBlock(ids.NewID(highBlock.ParentHash())) + parentBlock := vm.getBlock(ids.ID(highBlock.ParentHash())) if parentBlock == nil { return choices.Processing } @@ -702,12 +702,12 @@ func (vm *VM) getBlock(id ids.ID) *Block { if blockIntf, ok := vm.blockCache.Get(id); ok { return blockIntf.(*Block) } - ethBlock := vm.chain.GetBlockByHash(id.Key()) + ethBlock := vm.chain.GetBlockByHash(common.Hash(id)) if ethBlock == nil { return nil } block := &Block{ - id: ids.NewID(ethBlock.Hash()), + id: ids.ID(ethBlock.Hash()), ethBlock: ethBlock, vm: vm, } @@ -898,10 +898,10 @@ func (vm *VM) GetSpendableFunds(keys []*crypto.PrivateKeySECP256K1R, assetID ids } addr := GetEthAddress(key) var balance uint64 - if assetID.Equals(vm.ctx.AVAXAssetID) { + if assetID == vm.ctx.AVAXAssetID { balance = new(big.Int).Div(state.GetBalance(addr), x2cRate).Uint64() } else { - balance = state.GetBalanceMultiCoin(addr, assetID.Key()).Uint64() + balance = state.GetBalanceMultiCoin(addr, common.Hash(assetID)).Uint64() } if balance == 0 { continue -- cgit v1.2.3-70-g09d2 From c6fcd057903dc5ccc785b3a34fef534a4cb39d0a Mon Sep 17 00:00:00 2001 From: Dan Laine Date: Sun, 1 Nov 2020 18:24:33 -0500 Subject: remove id.Bytes() and ids.NewID --- plugin/evm/database.go | 2 +- plugin/evm/export_tx.go | 4 ++-- plugin/evm/import_tx_test.go | 18 +++++++++--------- plugin/evm/vm.go | 2 +- plugin/evm/vm_test.go | 8 ++++---- 5 files changed, 17 insertions(+), 17 deletions(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/database.go b/plugin/evm/database.go index 18890fa..fff18cb 100644 --- a/plugin/evm/database.go +++ b/plugin/evm/database.go @@ -53,7 +53,7 @@ func (db Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { // NewIteratorWithStart implements ethdb.Database func (db Database) NewIteratorWithStart(start []byte) ethdb.Iterator { - return db.NewIteratorWithStart(start) + return db.Database.NewIteratorWithStart(start) } // Batch implements ethdb.Batch diff --git a/plugin/evm/export_tx.go b/plugin/evm/export_tx.go index 74e36b6..0778d0a 100644 --- a/plugin/evm/export_tx.go +++ b/plugin/evm/export_tx.go @@ -155,9 +155,9 @@ func (tx *UnsignedExportTx) Accept(ctx *snow.Context, _ database.Batch) error { if err != nil { return err } - + utxoID := utxo.InputID() elem := &atomic.Element{ - Key: utxo.InputID().Bytes(), + Key: utxoID[:], Value: utxoBytes, } if out, ok := utxo.Out.(avax.Addressable); ok { diff --git a/plugin/evm/import_tx_test.go b/plugin/evm/import_tx_test.go index fcd18ac..52a8fa7 100644 --- a/plugin/evm/import_tx_test.go +++ b/plugin/evm/import_tx_test.go @@ -22,7 +22,7 @@ func TestImportTxVerifyNil(t *testing.T) { func TestImportTxVerify(t *testing.T) { var importAmount uint64 = 10000000 - txID := ids.NewID([32]byte{0xff}) + txID := [32]byte{0xff} importTx := &UnsignedImportTx{ NetworkID: testNetworkID, BlockchainID: testCChainID, @@ -134,12 +134,12 @@ func TestImportTxSemanticVerify(t *testing.T) { importAmount := uint64(1000000) utxoID := avax.UTXOID{ - TxID: ids.NewID([32]byte{ + TxID: [32]byte{ 0x0f, 0x2f, 0x4f, 0x6f, 0x8e, 0xae, 0xce, 0xee, 0x0d, 0x2d, 0x4d, 0x6d, 0x8c, 0xac, 0xcc, 0xec, 0x0b, 0x2b, 0x4b, 0x6b, 0x8a, 0xaa, 0xca, 0xea, 0x09, 0x29, 0x49, 0x69, 0x88, 0xa8, 0xc8, 0xe8, - }), + }, } utxo := &avax.UTXO{ @@ -203,9 +203,9 @@ func TestImportTxSemanticVerify(t *testing.T) { if err := unsignedImportTx.SemanticVerify(vm, tx); err != nil { t.Fatal("Should have failed to import non-existent UTXO") } - + inputID := utxo.InputID() if err := xChainSharedMemory.Put(vm.ctx.ChainID, []*atomic.Element{{ - Key: utxo.InputID().Bytes(), + Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ testKeys[0].PublicKey().Address().Bytes(), @@ -293,12 +293,12 @@ func TestNewImportTx(t *testing.T) { importAmount := uint64(1000000) utxoID := avax.UTXOID{ - TxID: ids.NewID([32]byte{ + TxID: [32]byte{ 0x0f, 0x2f, 0x4f, 0x6f, 0x8e, 0xae, 0xce, 0xee, 0x0d, 0x2d, 0x4d, 0x6d, 0x8c, 0xac, 0xcc, 0xec, 0x0b, 0x2b, 0x4b, 0x6b, 0x8a, 0xaa, 0xca, 0xea, 0x09, 0x29, 0x49, 0x69, 0x88, 0xa8, 0xc8, 0xe8, - }), + }, } utxo := &avax.UTXO{ @@ -318,9 +318,9 @@ func TestNewImportTx(t *testing.T) { } xChainSharedMemory := sharedMemory.NewSharedMemory(vm.ctx.XChainID) - + inputID := utxo.InputID() if err := xChainSharedMemory.Put(vm.ctx.ChainID, []*atomic.Element{{ - Key: utxo.InputID().Bytes(), + Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ testKeys[0].PublicKey().Address().Bytes(), diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 09e2ad5..2ab4028 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -851,7 +851,7 @@ func (vm *VM) GetAtomicUTXOs( chainID, addrsList, startAddr.Bytes(), - startUTXOID.Bytes(), + startUTXOID[:], limit, ) if err != nil { diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 8ce7825..1117d0d 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -23,15 +23,15 @@ import ( 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'}) + testCChainID = ids.ID([32]byte{'c', 'c', 'h', 'a', 'i', 'n', 't', 'e', 's', 't'}) + testXChainID = ids.ID([32]byte{'t', 'e', 's', 't', 'x'}) + nonExistentID = ids.ID([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}) + testAvaxAssetID = [32]byte{1, 2, 3} username = "Johns" password = "CjasdjhiPeirbSenfeI13" // #nosec G101 ethChainID uint32 = 43112 -- cgit v1.2.3-70-g09d2 From 52de74ce47a2614af3b3a32b21aa5309d4b00d78 Mon Sep 17 00:00:00 2001 From: Dan Laine Date: Sun, 1 Nov 2020 18:32:22 -0500 Subject: lint --- plugin/evm/export_tx_test.go | 2 +- plugin/evm/import_tx_test.go | 4 ++-- plugin/evm/tx.go | 4 ---- plugin/evm/user.go | 5 ++--- plugin/evm/vm.go | 29 ++--------------------------- plugin/evm/vm_test.go | 18 ++++++++---------- 6 files changed, 15 insertions(+), 47 deletions(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/export_tx_test.go b/plugin/evm/export_tx_test.go index 319c6dd..6fdf3a2 100644 --- a/plugin/evm/export_tx_test.go +++ b/plugin/evm/export_tx_test.go @@ -76,7 +76,7 @@ func TestExportTxVerify(t *testing.T) { // Test Valid Export Tx if err := exportTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err != nil { - t.Fatalf("Failed to verify valid ExportTx: %w", err) + t.Fatalf("Failed to verify valid ExportTx: %s", err) } exportTx.syntacticallyVerified = false diff --git a/plugin/evm/import_tx_test.go b/plugin/evm/import_tx_test.go index 52a8fa7..b0f2875 100644 --- a/plugin/evm/import_tx_test.go +++ b/plugin/evm/import_tx_test.go @@ -77,7 +77,7 @@ func TestImportTxVerify(t *testing.T) { // Test Valid ImportTx if err := importTx.Verify(testXChainID, ctx, testTxFee, testAvaxAssetID); err != nil { - t.Fatalf("Failed to verify ImportTx: %w", err) + t.Fatalf("Failed to verify ImportTx: %s", err) } importTx.syntacticallyVerified = false @@ -268,7 +268,7 @@ func TestImportTxSemanticVerify(t *testing.T) { } if err := unsignedImportTx.Accept(vm.ctx, nil); err != nil { - t.Fatalf("Accept failed due to: %w", err) + t.Fatalf("Accept failed due to: %s", err) } if err := unsignedImportTx.EVMStateTransfer(vm, state); err != nil { diff --git a/plugin/evm/tx.go b/plugin/evm/tx.go index 3a2f820..e44eefe 100644 --- a/plugin/evm/tx.go +++ b/plugin/evm/tx.go @@ -23,10 +23,6 @@ import ( "github.com/ethereum/go-ethereum/common" ) -// Max size of memo field -// Don't change without also changing avm.maxMemoSize -const maxMemoSize = 256 - var ( errWrongBlockchainID = errors.New("wrong blockchain ID provided") errWrongNetworkID = errors.New("tx was issued with a different network ID") diff --git a/plugin/evm/user.go b/plugin/evm/user.go index 152156d..0ab1863 100644 --- a/plugin/evm/user.go +++ b/plugin/evm/user.go @@ -18,9 +18,8 @@ import ( var addressesKey = ids.Empty[:] var ( - errDBNil = errors.New("db uninitialized") - errKeyNil = errors.New("key uninitialized") - errEmptyAddress = errors.New("address is empty") + errDBNil = errors.New("db uninitialized") + errKeyNil = errors.New("key uninitialized") ) type user struct { diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 2ab4028..c191720 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -57,10 +57,6 @@ import ( ) var ( - zeroAddr = common.Address{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - } x2cRate = big.NewInt(1000000000) ) @@ -83,10 +79,6 @@ const ( bdTimerStateLong ) -const ( - addressSep = "-" -) - var ( txFee = units.MilliAvax @@ -99,21 +91,14 @@ var ( errInvalidAddr = errors.New("invalid hex address") errTooManyAtomicTx = errors.New("too many pending atomic txs") errAssetIDMismatch = errors.New("asset IDs in the input don't match the utxo") - errWrongNumberOfCredentials = errors.New("should have the same number of credentials as inputs") - errNoInputs = errors.New("tx has no inputs") errNoImportInputs = errors.New("tx has no imported inputs") errInputsNotSortedUnique = errors.New("inputs not sorted and unique") errPublicKeySignatureMismatch = errors.New("signature doesn't match public key") errSignatureInputsMismatch = errors.New("number of inputs does not match number of signatures") - errUnknownAsset = errors.New("unknown asset ID") - errNoFunds = errors.New("no spendable funds were found") errWrongChainID = errors.New("tx has wrong chain ID") errInsufficientFunds = errors.New("insufficient funds") errNoExportOutputs = errors.New("tx has no export outputs") errOutputsNotSorted = errors.New("tx outputs not sorted") - errNoImportOutputs = errors.New("tx has no outputs to import") - errNoExportInputs = errors.New("tx has 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") ) @@ -457,8 +442,8 @@ func (vm *VM) ParseBlock(b []byte) (snowman.Block, error) { } blockHash := ethBlock.Hash() // Coinbase must be zero on C-Chain - if bytes.Compare(blockHash.Bytes(), vm.genesisHash.Bytes()) != 0 && - bytes.Compare(ethBlock.Coinbase().Bytes(), coreth.BlackholeAddr.Bytes()) != 0 { + if !bytes.Equal(blockHash.Bytes(), vm.genesisHash.Bytes()) && + !bytes.Equal(ethBlock.Coinbase().Bytes(), coreth.BlackholeAddr.Bytes()) { return nil, errInvalidBlock } block := &Block{ @@ -715,16 +700,6 @@ func (vm *VM) getBlock(id ids.ID) *Block { return block } -func (vm *VM) issueRemoteTxs(txs []*types.Transaction) error { - errs := vm.chain.AddRemoteTxs(txs) - for _, err := range errs { - if err != nil { - return err - } - } - return vm.tryBlockGen() -} - func (vm *VM) writeBackMetadata() { vm.metalock.Lock() defer vm.metalock.Unlock() diff --git a/plugin/evm/vm_test.go b/plugin/evm/vm_test.go index 1117d0d..d58fdda 100644 --- a/plugin/evm/vm_test.go +++ b/plugin/evm/vm_test.go @@ -27,14 +27,12 @@ var ( testXChainID = ids.ID([32]byte{'t', 'e', 's', 't', 'x'}) nonExistentID = ids.ID([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 = [32]byte{1, 2, 3} - username = "Johns" - password = "CjasdjhiPeirbSenfeI13" // #nosec G101 - ethChainID uint32 = 43112 + testAvaxAssetID = [32]byte{1, 2, 3} + username = "Johns" + password = "CjasdjhiPeirbSenfeI13" // #nosec G101 ) func init() { @@ -63,7 +61,7 @@ func BuildGenesisTest(t *testing.T) []byte { genesis := &core.Genesis{} if err := json.Unmarshal([]byte(genesisJSON), genesis); err != nil { - t.Fatalf("Problem unmarshaling genesis JSON: %w", err) + t.Fatalf("Problem unmarshaling genesis JSON: %s", err) } genesisReply, err := ss.BuildGenesis(nil, genesis) if err != nil { @@ -79,10 +77,10 @@ func NewContext() *snow.Context { 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()) + _ = 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 -- cgit v1.2.3-70-g09d2 From e3c39e7cde79a0f5b080db026242056032a1f55a Mon Sep 17 00:00:00 2001 From: Aaron Buchwald Date: Wed, 4 Nov 2020 12:22:04 -0500 Subject: Add back web3 API --- plugin/evm/config.go | 1 + plugin/evm/service.go | 12 +++++++++++- plugin/evm/vm.go | 4 ++++ plugin/params.go | 1 + 4 files changed, 17 insertions(+), 1 deletion(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/config.go b/plugin/evm/config.go index 4d6650a..21b3aaf 100644 --- a/plugin/evm/config.go +++ b/plugin/evm/config.go @@ -16,6 +16,7 @@ type CommandLineConfig struct { PersonalAPIEnabled bool `json:"personal-api-enabled"` TxPoolAPIEnabled bool `json:"tx-pool-api-enabled"` DebugAPIEnabled bool `json:"debug-api-enabled"` + Web3APIEnabled bool `json:"web3-api-enabled"` ParsingError error } diff --git a/plugin/evm/service.go b/plugin/evm/service.go index a934941..7b8368e 100644 --- a/plugin/evm/service.go +++ b/plugin/evm/service.go @@ -19,11 +19,12 @@ import ( "github.com/ava-labs/avalanchego/utils/json" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" + ethcrypto "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/log" ) const ( - version = "coreth-v0.3.7" + version = "coreth" ) // test constants @@ -50,6 +51,15 @@ func (s *NetAPI) PeerCount() hexutil.Uint { return hexutil.Uint(0) } // TODO: re // Version returns the current ethereum protocol version. func (s *NetAPI) Version() string { return fmt.Sprintf("%d", s.vm.networkID) } +// Web3API offers helper API methods +type Web3API struct{} + +// ClientVersion returns the version of the vm running +func (s *Web3API) ClientVersion() string { return version } + +// Sha3 returns the bytes returned by hashing [input] with Keccak256 +func (s *Web3API) Sha3(input hexutil.Bytes) hexutil.Bytes { return ethcrypto.Keccak256(input) } + // GetAcceptedFrontReply defines the reply that will be sent from the // GetAcceptedFront API call type GetAcceptedFrontReply struct { diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index c902f85..a8c4fc0 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -534,6 +534,10 @@ func (vm *VM) CreateHandlers() map[string]*commonEng.HTTPHandler { handler.RegisterName("net", &NetAPI{vm}) enabledAPIs = append(enabledAPIs, "net") } + if vm.CLIConfig.Web3APIEnabled { + handler.RegisterName("web3", &Web3API{}) + enabledAPIs = append(enabledAPIs, "web3") + } log.Info(fmt.Sprintf("Enabled APIs: %s", strings.Join(enabledAPIs, ", "))) diff --git a/plugin/params.go b/plugin/params.go index 6615798..a130d52 100644 --- a/plugin/params.go +++ b/plugin/params.go @@ -27,6 +27,7 @@ func init() { cliConfig.PersonalAPIEnabled = true cliConfig.TxPoolAPIEnabled = true cliConfig.NetAPIEnabled = true + cliConfig.Web3APIEnabled = true cliConfig.RPCGasCap = 2500000000 // 25000000 x 100 cliConfig.RPCTxFeeCap = 100 // 100 AVAX } else { -- cgit v1.2.3-70-g09d2 From d46b49cc7a0c624cb29eb40016d956d10e100ec9 Mon Sep 17 00:00:00 2001 From: Aaron Buchwald Date: Tue, 3 Nov 2020 20:11:32 -0500 Subject: Add bech32 address parsing --- plugin/evm/vm.go | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index a8c4fc0..fd177a0 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -155,7 +155,8 @@ func init() { type VM struct { ctx *snow.Context - CLIConfig CommandLineConfig + CLIConfig CommandLineConfig + encodingManager formatting.EncodingManager chainID *big.Int networkID uint64 @@ -236,6 +237,12 @@ func (vm *VM) Initialize( return vm.CLIConfig.ParsingError } + encodingManager, err := formatting.NewEncodingManager(formatting.CB58Encoding) + if err != nil { + return fmt.Errorf("problem creating encoding manager: %w", err) + } + vm.encodingManager = encodingManager + if len(fxs) > 0 { return errUnsupportedFXs } @@ -243,8 +250,7 @@ func (vm *VM) Initialize( vm.ctx = ctx vm.chaindb = Database{db} g := new(core.Genesis) - err := json.Unmarshal(b, g) - if err != nil { + if err := json.Unmarshal(b, g); err != nil { return err } @@ -947,6 +953,35 @@ func (vm *VM) GetAcceptedNonce(address common.Address) (uint64, error) { return state.GetNonce(address), nil } +// ParseLocalAddress takes in an address for this chain and produces the ID +func (vm *VM) ParseLocalAddress(addrStr string) (ids.ShortID, error) { + chainID, addr, err := vm.ParseAddress(addrStr) + if err != nil { + return ids.ShortID{}, err + } + if !chainID.Equals(vm.ctx.ChainID) { + return ids.ShortID{}, fmt.Errorf("expected chainID to be %q but was %q", + vm.ctx.ChainID, chainID) + } + return addr, nil +} + +// FormatLocalAddress takes in a raw address and produces the formatted address +func (vm *VM) FormatLocalAddress(addr ids.ShortID) (string, error) { + return vm.FormatAddress(vm.ctx.ChainID, addr) +} + +// FormatAddress takes in a chainID and a raw address and produces the formatted +// address +func (vm *VM) FormatAddress(chainID ids.ID, addr ids.ShortID) (string, error) { + chainIDAlias, err := vm.ctx.BCLookup.PrimaryAlias(chainID) + if err != nil { + return "", err + } + hrp := constants.GetHRP(vm.ctx.NetworkID) + return formatting.FormatAddress(chainIDAlias, hrp, addr.Bytes()) +} + // ParseEthAddress parses [addrStr] and returns an Ethereum address func ParseEthAddress(addrStr string) (common.Address, error) { if !common.IsHexAddress(addrStr) { -- cgit v1.2.3-70-g09d2 From 60eb1fdfa0e996f5564bbd9a17801ea9b7c9df1a Mon Sep 17 00:00:00 2001 From: Aaron Buchwald Date: Mon, 9 Nov 2020 12:36:26 -0500 Subject: Fix typo --- plugin/evm/vm.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index c7c7ca0..4b3c2bb 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -934,7 +934,7 @@ func (vm *VM) ParseLocalAddress(addrStr string) (ids.ShortID, error) { if err != nil { return ids.ShortID{}, err } - if !chainID.Equals(vm.ctx.ChainID) { + if chainID != vm.ctx.ChainID { return ids.ShortID{}, fmt.Errorf("expected chainID to be %q but was %q", vm.ctx.ChainID, chainID) } -- cgit v1.2.3-70-g09d2 From 419cd2d882b93bd98f54957a15c25716fca09123 Mon Sep 17 00:00:00 2001 From: Aaron Buchwald Date: Mon, 9 Nov 2020 15:34:14 -0500 Subject: Fix byte comparison --- plugin/evm/vm.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'plugin/evm/vm.go') diff --git a/plugin/evm/vm.go b/plugin/evm/vm.go index 4b3c2bb..284a772 100644 --- a/plugin/evm/vm.go +++ b/plugin/evm/vm.go @@ -4,7 +4,6 @@ package evm import ( - "bytes" "crypto/rand" "encoding/json" "errors" @@ -448,8 +447,7 @@ func (vm *VM) ParseBlock(b []byte) (snowman.Block, error) { } blockHash := ethBlock.Hash() // Coinbase must be zero on C-Chain - if !bytes.Equal(blockHash.Bytes(), vm.genesisHash.Bytes()) && - !bytes.Equal(ethBlock.Coinbase().Bytes(), coreth.BlackholeAddr.Bytes()) { + if blockHash != vm.genesisHash && ethBlock.Coinbase() != coreth.BlackholeAddr { return nil, errInvalidBlock } block := &Block{ -- cgit v1.2.3-70-g09d2