diff --git a/consensus/hotstuff/backend/engine.go b/consensus/hotstuff/backend/engine.go index c9e6cd3b..d13e05fd 100644 --- a/consensus/hotstuff/backend/engine.go +++ b/consensus/hotstuff/backend/engine.go @@ -131,8 +131,8 @@ func (s *backend) BlockTransactions(block *types.Block, state *state.StateDB) (t signer := types.MakeSigner(s.chainConfig, block.Number()) for i, tx := range systemTransactions { includedTx := allTransactions[commonTransactionCount + i] - if includedTx.Hash() != tx.Hash() { - return nil, nil, nil, fmt.Errorf("unexpected system tx hash detected, tx index %v, hash %s, expected: %s", commonTransactionCount + i, includedTx.Hash(), tx.Hash()) + if signer.Hash(includedTx) != signer.Hash(tx) { + return nil, nil, nil, fmt.Errorf("unexpected system tx hash detected, tx index %v, hash %s, expected: %s", commonTransactionCount + i, signer.Hash(includedTx), signer.Hash(tx)) } from, err := signer.Sender(includedTx) if err != nil { diff --git a/contracts/native/contract.go b/contracts/native/contract.go index 315fe9af..0143e415 100644 --- a/contracts/native/contract.go +++ b/contracts/native/contract.go @@ -38,14 +38,6 @@ var ( DebugSpentOpen bool = true ) -// the gasUsage for the native contract transaction calculated according to the following formula: -// * `gasUsage = gasRatio * gasTable[methodId]` -// the value in gas table for native tx is the max num for bench test in linux. -const ( - basicGas = uint64(21000) // minimum gas spent by transaction which failed before contract.handler, the default value is 21000 wei. - gasRatio = float64(1.0) // gasRatio is used to adjust the final value of gasUsage. -) - type NativeContract struct { ref *ContractRef db *state.StateDB @@ -81,8 +73,7 @@ func (s *NativeContract) Prepare(ab *abiPkg.ABI, gasTb map[string]uint64) { s.gasTable = make(map[string]uint64) for name, gas := range gasTb { id := utils.MethodID(s.ab, name) - final := uint64(float64(basicGas) + float64(gas)*gasRatio) - s.gasTable[id] = final + s.gasTable[id] = gas } } @@ -93,15 +84,6 @@ func (s *NativeContract) Register(name string, handler MethodHandler) { // Invoke return execute ret and cost gas func (s *NativeContract) Invoke() ([]byte, error) { - - // pre-cost for failed tx which failed before `handler` execution. - if gasLeft := s.ref.gasLeft; gasLeft < basicGas { - s.ref.gasLeft = 0 - return nil, fmt.Errorf("gasLeft not enough, need %d, got %d", basicGas, gasLeft) - } else { - s.ref.gasLeft -= basicGas - } - // check context if !s.ref.CheckContexts() { return nil, fmt.Errorf("context error") @@ -132,18 +114,14 @@ func (s *NativeContract) Invoke() ([]byte, error) { if !ok { return nil, fmt.Errorf("failed to find method: [%s]", methodID) } - if gasUsage < basicGas { - gasUsage = basicGas - } - // refund basic gas before tx get into `handler` - s.ref.gasLeft += basicGas + if gasLeft := s.ref.gasLeft; gasLeft < gasUsage { return nil, fmt.Errorf("gasLeft not enough, need %d, got %d", gasUsage, gasLeft) } + s.ref.gasLeft -= gasUsage // execute transaction and cost gas ret, err := handler(s) - s.ref.gasLeft -= gasUsage return ret, err } diff --git a/contracts/native/cross_chain_manager/entrance_test.go b/contracts/native/cross_chain_manager/entrance_test.go index bc2e2684..5bca0fd6 100644 --- a/contracts/native/cross_chain_manager/entrance_test.go +++ b/contracts/native/cross_chain_manager/entrance_test.go @@ -66,29 +66,31 @@ func init() { param := new(side_chain_manager.RegisterSideChainParam) param.ChainID = 8 param.Name = "mychain" + param.Router = 1 param1 := new(side_chain_manager.RegisterSideChainParam) - param1.ChainID = 9 + param1.ChainID = 79 param1.Name = strings.Repeat("1", 100) param1.ExtraInfo = make([]byte, 1000000) param1.CCMCAddress = make([]byte, 1000) + param1.Router = 1 ccd := common.HexToAddress("0xdedace1809079e241234d546e44517f31b57ab8f") param2 := new(side_chain_manager.RegisterSideChainParam) param2.ChainID = 10 - param2.Router = 15 + param2.Router = 2 param2.Name = "chain10" param2.CCMCAddress = ccd.Bytes() param3 := new(side_chain_manager.RegisterSideChainParam) param3.ChainID = 11 - param3.Router = 15 + param3.Router = 2 param3.Name = strings.Repeat("1", 100) param3.ExtraInfo = make([]byte, 1000000) param3.CCMCAddress = ccd.Bytes() param4 := *param3 - param4.ChainID = 79 + param4.ChainID = 2 for _, param := range []*side_chain_manager.RegisterSideChainParam{param, param1, param2, param3, ¶m4} { input, err := utils.PackMethodWithStruct(side_chain_manager.ABI, side_chain_manager_abi.MethodRegisterSideChain, param) @@ -171,7 +173,7 @@ func TestImportOuterTransfer(t *testing.T) { param.Extra = event param1 := new(scom.EntranceParam) - param1.SourceChainID = 9 + param1.SourceChainID = 79 param1.Extra = event param2 := new(scom.EntranceParam) @@ -204,9 +206,8 @@ func TestImportOuterTransfer(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := common.Address{} - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodImportOuterTransfer]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodImportOuterTransfer], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -214,7 +215,7 @@ func TestImportOuterTransfer(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodImportOuterTransfer, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } } @@ -223,9 +224,8 @@ func TestImportOuterTransfer(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := common.Address{} - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodImportOuterTransfer]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodImportOuterTransfer], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -233,7 +233,7 @@ func TestImportOuterTransfer(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodImportOuterTransfer, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -255,9 +255,8 @@ func TestReplenish(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := common.Address{} - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodReplenish]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodReplenish], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -265,7 +264,7 @@ func TestReplenish(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodReplenish, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -283,9 +282,8 @@ func TestCheckDone(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := common.Address{} - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodCheckDone]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodCheckDone], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -293,7 +291,7 @@ func TestCheckDone(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodCheckDone, false) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -311,9 +309,8 @@ func TestWhiteChain(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodWhiteChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodWhiteChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -321,7 +318,7 @@ func TestWhiteChain(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodWhiteChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -339,9 +336,8 @@ func TestBlackChain(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodBlackChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[cross_chain_manager_abi.MethodBlackChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.CrossChainManagerContractAddress, input) tr.Stop() @@ -349,7 +345,7 @@ func TestBlackChain(t *testing.T) { result, err := utils.PackOutputs(scom.ABI, cross_chain_manager_abi.MethodBlackChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } diff --git a/contracts/native/economic/economic_test.go b/contracts/native/economic/economic_test.go index b186c5a7..d8fbe3a3 100644 --- a/contracts/native/economic/economic_test.go +++ b/contracts/native/economic/economic_test.go @@ -48,7 +48,7 @@ func TestName(t *testing.T) { payload, err := new(MethodContractNameInput).Encode() assert.NoError(t, err) - raw, err := native.TestNativeCall(t, this, name, payload, common.Big0) + raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, gasTable[MethodName]) assert.NoError(t, err) var got string assert.NoError(t, utils.UnpackOutputs(ABI, name, &got, raw)) @@ -78,7 +78,7 @@ func TestTotalSupply(t *testing.T) { var supply *big.Int payload, _ := new(MethodTotalSupplyInput).Encode() - raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, tc.height) + raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, tc.height, gasTable[MethodTotalSupply]) assert.NoError(t, err) if tc.testABI { @@ -120,7 +120,7 @@ func TestReward(t *testing.T) { payload, _ := new(MethodRewardInput).Encode() raw, err := native.TestNativeCall(t, this, name, payload, common.Big0, tc.height, func(state *state.StateDB) { community.StoreCommunityInfo(state, big.NewInt(int64(tc.rate)), tc.pool) - }) + }, gasTable[MethodReward]) if tc.err == nil { assert.NoError(t, err) assert.NoError(t, got.Decode(raw)) diff --git a/contracts/native/governance/entrance.go b/contracts/native/governance/entrance.go index d4b67bf8..9a4188ba 100644 --- a/contracts/native/governance/entrance.go +++ b/contracts/native/governance/entrance.go @@ -19,7 +19,6 @@ package governance import ( "fmt" - "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/contracts/native/go_abi/node_manager_abi" nm "github.com/ethereum/go-ethereum/contracts/native/governance/node_manager" @@ -43,6 +42,7 @@ func AssembleSystemTransactions(state *state.StateDB, height uint64) (types.Tran if err != nil { return nil, err } + gas, err := core.IntrinsicGas(payload, nil, false, true, true) if err != nil { return nil, err diff --git a/contracts/native/governance/node_manager/manager_test.go b/contracts/native/governance/node_manager/manager_test.go index d96b7c9d..26aa4101 100644 --- a/contracts/native/governance/node_manager/manager_test.go +++ b/contracts/native/governance/node_manager/manager_test.go @@ -453,7 +453,7 @@ func TestChangeEpoch(t *testing.T) { param := new(CreateValidatorParam) param.ConsensusAddress = consensusAddr param.SignerAddress = consensusAddr - param.ProposalAddress = caller + param.ProposalAddress = consensusAddr param.Commission = new(big.Int).SetUint64(2000) param.Desc = "test" validatorsKey = append(validatorsKey, &ValidatorKey{param.ConsensusAddress, caller}) @@ -537,7 +537,7 @@ func TestDistribute(t *testing.T) { param := new(CreateValidatorParam) param.ConsensusAddress = consensusAddr param.SignerAddress = consensusAddr - param.ProposalAddress = caller + param.ProposalAddress = consensusAddr param.Commission = new(big.Int).SetUint64(2000) param.Desc = "test" validatorsKey = append(validatorsKey, &ValidatorKey{param.ConsensusAddress, caller}) @@ -985,7 +985,7 @@ func TestPerformance(t *testing.T) { param := new(CreateValidatorParam) param.ConsensusAddress = consensusAddr param.SignerAddress = consensusAddr - param.ProposalAddress = caller + param.ProposalAddress = consensusAddr param.Commission = new(big.Int).SetUint64(2000) param.Desc = "test" validatorsKey = append(validatorsKey, &ValidatorKey{param.ConsensusAddress, caller}) diff --git a/contracts/native/governance/side_chain_manager/side_chain_manager_test.go b/contracts/native/governance/side_chain_manager/side_chain_manager_test.go index f0fbef2e..bda2d649 100644 --- a/contracts/native/governance/side_chain_manager/side_chain_manager_test.go +++ b/contracts/native/governance/side_chain_manager/side_chain_manager_test.go @@ -71,24 +71,25 @@ func testRegisterSideChainManager(t *testing.T) { assert.Nil(t, err) blockNumber := big.NewInt(1) - extra := uint64(10) tr := native.NewTimer(side_chain_manager_abi.MethodRegisterSideChain) for _, input := range [][]byte{input, input1} { caller := signers[0] tr.Start() - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodRegisterSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodRegisterSideChain], nil) ret, leftOverGas, err := contractRef.NativeCall(common.Address{}, utils.SideChainManagerContractAddress, input) tr.Stop() assert.Nil(t, err) result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodRegisterSideChain) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) contract := native.NewNativeContract(sdb, contractRef) sideChain, err := GetSideChainApply(contract, 8) - assert.Equal(t, sideChain.Name, "mychain") assert.Nil(t, err) + assert.NotNil(t, sideChain) + t.Log(sideChain) + assert.Equal(t, sideChain.Name, "mychain") _, _, err = contractRef.NativeCall(common.Address{}, utils.SideChainManagerContractAddress, input) assert.NotNil(t, err) @@ -112,8 +113,7 @@ func testApproveRegisterSideChain(t *testing.T) { for _, input := range [][]byte{input, input1} { caller := signers[0] blockNumber := big.NewInt(1) - extra := uint64(10) - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveRegisterSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveRegisterSideChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -122,10 +122,10 @@ func testApproveRegisterSideChain(t *testing.T) { result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveRegisterSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) caller = signers[1] - contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveRegisterSideChain]+extra, nil) + contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveRegisterSideChain], nil) tr.Start() ret, leftOverGas, err = contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -134,7 +134,7 @@ func testApproveRegisterSideChain(t *testing.T) { result, err = utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveRegisterSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -160,9 +160,8 @@ func testUpdateSideChain(t *testing.T) { tr := native.NewTimer(side_chain_manager_abi.MethodUpdateSideChain) for _, input := range [][]byte{input, input1} { blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodUpdateSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodUpdateSideChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(common.Address{}, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -171,7 +170,7 @@ func testUpdateSideChain(t *testing.T) { result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodUpdateSideChain) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() @@ -193,9 +192,8 @@ func testApproveUpdateSideChain(t *testing.T) { tr1 := native.NewTimer(side_chain_manager_abi.MethodGetSideChain) for i, input := range [][]byte{input, input1} { blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveUpdateSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveUpdateSideChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -204,10 +202,10 @@ func testApproveUpdateSideChain(t *testing.T) { result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveUpdateSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) caller = signers[1] - contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveUpdateSideChain]+extra, nil) + contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveUpdateSideChain], nil) tr.Start() ret, leftOverGas, err = contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -216,7 +214,7 @@ func testApproveUpdateSideChain(t *testing.T) { result, err = utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveUpdateSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) contract := native.NewNativeContract(sdb, contractRef) sideChain, err := GetSideChainObject(contract, 8+uint64(i)) @@ -231,7 +229,7 @@ func testApproveUpdateSideChain(t *testing.T) { input, err = utils.PackMethodWithStruct(ABI, side_chain_manager_abi.MethodGetSideChain, param) assert.Nil(t, err) - contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodGetSideChain]+extra, nil) + contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodGetSideChain], nil) tr1.Start() ret, leftOverGas, err = contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr1.Stop() @@ -239,7 +237,7 @@ func testApproveUpdateSideChain(t *testing.T) { result, err = utils.PackOutputs(ABI, side_chain_manager_abi.MethodGetSideChain, sideChain) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() tr1.Dump() @@ -260,9 +258,8 @@ func testQuiteSideChain(t *testing.T) { tr := native.NewTimer(side_chain_manager_abi.MethodQuitSideChain) for _, input := range [][]byte{input, input1} { blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodQuitSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodQuitSideChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -271,7 +268,7 @@ func testQuiteSideChain(t *testing.T) { result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodQuitSideChain) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) } tr.Dump() } @@ -291,9 +288,8 @@ func TestApproveQuiteSideChain(t *testing.T) { tr := native.NewTimer(side_chain_manager_abi.MethodApproveQuitSideChain) for i, input := range [][]byte{input, input1} { blockNumber := big.NewInt(1) - extra := uint64(10) caller := signers[0] - contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveQuitSideChain]+extra, nil) + contractRef := native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveQuitSideChain], nil) tr.Start() ret, leftOverGas, err := contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -302,10 +298,10 @@ func TestApproveQuiteSideChain(t *testing.T) { result, err := utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveUpdateSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) caller = signers[1] - contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveQuitSideChain]+extra, nil) + contractRef = native.NewContractRef(sdb, caller, caller, blockNumber, common.Hash{}, gasTable[side_chain_manager_abi.MethodApproveQuitSideChain], nil) tr.Start() ret, leftOverGas, err = contractRef.NativeCall(caller, utils.SideChainManagerContractAddress, input) tr.Stop() @@ -314,7 +310,7 @@ func TestApproveQuiteSideChain(t *testing.T) { result, err = utils.PackOutputs(ABI, side_chain_manager_abi.MethodApproveQuitSideChain, true) assert.Nil(t, err) assert.Equal(t, ret, result) - assert.Equal(t, leftOverGas, extra) + assert.Equal(t, leftOverGas, uint64(0)) contract := native.NewNativeContract(sdb, contractRef) sideChain, err := GetSideChainObject(contract, 8+uint64(i)) diff --git a/contracts/native/governance/signature_manager/signature_manager_test.go b/contracts/native/governance/signature_manager/signature_manager_test.go index 7c16ff73..bddd9082 100644 --- a/contracts/native/governance/signature_manager/signature_manager_test.go +++ b/contracts/native/governance/signature_manager/signature_manager_test.go @@ -121,6 +121,6 @@ func TestAddSignature(t *testing.T) { _, err = native.TestNativeCall(t, this, name, payload, common.Big0, sender, supplyGas, func(state *state.StateDB) { nm.StoreGenesisEpoch(state, peers, peers) }) - t.Error(err) + assert.Nil(t, err) } } diff --git a/contracts/native/helper/internal.go b/contracts/native/helper/internal.go deleted file mode 100644 index b92ff49b..00000000 --- a/contracts/native/helper/internal.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (C) 2021 The Zion Authors - * This file is part of The Zion library. - * - * The Zion is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Zion is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with The Zion. If not, see . - */ - -package helper - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/common/hexutil" - "github.com/ethereum/go-ethereum/core/state" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/internal/ethapi" - "github.com/ethereum/go-ethereum/light" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - "github.com/ethereum/go-ethereum/trie" -) - -func VerifyTx(proof []byte, hdr *types.Header, contract common.Address, extra []byte, checkResult bool) ([]byte, error) { - ethProof := new(ethapi.AccountResult) - if err := json.Unmarshal(proof, ethProof); err != nil { - return nil, fmt.Errorf("VerifyFromEthProof, unmarshal proof failed, err:%v", err) - } - - proofResult, err := VerifyAccountResult(ethProof, hdr, contract) - if err != nil { - return nil, fmt.Errorf("VerifyFromEthProof, verifyMerkleProof failed, err:%v", err) - } - if proofResult == nil { - return nil, fmt.Errorf("VerifyFromEthProof, verifyMerkleProof failed, err:%s", "proof result is nil") - } - if checkResult && !CheckProofResult(proofResult, extra) { - return nil, fmt.Errorf("VerifyFromEthProof, failed to check result, stored %s, got %s", hexutil.Encode(proofResult), hexutil.Encode(extra)) - } - return proofResult, nil -} - -func VerifyAccountResult(proof *ethapi.AccountResult, header *types.Header, contractAddr common.Address) ([]byte, error) { - if err := VerifyAccountProof(proof, header, contractAddr); err != nil { - return nil, err - } - return VerifyStorageProof(proof) -} - -func VerifyAccountProof(proof *ethapi.AccountResult, header *types.Header, contractAddr common.Address) error { - nodeList := new(light.NodeList) - for _, s := range proof.AccountProof { - nodeList.Put(nil, common.FromHex(s)) - } - ns := nodeList.NodeSet() - - if proof.Address != contractAddr { - return fmt.Errorf("verifyMerkleProof, contract address is error, proof address: %s, side chain address: %s", proof.Address.Hex(), contractAddr.Hex()) - } - acctKey := crypto.Keccak256(proof.Address[:]) - - // 2. verify account proof - acctVal, err := trie.VerifyProof(header.Root, acctKey, ns) - if err != nil { - return fmt.Errorf("verifyMerkleProof, verify account proof error:%s\n", err) - } - - acct := &state.Account{ - Nonce: uint64(proof.Nonce), - Balance: proof.Balance.ToInt(), - Root: proof.StorageHash, - CodeHash: proof.CodeHash[:], - } - - acctrlp, err := rlp.EncodeToBytes(acct) - if err != nil { - return err - } - - if !bytes.Equal(acctrlp, acctVal) { - return fmt.Errorf("verifyMerkleProof, verify account proof failed, wanted:%v, get:%v", acctrlp, acctVal) - } - - return nil -} - -func VerifyStorageProof(proof *ethapi.AccountResult) ([]byte, error) { - nodeList := new(light.NodeList) - if len(proof.StorageProof) != 1 { - return nil, fmt.Errorf("verifyMerkleProof, invalid storage proof format") - } - sp := proof.StorageProof[0] - storageKey := crypto.Keccak256(common.HexToHash(Replace0x(sp.Key)).Bytes()) - - for _, prf := range sp.Proof { - nodeList.Put(nil, common.Hex2Bytes(Replace0x(prf))) - } - ns := nodeList.NodeSet() - - val, err := trie.VerifyProof(proof.StorageHash, storageKey[:], ns) - if err != nil { - return nil, fmt.Errorf("verifyMerkleProof, verify storage proof error:%s\n", err) - } - return val, nil -} - -func Replace0x(s string) string { - return strings.Replace(strings.ToLower(s), "0x", "", 1) -} - -func CheckProofResult(result, value []byte) bool { - var s_temp []byte - err := rlp.DecodeBytes(result, &s_temp) - if err != nil { - log.Errorf("checkProofResult, rlp.DecodeBytes error:%s\n", err) - return false - } - // - var s []byte - for i := len(s_temp); i < 32; i++ { - s = append(s, 0) - } - s = append(s, s_temp...) - hash := crypto.Keccak256(value) - - return bytes.Equal(s, hash) -} diff --git a/contracts/native/helper/internal_test.go b/contracts/native/helper/internal_test.go deleted file mode 100644 index dd6969df..00000000 --- a/contracts/native/helper/internal_test.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2021 The Zion Authors - * This file is part of The Zion library. - * - * The Zion is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * The Zion is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with The Zion. If not, see . - */ - -package helper - -import ( - "encoding/json" - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/internal/ethapi" -) - -func TestVerifyAccountResult(t *testing.T) { - headerJson := `{"parentHash":"0xc4daea63055c5364fb42cb45c7f6eebf3277451c8d8ac984084e143b8c85c26d","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","miner":"0x8c09d936a1b408d6e0afaa537ba4e06c4504a0ae","stateRoot":"0x7f13d3173193b206527ff06ec2defb2cb79dd30fa09eba1c741a24aa71ad19f9","transactionsRoot":"0x41985aa48725b27456004e7596e64ccdaeb66ae38b5c42cdcc599072a123d566","receiptsRoot":"0x056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","difficulty":"0x1","number":"0xa933b","gasLimit":"0x7a1200","gasUsed":"0x5208","timestamp":"0x618262de","extraData":"0x0000000000000000000000000000000000000000000000000000000000000000f90197c0b841d68c498ce9f44f82cfd0aedba61701516858d8db76d991e07daf080cf24835991ceae0eaa46220db3087ccea3692cbd4ab50019ad1369608e6d74747fc52e0a701f9014fb841fc08d7eb36cb49673b8526bf680f3ce2bddadcd11623d4e69a3c7c3ce98ff94861e6efcec0a34451404eac2ae63e599c747c41d351da80b818ac8b2fe29d004100b841be610bc5e49b1b1f5e4330dcce624f05f3c4f9fd58563edf2edda5370f093e6c62c6c4f42538dc34eead3ee848ee92d4ebad9f4116d02922369b15e250ed426e00b8419056e2c70f710717333afc7879860cbe84cd43426c07c2e60b62f273494d4dba6d7845250b15933681a9d0c0a59c37e8bb91d5804131d110065a2b1885e4e66600b841e2348610285a035b89dbbc0dfb4b88b62c90b085839eb57bfb1e60c83edb0a052462c22bc50549b02703d71ec8cb7a3c1ad015979d5e913f2a6507d8f94e940b00b8415706cd4cd259665ec1987d2bf42a776dd90681478c19ee6c03444fa131d4fcef0a4d3ae1f9649fec11db195cbf3759c54a225a51b914bfc7ea1d518eded83e400080","mixHash":"0x63746963616c2062797a616e74696e65206661756c7420746f6c6572616e6365","nonce":"0x0000000000000000","hash":"0xe71005f3dea6edde3adcb5c4d95413d37bdbcc8c1ae136747cd5905a18081ec1"}` - proofJson := `{"address":"0x7559968a6395d67d1b14a33e461a07837fc76534","accountProof":["0xf90211a0dc645c1bc408c7455f7148dd7d0bdadc4828a3d68cec2a894cee43b04a8c6371a0b2d9749426507e67698679359be1f6465f9bc6c37232c4fd8aa4f8d5e69e79dea042171732bfeae1d9d706633b40137c6ce0c4cdcc8f3c64869247e183b2d7b41ea0fa6777985694d2c92862eceb62c50994aec2a5b77b75d9d6e4e6fbe4a21fc92fa09c689b8ff30656dd6c04061996042f42e4e99475658803ed66f46e54dde8812da03d1a791ef6a1e74dde297afbc721c8cc9630852676c8925bcbd8d65aa3ea7f6aa009461bf87644c5065244d7ab3cfd56b9770621cde1d443e75d789de64b7d162aa0073b6b94eebfc830252ce6acadac4698b9cf60acf8ec1fecd15066c7e5684bc8a0ff85ebfa2dd7a4eb5895861f4756db8739c509ee4a8944294ea748cdc7f1a88ca08ba8c6a349cc7088884c2d5c7d5f7cc31e2d8e5774aa7c8d92085366ab9c5553a0ef4f0a8df0a0793735df3123c78f6cfb72907940efdacf35a7717ccd431b70f8a0f3570db8b65c9dbda26648386018d8d28947b34ede83c2318a36437a9c17571ca0b560872d03afb2de3dd5664298524b092846e2fc297af7682cd39cfb3a16e892a0e7f9d44e75ce1ead9eab9eb4b9d34e960f37a0da3f7abff8ada31f323eb8f465a06844be9ba9b1a11bcba38962212457dad2a234ad4267859fd088ae10a9cef6aea0d3701d759ded6f12cb8cc69c67daf9ebd6854de2065653d65aa17b034dbdce0080","0xf901f1a037121ae504f846cc7feec07fce5bb8a484f14a87ea89a34d7852f1b8f906220aa0c5724ef803e16fbaadcb01fb53d71047614f87456d0940f840323f5b00b51ba4a0384183443feade18a1c4c32985076d4a476f1d8df6fe3d6a5ceb122aeac47683a0f3011005e25a4f657a66279d3476644bbe9a0190f4573bf9dc0ac94ca3b0071ea02be843a7b9919b3c983adf75bc97b88725c010271687547e2a2621a2f8572076a0065494029df72cdb469b6fa0a4a0dfb71cf81d23252b50b402a34b3b769964cfa0f629bcfa2e70e49819c05c567f1b493b07757ae408ad4f3b07d7fca85def010aa0dc3cef685c9d54a52856ae48d38834fa5166f5efaa86ec105d3263efd52d7016a0dcfe9cecc57294fcb25c20000f3a4a376fd90ac2edced927d19b051e09468578a04db064a86a09a7838b3ce7b690c7277f752319f9072aee642d958e8a80ef416ea0d10d5c56904ba0769e94b473472d95daa28487f55211b30aafde658c2deec48da05190053527e9b10ebfa1855e7049c54ae1da76650e122d3197520caf1e0ec45aa0767ea183e6bedb588f3341b2be3a4e732a6b7470b10a4e9cfdedcee9d93b4b42a0f5a3e1ae905310644a810d05d416ae27ecf821bb50a582628fa43bb3afa30a43a034802e794acdc4514d37ddf08648170cbb0e4d545c0c999e11cb2e55734df85a8080","0xf8d18080a08dc3fbeb5b35dbef92d1378c7ba8f20d894d4df739df7492dcd74fb96790704280808080a007551a8a7efd604c4437ddab5c08750f6a79926321e8c74fc9c0a8913d5ec3c0a022784e544b94f8f5f1626286113721efbcf30556a4886c2b233f5fd3c77c2134a0d11d6371f79aea13fc89c3c389f167cb54f012f172d91efd491ec5c60b946048a0906553817ed69ff29645fd05ba32d7418b5217c5aabc6ae7e5b098e5a3de9d8180a087968c8af6e9b8931ea798f9584bbc75597ce8dfead3c1b7634cd9b4f26559b280808080","0xf8729f3d23679c94d1d1529982d63fab85ee7275fd777d7e61214c4f4723068921dbb850f84e808a043c33c1937564800000a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"],"balance":"0x43c33c1937564800000","codeHash":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","nonce":"0x0","storageHash":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","storageProof":[{"key":"0x439d23679c94d1d1529982d63fab85ee7275fd777d7e61214c4f4723068921db","value":"0x0","proof":[]}]}` - - header := new(types.Header) - if err := header.UnmarshalJSON([]byte(headerJson)); err != nil { - t.Fatal(err) - } - - var proof ethapi.AccountResult - if err := json.Unmarshal([]byte(proofJson), &proof); err != nil { - t.Fatal(err) - } - - user := common.HexToAddress("0x7559968a6395d67d1b14a33e461a07837fc76534") - if _, err := VerifyAccountResult(&proof, header, user); err != nil { - t.Fatal(err) - } -} diff --git a/core/genesis.go b/core/genesis.go index f692d6c8..112953de 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -299,6 +299,8 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { g.createNativeContract(statedb, v) } RegGenesis(statedb, g) + } else { + g.mintNativeToken(statedb) } root := statedb.IntermediateRoot(false) @@ -390,14 +392,14 @@ func (g *Genesis) mintNativeToken(statedb *state.StateDB) { if total.Cmp(params.GenesisSupply) != 0 { panic("alloc amount should be equal to genesis supply") } + } - for addr, account := range g.Alloc { - statedb.AddBalance(addr, account.Balance) - statedb.SetCode(addr, account.Code) - statedb.SetNonce(addr, account.Nonce) - for key, value := range account.Storage { - statedb.SetState(addr, key, value) - } + for addr, account := range g.Alloc { + statedb.AddBalance(addr, account.Balance) + statedb.SetCode(addr, account.Code) + statedb.SetNonce(addr, account.Nonce) + for key, value := range account.Storage { + statedb.SetState(addr, key, value) } } } diff --git a/core/state_transition.go b/core/state_transition.go index 98e62f48..63c42f69 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -241,7 +241,7 @@ func (st *StateTransition) preCheck() error { } // This will panic if baseFee is nil, but basefee presence is verified // as part of header validation. - if st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 { + if st.gasFeeCap.Cmp(st.evm.Context.BaseFee) < 0 && st.msg.From() != utils.SystemTxSender { return fmt.Errorf("%w: address %v, maxFeePerGas: %s baseFee: %s", ErrFeeCapTooLow, st.msg.From().Hex(), st.gasFeeCap, st.evm.Context.BaseFee) } diff --git a/core/tx_pool.go b/core/tx_pool.go index 41689ba1..e2d1db75 100644 --- a/core/tx_pool.go +++ b/core/tx_pool.go @@ -18,13 +18,14 @@ package core import ( "errors" - "github.com/ethereum/go-ethereum/consensus/misc" "math" "math/big" "sort" "sync" "time" + "github.com/ethereum/go-ethereum/consensus/misc" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/prque" "github.com/ethereum/go-ethereum/core/state" diff --git a/core/types/block.go b/core/types/block.go index 4e2c141c..7240577f 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -114,25 +114,7 @@ func SealHash(header *Header) (hash common.Hash) { } hasher := sha3.NewLegacyKeccak256() - enc := []interface{}{ - header.ParentHash, - header.UncleHash, - header.Coinbase, - header.Root, - header.TxHash, - header.ReceiptHash, - header.Bloom, - header.Difficulty, - header.Number, - header.GasLimit, - header.GasUsed, - header.Time, - header.Extra, - } - if header.BaseFee != nil { - enc = append(enc, header.BaseFee) - } - rlp.Encode(hasher, enc) + rlp.Encode(hasher, header) hasher.Sum(hash[:0]) return hash } diff --git a/miner/miner.go b/miner/miner.go index 34ca2049..603f1ec7 100644 --- a/miner/miner.go +++ b/miner/miner.go @@ -78,12 +78,16 @@ func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *even } // hotstuff: disable pre-sealing, and waiting for p2p server connections - protocol := hotstuff.HotstuffProtocol(chainConfig.HotStuff.Protocol) - switch protocol { - case hotstuff.HOTSTUFF_PROTOCOL_BASIC: - miner.worker = newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true) - miner.EnablePreseal() - default: + if chainConfig.HotStuff != nil { + protocol := hotstuff.HotstuffProtocol(chainConfig.HotStuff.Protocol) + switch protocol { + case hotstuff.HOTSTUFF_PROTOCOL_BASIC: + miner.worker = newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true) + miner.EnablePreseal() + default: + log.Crit("Unknown hotstuff protocal", "protocal", protocol) + } + } else { miner.worker = newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true) } diff --git a/miner/worker.go b/miner/worker.go index 1c6c2b0b..71832512 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -57,7 +57,7 @@ const ( // minRecommitInterval is the minimal time interval to recreate the mining block with // any newly arrived transactions. - minRecommitInterval = 20 * time.Second + minRecommitInterval = 3 * time.Second // maxRecommitInterval is the maximum time interval to recreate the mining block with // any newly arrived transactions. @@ -223,7 +223,10 @@ func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus go worker.resultLoop() go worker.taskLoop() - worker.startCh <- struct{}{} + // Submit first work to initialize pending state. + if init { + worker.startCh <- struct{}{} + } return worker } @@ -378,6 +381,7 @@ func (w *worker) newWorkLoop(recommit time.Duration) { // If mining is running resubmit a new work cycle periodically to pull in // higher priced transactions. Disable this overhead for pending blocks. if w.IsRunning() && (w.chainConfig.HotStuff != nil && w.chainConfig.HotStuff.Protocol != "") { + timestamp = time.Now().Unix() log.Debug("Miner resubmit work", "timestamp", timestamp, "from", minRecommit) commit(commitInterruptResubmit) } @@ -864,10 +868,8 @@ func (w *worker) commitNewWork(interrupt *int32, timestamp int64) { w.mu.RLock() defer w.mu.RUnlock() - // just use current time as block timestamp tstart := time.Now() parent := w.chain.CurrentBlock() - timestamp = tstart.Unix() num := parent.Number() header := &types.Header{ diff --git a/miner/worker_test.go b/miner/worker_test.go index b267a74d..003987b2 100644 --- a/miner/worker_test.go +++ b/miner/worker_test.go @@ -89,6 +89,7 @@ func init() { To: &testUserAddress, Value: big.NewInt(1000), Gas: params.TxGas, + GasPrice: big.NewInt(params.InitialBaseFee), }) pendingTxs = append(pendingTxs, tx1) @@ -97,6 +98,7 @@ func init() { To: &testUserAddress, Value: big.NewInt(1000), Gas: params.TxGas, + GasPrice: big.NewInt(params.InitialBaseFee), }) newTxs = append(newTxs, tx2) @@ -244,12 +246,12 @@ func testGenerateBlockAndImport(t *testing.T, isClique bool) { // Start mining! w.Start() + time.Sleep(time.Second) for i := 0; i < 5; i++ { b.txPool.AddLocal(b.newRandomTx(true)) b.txPool.AddLocal(b.newRandomTx(false)) - //w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) - //w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()}) + w.newWorkCh <- &newWorkReq{timestamp: time.Now().Unix()} select { case ev := <-sub.Chan(): @@ -257,6 +259,7 @@ func testGenerateBlockAndImport(t *testing.T, isClique bool) { if _, err := chain.InsertChain([]*types.Block{block}); err != nil { t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err) } + time.Sleep(time.Second * 1) case <-time.After(3 * time.Second): // Worker needs 1s to include new changes. t.Fatalf("timeout") } @@ -283,7 +286,7 @@ func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consens checkEqual := func(t *testing.T, task *task, index int) { // The first empty work without any txs included receiptLen, balance := 0, big.NewInt(0) - if index == 1 { + if index == 0 { // The second full work with 1 tx included receiptLen, balance = 1, big.NewInt(1000) } @@ -306,7 +309,7 @@ func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consens time.Sleep(100 * time.Millisecond) } w.Start() // Start mining! - for i := 0; i < 2; i += 1 { + for i := 0; i < 1; i += 1 { select { case <-taskCh: case <-time.NewTimer(3 * time.Second).C: @@ -330,7 +333,7 @@ func TestStreamUncleBlock(t *testing.T) { // The first task is an empty task, the second // one has 1 pending tx, the third one has 1 tx // and 1 uncle. - if taskIndex == 2 { + if taskIndex == 1 { have := task.block.Header().UncleHash want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()}) if have != want { @@ -349,16 +352,6 @@ func TestStreamUncleBlock(t *testing.T) { } w.Start() - for i := 0; i < 2; i += 1 { - select { - case <-taskCh: - case <-time.NewTimer(time.Second).C: - t.Error("new task timeout") - } - } - - //w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock}) - select { case <-taskCh: case <-time.NewTimer(time.Second).C: @@ -387,7 +380,7 @@ func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, en if task.block.NumberU64() == 1 { // The first task is an empty task, the second // one has 1 pending tx, the third one has 2 txs - if taskIndex == 2 { + { receiptLen, balance := 2, big.NewInt(2000) if len(task.receipts) != receiptLen { t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen) @@ -407,16 +400,8 @@ func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, en time.Sleep(100 * time.Millisecond) } - w.Start() - // Ignore the first two works - for i := 0; i < 2; i += 1 { - select { - case <-taskCh: - case <-time.NewTimer(time.Second).C: - t.Error("new task timeout") - } - } b.txPool.AddLocals(newTxs) + w.Start() time.Sleep(time.Second) select { @@ -472,15 +457,15 @@ func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine co estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias) wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond case 3: - wantMinInterval, wantRecommitInterval = time.Second, time.Second + wantMinInterval, wantRecommitInterval = 3 * time.Second, 3* time.Second } // Check interval if minInterval != wantMinInterval { - t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval) + t.Errorf("resubmit min interval mismatch: have %v, want %v , index %v", minInterval, wantMinInterval, index) } if recommitInterval != wantRecommitInterval { - t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval) + t.Errorf("resubmit interval mismatch: have %v, want %v, index %v", recommitInterval, wantRecommitInterval, index) } result = append(result, float64(recommitInterval.Nanoseconds())) index += 1