diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 9c2b6cdce5..6c59092b79 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -65,13 +65,9 @@ type SimulatedBackend struct { config *params.ChainConfig } -// NewSimulatedBackend creates a new binding backend using a simulated blockchain -// for testing purposes. -func NewSimulatedBackend(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { - // Don't panic for the lazy user. - if database == nil { - database = rawdb.NewMemoryDatabase() - } +// NewSimulatedBackendWithDatabase creates a new binding backend based on the given database +// and uses a simulated blockchain for testing purposes. +func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc} genesis.MustCommit(database) blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil) @@ -86,6 +82,12 @@ func NewSimulatedBackend(database ethdb.Database, alloc core.GenesisAlloc, gasLi return backend } +// NewSimulatedBackend creates a new binding backend using a simulated blockchain +// for testing purposes. +func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { + return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit) +} + // Commit imports all the pending transactions as a single block and starts a // fresh new state. func (b *SimulatedBackend) Commit() { @@ -429,28 +431,6 @@ func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { return nil } -// InsertEmptyBlocks inserts a batch of empty blocks to blockchain. -func (b *SimulatedBackend) InsertEmptyBlocks(number int) error { - b.mu.Lock() - defer b.mu.Unlock() - // Insert a batch of empty blocks and commit to the database - blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, number, func(i int, block *core.BlockGen) {}) - if _, err := b.blockchain.InsertChain(blocks); err != nil { - panic(err) // This cannot happen unless the simulator is wrong, fail in that case - } - // Apply all pending transactions to new pending blocks. - blocks, _ = core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { - for _, tx := range b.pendingBlock.Transactions() { - block.AddTx(tx) - } - }) - - statedb, _ := b.blockchain.State() - b.pendingBlock = blocks[0] - b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database()) - return nil -} - // Blockchain returns the underlying blockchain. func (b *SimulatedBackend) Blockchain() *core.BlockChain { return b.blockchain diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index a92bb740e0..bd75807d75 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -37,7 +37,7 @@ func TestSimulatedBackend(t *testing.T) { genAlloc := make(core.GenesisAlloc) genAlloc[auth.From] = core.GenesisAccount{Balance: big.NewInt(9223372036854775807)} - sim := backends.NewSimulatedBackend(nil, genAlloc, gasLimit) + sim := backends.NewSimulatedBackend(genAlloc, gasLimit) // should return an error if the tx is not found txHash := common.HexToHash("2") diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 16f3c85340..e4c9f1003a 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -258,7 +258,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy an interaction tester contract and call a transaction on it _, _, interactor, err := DeployInteractor(auth, sim, "Deploy string") @@ -307,7 +307,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a tuple tester contract and execute a structured call on it _, _, getter, err := DeployGetter(auth, sim) @@ -347,7 +347,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a tuple tester contract and execute a structured call on it _, _, tupler, err := DeployTupler(auth, sim) @@ -399,7 +399,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a slice tester contract and execute a n array call on it _, _, slicer, err := DeploySlicer(auth, sim) @@ -441,7 +441,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a default method invoker contract and execute its default method _, _, defaulter, err := DeployDefaulter(auth, sim) @@ -480,7 +480,7 @@ var bindTests = []struct { `, ` // Create a simulator and wrap a non-deployed contract - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{}, uint64(10000000000)) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{}, uint64(10000000000)) nonexistent, err := NewNonExistent(common.Address{}, sim) if err != nil { @@ -524,7 +524,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a funky gas pattern contract _, _, limiter, err := DeployFunkyGasPattern(auth, sim) @@ -568,7 +568,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a sender tester contract and execute a structured call on it _, _, callfrom, err := DeployCallFrom(auth, sim) @@ -637,7 +637,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy a underscorer tester contract and execute a structured call on it _, _, underscorer, err := DeployUnderscorer(auth, sim) @@ -725,7 +725,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) // Deploy an eventer contract _, _, eventer, err := DeployEventer(auth, sim) @@ -909,7 +909,7 @@ var bindTests = []struct { // Generate a new random account and a funded simulator key, _ := crypto.GenerateKey() auth := bind.NewKeyedTransactor(key) - sim := backends.NewSimulatedBackend(nil, core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}, 10000000) //deploy the test contract _, _, testContract, err := DeployDeeplyNestedArray(auth, sim) diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index 49dc8c547c..87bc29822b 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -54,7 +54,6 @@ var waitDeployedTests = map[string]struct { func TestWaitDeployed(t *testing.T) { for name, test := range waitDeployedTests { backend := backends.NewSimulatedBackend( - nil, core.GenesisAlloc{ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)}, }, diff --git a/cmd/puppeth/wizard_genesis.go b/cmd/puppeth/wizard_genesis.go index 10f015326d..fa89e4ee79 100644 --- a/cmd/puppeth/wizard_genesis.go +++ b/cmd/puppeth/wizard_genesis.go @@ -189,11 +189,11 @@ func (w *wizard) makeGenesis() { if err != nil { log.Crit("Failed to iterate contract storage", "err", err) } - genesis.Config.CheckpointContract = ¶ms.CheckpointContractConfig{ - Name: w.network, - ContractAddr: address, - Signers: signers, - Threshold: threshold.Uint64(), + genesis.Config.CheckpointConfig = ¶ms.CheckpointContractConfig{ + Name: w.network, + Address: address, + Signers: signers, + Threshold: threshold.Uint64(), } } diff --git a/contracts/registrar/registrar_test.go b/contracts/registrar/registrar_test.go index bcfec7856f..90ac89bf86 100644 --- a/contracts/registrar/registrar_test.go +++ b/contracts/registrar/registrar_test.go @@ -176,7 +176,7 @@ func TestCheckpointRegister(t *testing.T) { // Deploy registrar contract transactOpts := bind.NewKeyedTransactor(accounts[0].key) - contractBackend := backends.NewSimulatedBackend(nil, core.GenesisAlloc{accounts[0].addr: {Balance: big.NewInt(1000000000)}, accounts[1].addr: {Balance: big.NewInt(1000000000)}, accounts[2].addr: {Balance: big.NewInt(1000000000)}}, 10000000) + contractBackend := backends.NewSimulatedBackend(core.GenesisAlloc{accounts[0].addr: {Balance: big.NewInt(1000000000)}, accounts[1].addr: {Balance: big.NewInt(1000000000)}, accounts[2].addr: {Balance: big.NewInt(1000000000)}}, 10000000) // 3 trusted signers, threshold 2 contractAddr, _, c, err := contract.DeployContract(transactOpts, contractBackend, []common.Address{accounts[0].addr, accounts[1].addr, accounts[2].addr}, sectionSize, processConfirms, big.NewInt(2)) if err != nil { @@ -203,6 +203,12 @@ func TestCheckpointRegister(t *testing.T) { } return v, r, s } + // insertEmptyBlocks inserts a batch of empty blocks to blockchain. + insertEmptyBlocks := func(number int) { + for i := 0; i < number; i++ { + contractBackend.Commit() + } + } // assert checks whether the current contract status is same with // the expected. assert := func(index uint64, hash [32]byte, height *big.Int) error { @@ -231,7 +237,7 @@ func TestCheckpointRegister(t *testing.T) { return assert(0, emptyHash, big.NewInt(0)) }, "test future checkpoint registration") - contractBackend.InsertEmptyBlocks(int(sectionSize.Uint64() + processConfirms.Uint64())) + insertEmptyBlocks(int(sectionSize.Uint64() + processConfirms.Uint64())) // Test transaction replay protection validateOperation(t, c, contractBackend, func() { @@ -283,7 +289,7 @@ func TestCheckpointRegister(t *testing.T) { }, "test valid checkpoint registration") distance := 3*sectionSize.Uint64() + processConfirms.Uint64() - contractBackend.Blockchain().CurrentHeader().Number.Uint64() - contractBackend.InsertEmptyBlocks(int(distance)) + insertEmptyBlocks(int(distance)) // Test uncontinuous checkpoint registration validateOperation(t, c, contractBackend, func() { diff --git a/les/api.go b/les/api.go index 9ce6ed4800..5598988b90 100644 --- a/les/api.go +++ b/les/api.go @@ -526,5 +526,5 @@ func (api *PrivateLightAPI) GetCheckpointContractAddress() (string, error) { if api.reg == nil { return "", ErrNotActivated } - return api.reg.config.ContractAddr.Hex(), nil + return api.reg.config.Address.Hex(), nil } diff --git a/les/backend.go b/les/backend.go index 71c6499145..71a42f814e 100644 --- a/les/backend.go +++ b/les/backend.go @@ -150,7 +150,7 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) { } leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams) - registrar := newCheckpointRegistrar(chainConfig.CheckpointContract, leth.getLocalCheckpoint) + registrar := newCheckpointRegistrar(chainConfig.CheckpointConfig, leth.getLocalCheckpoint) if leth.protocolManager, err = NewProtocolManager(leth.chainConfig, light.DefaultClientIndexerConfig, config.ULC, true, config.NetworkId, leth.eventMux, leth.peers, leth.blockchain, nil, chainDb, leth.odr, leth.serverPool, registrar, quitSync, &leth.wg, nil); err != nil { return nil, err } diff --git a/les/handler_test.go b/les/handler_test.go index 0a085bae52..a995b0b60b 100644 --- a/les/handler_test.go +++ b/les/handler_test.go @@ -373,7 +373,7 @@ func testGetStaleProof(t *testing.T, protocol int) { check := func(number uint64, wantOK bool) { var ( header = bc.GetHeaderByNumber(number) - account = crypto.Keccak256(testBankAddress.Bytes()) + account = crypto.Keccak256(userAddr1.Bytes()) ) req := &ProofReq{ BHash: header.Hash(), @@ -386,7 +386,7 @@ func testGetStaleProof(t *testing.T, protocol int) { if wantOK { proofsV2 := light.NewNodeSet() t, _ := trie.New(header.Root, trie.NewDatabase(server.db)) - t.Prove(crypto.Keccak256(account), 0, proofsV2) + t.Prove(account, 0, proofsV2) expected = proofsV2.NodeList() } if err := expectResponse(server.tPeer.app, ProofsV2Msg, 42, testBufLimit, expected); err != nil { diff --git a/les/helper_test.go b/les/helper_test.go index e78765ca33..7da213dbfa 100644 --- a/les/helper_test.go +++ b/les/helper_test.go @@ -184,7 +184,7 @@ func newTestProtocolManager(lightSync bool, blocks int, odr *LesOdr, indexers [] peers = newPeerSet() } // create a simulation backend and pre-commit several customized block to the database. - simulation := backends.NewSimulatedBackend(db, gspec.Alloc, 100000000) + simulation := backends.NewSimulatedBackendWithDatabase(db, gspec.Alloc, 100000000) prepareTestchain(blocks, simulation) // initialize empty chain for light client or pre-committed chain for server. @@ -201,10 +201,10 @@ func newTestProtocolManager(lightSync bool, blocks int, odr *LesOdr, indexers [] indexConfig = light.TestClientIndexerConfig } config := ¶ms.CheckpointContractConfig{ - Name: "test", - ContractAddr: crypto.CreateAddress(bankAddr, 0), - Signers: []common.Address{signerAddr}, - Threshold: 1, + Name: "test", + Address: crypto.CreateAddress(bankAddr, 0), + Signers: []common.Address{signerAddr}, + Threshold: 1, } var reg *checkpointRegistrar if indexers != nil { diff --git a/les/registrar.go b/les/registrar.go index a848ee1650..1e61e43fa5 100644 --- a/les/registrar.go +++ b/les/registrar.go @@ -1,4 +1,4 @@ -// Copyright 2016 The go-ethereum Authors +// Copyright 2019 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify @@ -50,11 +50,11 @@ func newCheckpointRegistrar(config *params.CheckpointContractConfig, getLocal fu log.Info("Checkpoint registrar is not enabled") return nil } - if config.ContractAddr == (common.Address{}) || uint64(len(config.Signers)) < config.Threshold { + if config.Address == (common.Address{}) || uint64(len(config.Signers)) < config.Threshold { log.Warn("Invalid checkpoint contract config") return nil } - log.Info("Setup checkpoint registrar", "contract", config.ContractAddr, "numsigner", len(config.Signers), + log.Info("Setup checkpoint registrar", "contract", config.Address, "numsigner", len(config.Signers), "threshold", config.Threshold) return &checkpointRegistrar{ config: config, @@ -65,7 +65,7 @@ func newCheckpointRegistrar(config *params.CheckpointContractConfig, getLocal fu // start binds the registrar contract and start listening to the // newCheckpointEvent for the server side. func (reg *checkpointRegistrar) start(backend bind.ContractBackend) { - contract, err := registrar.NewRegistrar(reg.config.ContractAddr, backend) + contract, err := registrar.NewRegistrar(reg.config.Address, backend) if err != nil { log.Info("Registrar contract binding failed", "err", err) return @@ -134,7 +134,7 @@ func (reg *checkpointRegistrar) verifySigner(index uint64, hash [32]byte, signat // hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root) buf := make([]byte, 8) binary.BigEndian.PutUint64(buf, index) - data := append([]byte{0x19, 0x00}, append(reg.config.ContractAddr.Bytes(), append(buf, hash[:]...)...)...) + data := append([]byte{0x19, 0x00}, append(reg.config.Address.Bytes(), append(buf, hash[:]...)...)...) signatures[i][64] -= 27 // Transform V from 27/28 to 0/1 according to the yellow paper for verification. pubkey, err := crypto.Ecrecover(crypto.Keccak256(data), signatures[i]) if err != nil { diff --git a/les/server.go b/les/server.go index e524ddfea4..2e125e2f27 100644 --- a/les/server.go +++ b/les/server.go @@ -120,7 +120,7 @@ func NewLesServer(e *eth.Ethereum, config *eth.Config) (*LesServer, error) { srv.chtIndexer.Start(e.BlockChain()) - registrar := newCheckpointRegistrar(e.BlockChain().Config().CheckpointContract, srv.getLocalCheckpoint) + registrar := newCheckpointRegistrar(e.BlockChain().Config().CheckpointConfig, srv.getLocalCheckpoint) pm, err := NewProtocolManager(e.BlockChain().Config(), light.DefaultServerIndexerConfig, config.ULC, false, config.NetworkId, e.EventMux(), newPeerSet(), e.BlockChain(), e.TxPool(), e.ChainDb(), nil, nil, registrar, quitSync, new(sync.WaitGroup), e.Synced) if err != nil { return nil, err diff --git a/les/sync_test.go b/les/sync_test.go index 7dfef953c5..944d0dce3b 100644 --- a/les/sync_test.go +++ b/les/sync_test.go @@ -67,7 +67,7 @@ func testCheckpointSyncing(t *testing.T, protocol int) { t.Error("register checkpoint failed", err) } server.backend.Commit() - server.backend.InsertEmptyBlocks(1) + server.backend.Commit() // Inject an empty block // Wait for the checkpoint registration for { diff --git a/params/config.go b/params/config.go index 2a4fae5605..ba40cc5941 100644 --- a/params/config.go +++ b/params/config.go @@ -110,9 +110,9 @@ var ( Period: 15, Epoch: 30000, }, - CheckpointContract: &CheckpointContractConfig{ - Name: "rinkeby", - ContractAddr: common.HexToAddress("0x62652ed8e969ce7bd5e3dd13590efa1e569215f1"), + CheckpointConfig: &CheckpointContractConfig{ + Name: "rinkeby", + Address: common.HexToAddress("0x62652ed8e969ce7bd5e3dd13590efa1e569215f1"), Signers: []common.Address{ common.HexToAddress("0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3"), // Peter common.HexToAddress("0x78d1ad571a1a09d60d9bbf25894b44e4c8859595"), // Martin @@ -215,10 +215,10 @@ func (c *TrustedCheckpoint) Empty() bool { // CheckpointContractConfig represents a set of checkpoint contract config // which used for light client checkpoint syncing. type CheckpointContractConfig struct { - Name string `json:"-"` - ContractAddr common.Address `json:"contractAddr"` - Signers []common.Address `json:"signers"` - Threshold uint64 `json:"threshold"` + Name string `json:"-"` + Address common.Address `json:"contractAddr"` + Signers []common.Address `json:"signers"` + Threshold uint64 `json:"threshold"` } // ChainConfig is the core config which determines the blockchain settings. @@ -251,7 +251,7 @@ type ChainConfig struct { Clique *CliqueConfig `json:"clique,omitempty"` // Checkpoint contract configs - CheckpointContract *CheckpointContractConfig `json:"checkpointContract,omitempty"` + CheckpointConfig *CheckpointContractConfig `json:"checkpointContract,omitempty"` } // EthashConfig is the consensus engine configs for proof-of-work based sealing.