diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 698f0156e4..30c790d2cd 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -1227,7 +1227,7 @@ func (b *Blockchain) writeHeaderImpl(evnt *Event, header *types.Header) error { currentTD, ok := b.readTotalDifficulty(currentHeader.Hash) if !ok { - panic("failed to get header difficulty") + return errors.New("failed to get header difficulty") } // parent total difficulty of incoming header diff --git a/blockchain/storage/keyvalue.go b/blockchain/storage/keyvalue.go index 9d2421facf..fd1494e86f 100644 --- a/blockchain/storage/keyvalue.go +++ b/blockchain/storage/keyvalue.go @@ -261,7 +261,7 @@ func (s *KeyValueStorage) ReadTxLookup(hash types.Hash) (types.Hash, bool) { blockHash, err := v.GetBytes(blockHash[:0], 32) if err != nil { - panic(err) + return types.Hash{}, false } return types.BytesToHash(blockHash), true diff --git a/blockchain/storage/testing.go b/blockchain/storage/testing.go index 3fe1fe6ea0..63330b2d4e 100644 --- a/blockchain/storage/testing.go +++ b/blockchain/storage/testing.go @@ -264,7 +264,7 @@ func testBody(t *testing.T, m PlaceholderStorage) { ExtraData: []byte{}, // if not set it will fail } if err := s.WriteHeader(header); err != nil { - panic(err) + t.Fatal(err) } addr1 := types.StringToAddress("11") @@ -297,9 +297,7 @@ func testBody(t *testing.T, m PlaceholderStorage) { } body0 := block.Body() - if err := s.WriteBody(header.Hash, body0); err != nil { - panic(err) - } + assert.NoError(t, s.WriteBody(header.Hash, body0)) body1, err := s.ReadBody(header.Hash) assert.NoError(t, err) diff --git a/command/polybftsecrets/params.go b/command/polybftsecrets/params.go index 41e116aa5e..f35d2bea13 100644 --- a/command/polybftsecrets/params.go +++ b/command/polybftsecrets/params.go @@ -186,7 +186,11 @@ func (ip *initParams) initKeys(secretsManager secrets.SecretsManager) ([]string, ) if !secretsManager.HasSecret(secrets.ValidatorKey) && !secretsManager.HasSecret(secrets.ValidatorBLSKey) { - a = wallet.GenerateAccount() + a, err = wallet.GenerateAccount() + if err != nil { + return generated, fmt.Errorf("error generating account: %w", err) + } + if err = a.Save(secretsManager); err != nil { return generated, fmt.Errorf("error saving account: %w", err) } diff --git a/command/polybftsecrets/utils.go b/command/polybftsecrets/utils.go index f78d5fdf8c..9507c0cb31 100644 --- a/command/polybftsecrets/utils.go +++ b/command/polybftsecrets/utils.go @@ -35,7 +35,9 @@ func GetSecretsManager(dataPath, configPath string, insecureLocalStore bool) (se if configPath != "" { secretsConfig, readErr := secrets.ReadConfig(configPath) if readErr != nil { - return nil, fmt.Errorf("%s: %w", ErrInvalidConfig.Error(), readErr) + invalidConfigErr := ErrInvalidConfig.Error() + + return nil, fmt.Errorf("%s: %w", invalidConfigErr, readErr) } if !secrets.SupportedServiceManager(secretsConfig.Type) { diff --git a/consensus/ibft/fork/hooks_test.go b/consensus/ibft/fork/hooks_test.go index 3c6585e6f8..06c5b06dc1 100644 --- a/consensus/ibft/fork/hooks_test.go +++ b/consensus/ibft/fork/hooks_test.go @@ -17,6 +17,7 @@ import ( "github.com/0xPolygon/polygon-edge/validators/store" "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type mockHeaderModifierStore struct { @@ -281,7 +282,9 @@ func newTestTransition( Forks: chain.AllForksEnabled, }, st, hclog.NewNullLogger()) - rootHash := ex.WriteGenesis(nil) + rootHash, err := ex.WriteGenesis(nil) + require.NoError(t, err) + ex.GetHash = func(h *types.Header) state.GetHashByNumber { return func(i uint64) types.Hash { return rootHash diff --git a/consensus/ibft/helper_test.go b/consensus/ibft/helper_test.go index 0f12b70789..c6761f430c 100644 --- a/consensus/ibft/helper_test.go +++ b/consensus/ibft/helper_test.go @@ -8,6 +8,7 @@ import ( "github.com/0xPolygon/polygon-edge/crypto" "github.com/0xPolygon/polygon-edge/types" "github.com/0xPolygon/polygon-edge/validators" + "github.com/stretchr/testify/require" ) type testerAccount struct { @@ -55,9 +56,7 @@ func (ap *testerAccountPool) add(accounts ...string) { } priv, err := crypto.GenerateECDSAKey() - if err != nil { - panic("BUG: Failed to generate crypto key") - } + require.NoError(ap.t, err) ap.accounts = append(ap.accounts, &testerAccount{ alias: account, diff --git a/consensus/polybft/blockchain_wrapper.go b/consensus/polybft/blockchain_wrapper.go index 2af57a5b78..33f11280c1 100644 --- a/consensus/polybft/blockchain_wrapper.go +++ b/consensus/polybft/blockchain_wrapper.go @@ -208,5 +208,5 @@ func (s *stateProvider) Call(addr ethgo.Address, input []byte, opts *contract.Ca // Txn is part of the contract.Provider interface to make Ethereum transactions. We disable this function // since the system state does not make any transaction func (s *stateProvider) Txn(ethgo.Address, ethgo.Key, []byte) (contract.Txn, error) { - panic(errSendTxnUnsupported) + return nil, errSendTxnUnsupported } diff --git a/consensus/polybft/checkpoint_manager_test.go b/consensus/polybft/checkpoint_manager_test.go index 8473553da6..e91fd2ccb1 100644 --- a/consensus/polybft/checkpoint_manager_test.go +++ b/consensus/polybft/checkpoint_manager_test.go @@ -36,7 +36,7 @@ func TestCheckpointManager_SubmitCheckpoint(t *testing.T) { var aliases = []string{"A", "B", "C", "D", "E"} - validators := newTestValidatorsWithAliases(aliases) + validators := newTestValidatorsWithAliases(t, aliases) validatorsMetadata := validators.getPublicIdentities() txRelayerMock := newDummyTxRelayer(t) txRelayerMock.On("Call", mock.Anything, mock.Anything, mock.Anything). @@ -122,8 +122,8 @@ func TestCheckpointManager_abiEncodeCheckpointBlock(t *testing.T) { const epochSize = uint64(10) - currentValidators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D"}) - nextValidators := newTestValidatorsWithAliases([]string{"E", "F", "G", "H"}) + currentValidators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D"}) + nextValidators := newTestValidatorsWithAliases(t, []string{"E", "F", "G", "H"}) header := &types.Header{Number: 50} checkpoint := &CheckpointData{ BlockRound: 1, @@ -213,10 +213,12 @@ func TestCheckpointManager_getCurrentCheckpointID(t *testing.T) { txRelayerMock.On("Call", mock.Anything, mock.Anything, mock.Anything). Return(c.checkpointID, c.returnError). Once() + acc, err := wallet.GenerateAccount() + require.NoError(t, err) checkpointMgr := &checkpointManager{ rootChainRelayer: txRelayerMock, - key: wallet.GenerateAccount().Ecdsa, + key: acc.Ecdsa, logger: hclog.NewNullLogger(), } actualCheckpointID, err := checkpointMgr.getLatestCheckpointBlock() diff --git a/consensus/polybft/consensus_runtime_test.go b/consensus/polybft/consensus_runtime_test.go index ff7f00e145..cf06c3eb4b 100644 --- a/consensus/polybft/consensus_runtime_test.go +++ b/consensus/polybft/consensus_runtime_test.go @@ -183,7 +183,7 @@ func TestConsensusRuntime_OnBlockInserted_EndOfEpoch(t *testing.T) { ) currentEpochNumber := getEpochNumber(t, epochSize, epochSize) - validatorSet := newTestValidators(validatorsCount).getPublicIdentities() + validatorSet := newTestValidators(t, validatorsCount).getPublicIdentities() header, headerMap := createTestBlocks(t, epochSize, epochSize, validatorSet) builtBlock := consensus.BuildBlock(consensus.BuildBlockParams{ Header: header, @@ -289,7 +289,7 @@ func TestConsensusRuntime_OnBlockInserted_MiddleOfEpoch(t *testing.T) { func TestConsensusRuntime_FSM_NotInValidatorSet(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D"}) snapshot := NewProposerSnapshot(1, nil) config := &runtimeConfig{ @@ -324,7 +324,7 @@ func TestConsensusRuntime_FSM_NotEndOfEpoch_NotEndOfSprint(t *testing.T) { ExtraData: append(make([]byte, ExtraVanity), extra.MarshalRLPTo(nil)...), } - validators := newTestValidators(3) + validators := newTestValidators(t, 3) blockchainMock := new(blockchainMock) blockchainMock.On("NewBlockBuilder", mock.Anything).Return(&BlockBuilder{}, nil).Once() @@ -382,7 +382,7 @@ func TestConsensusRuntime_FSM_EndOfEpoch_BuildCommitEpoch(t *testing.T) { toIndex = uint64(9) ) - validatorAccounts := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validatorAccounts := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) validators := validatorAccounts.getPublicIdentities() lastBuiltBlock, headerMap := createTestBlocks(t, 9, epochSize, validators) @@ -450,7 +450,7 @@ func Test_NewConsensusRuntime(t *testing.T) { BlockTime: 2 * time.Second, } - validators := newTestValidators(3).getPublicIdentities() + validators := newTestValidators(t, 3).getPublicIdentities() systemStateMock := new(systemStateMock) systemStateMock.On("GetEpoch").Return(uint64(1)).Once() @@ -497,7 +497,7 @@ func TestConsensusRuntime_restartEpoch_SameEpochNumberAsTheLastOne(t *testing.T) const originalBlockNumber = uint64(5) newCurrentHeader := &types.Header{Number: originalBlockNumber + 1} - validatorSet := newTestValidators(3).getPublicIdentities() + validatorSet := newTestValidators(t, 3).getPublicIdentities() systemStateMock := new(systemStateMock) systemStateMock.On("GetEpoch").Return(uint64(1), nil).Once() @@ -547,7 +547,7 @@ func TestConsensusRuntime_calculateCommitEpochInput_SecondEpoch(t *testing.T) { sprintSize = 5 ) - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}) polybftConfig := &PolyBFTConfig{ ValidatorSetAddr: contracts.ValidatorSetContract, EpochSize: epochSize, @@ -596,7 +596,7 @@ func TestConsensusRuntime_IsValidValidator_BasicCases(t *testing.T) { setupFn := func(t *testing.T) (*consensusRuntime, *testValidators) { t.Helper() - validatorAccounts := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validatorAccounts := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) epoch := &epochMetadata{ Validators: validatorAccounts.getPublicIdentities("A", "B", "C", "D"), } @@ -654,7 +654,7 @@ func TestConsensusRuntime_IsValidValidator_BasicCases(t *testing.T) { func TestConsensusRuntime_IsValidValidator_TamperSignature(t *testing.T) { t.Parallel() - validatorAccounts := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validatorAccounts := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) epoch := &epochMetadata{ Validators: validatorAccounts.getPublicIdentities("A", "B", "C", "D"), } @@ -676,7 +676,7 @@ func TestConsensusRuntime_IsValidValidator_TamperSignature(t *testing.T) { func TestConsensusRuntime_TamperMessageContent(t *testing.T) { t.Parallel() - validatorAccounts := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validatorAccounts := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) epoch := &epochMetadata{ Validators: validatorAccounts.getPublicIdentities("A", "B", "C", "D"), } @@ -838,7 +838,7 @@ func TestConsensusRuntime_HasQuorum(t *testing.T) { const round = 5 - validatorAccounts := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validatorAccounts := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) extra := &Extra{ Checkpoint: &CheckpointData{}, diff --git a/consensus/polybft/contractsapi/artifacts-gen/main.go b/consensus/polybft/contractsapi/artifacts-gen/main.go index 58f2c29089..21a033f961 100644 --- a/consensus/polybft/contractsapi/artifacts-gen/main.go +++ b/consensus/polybft/contractsapi/artifacts-gen/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log" "os" "path" "runtime" @@ -87,7 +88,7 @@ func main() { for _, v := range readContracts { artifactBytes, err := artifact.ReadArtifactData(scpath, v.Path, v.Name) if err != nil { - panic(err) + log.Fatal(err) } f.Var().Id(v.Name + "Artifact").String().Op("=").Lit(string(artifactBytes)) @@ -95,11 +96,11 @@ func main() { fl, err := os.Create(currentPath + "/../gen_sc_data.go") if err != nil { - panic(err) + log.Fatal(err) } _, err = fmt.Fprintf(fl, "%#v", f) if err != nil { - panic(err) + log.Fatal(err) } } diff --git a/consensus/polybft/contractsapi/bindings-gen/main.go b/consensus/polybft/contractsapi/bindings-gen/main.go index 5983302c40..546cdae83e 100644 --- a/consensus/polybft/contractsapi/bindings-gen/main.go +++ b/consensus/polybft/contractsapi/bindings-gen/main.go @@ -2,9 +2,11 @@ package main import ( "bytes" + "errors" "fmt" "go/format" "io/ioutil" + "log" "strconv" "strings" "text/template" @@ -132,11 +134,15 @@ func main() { for _, c := range cases { for _, method := range c.functions { - generateFunction(generatedData, c.contractName, c.artifact.Abi.Methods[method]) + if err := generateFunction(generatedData, c.contractName, c.artifact.Abi.Methods[method]); err != nil { + log.Fatal(err) + } } for _, event := range c.events { - generateEvent(generatedData, c.contractName, c.artifact.Abi.Events[event]) + if err := generateEvent(generatedData, c.contractName, c.artifact.Abi.Events[event]); err != nil { + log.Fatal(err) + } } } @@ -157,11 +163,11 @@ import ( output, err := format.Source([]byte(str)) if err != nil { fmt.Println(str) - panic(err) + log.Fatal(err) } if err := ioutil.WriteFile("./consensus/polybft/contractsapi/contractsapi.go", output, 0600); err != nil { - panic(err) + log.Fatal(err) } } @@ -183,9 +189,9 @@ func getInternalType(paramName string, paramAbiType *abi.Type) string { } // generateType generates code for structs used in smart contract functions and events -func generateType(generatedData *generatedData, name string, obj *abi.Type, res *[]string) string { +func generateType(generatedData *generatedData, name string, obj *abi.Type, res *[]string) (string, error) { if obj.Kind() != abi.KindTuple { - panic("BUG: Not expected") + return "", errors.New("type not expected") } internalType := getInternalType(name, obj) @@ -202,14 +208,28 @@ func generateType(generatedData *generatedData, name string, obj *abi.Type, res if elem.Kind() == abi.KindTuple { // Struct - typ = generateNestedType(generatedData, tupleElem.Name, elem, res) + nestedType, err := generateNestedType(generatedData, tupleElem.Name, elem, res) + if err != nil { + return "", err + } + + typ = nestedType } else if elem.Kind() == abi.KindSlice && elem.Elem().Kind() == abi.KindTuple { // []Struct - typ = "[]" + generateNestedType(generatedData, getInternalType(tupleElem.Name, elem), elem.Elem(), res) + nestedType, err := generateNestedType(generatedData, getInternalType(tupleElem.Name, elem), elem.Elem(), res) + if err != nil { + return "", err + } + + typ = "[]" + nestedType } else if elem.Kind() == abi.KindArray && elem.Elem().Kind() == abi.KindTuple { // [n]Struct - typ = "[" + strconv.Itoa(elem.Size()) + "]" + - generateNestedType(generatedData, getInternalType(tupleElem.Name, elem), elem.Elem(), res) + nestedType, err := generateNestedType(generatedData, getInternalType(tupleElem.Name, elem), elem.Elem(), res) + if err != nil { + return "", err + } + + typ = "[" + strconv.Itoa(elem.Size()) + "]" + nestedType } else if elem.Kind() == abi.KindAddress { // for address use the native `types.Address` type instead of `ethgo.Address`. Note that // this only works for simple types and not for []address inputs. This is good enough since @@ -239,28 +259,38 @@ func generateType(generatedData *generatedData, name string, obj *abi.Type, res str = append(str, "}") *res = append(*res, strings.Join(str, "\n")) - return internalType + return internalType, nil } // generateNestedType generates code for nested types found in smart contracts structs -func generateNestedType(generatedData *generatedData, name string, obj *abi.Type, res *[]string) string { +func generateNestedType(generatedData *generatedData, name string, obj *abi.Type, res *[]string) (string, error) { for _, s := range generatedData.structs { if s == name { // do not generate the same type again if it's already generated // this happens when two functions use the same struct type as one of its parameters - return "*" + name + return "*" + name, nil } } - result := generateType(generatedData, name, obj, res) + result, err := generateType(generatedData, name, obj, res) + if err != nil { + return "", err + } + *res = append(*res, fmt.Sprintf(abiTypeNameFormat, result, obj.Format(true))) - *res = append(*res, generateAbiFuncsForNestedType(result)) - return "*" + result + nestedTypeFunctions, err := generateAbiFuncsForNestedType(result) + if err != nil { + return "", err + } + + *res = append(*res, nestedTypeFunctions) + + return "*" + result, nil } // generateAbiFuncsForNestedType generates necessary functions for nested types smart contracts interaction -func generateAbiFuncsForNestedType(name string) string { +func generateAbiFuncsForNestedType(name string) (string, error) { tmpl := `func ({{.Sig}} *{{.TName}}) EncodeAbi() ([]byte, error) { return {{.Name}}ABIType.Encode({{.Sig}}) } @@ -281,11 +311,14 @@ func generateAbiFuncsForNestedType(name string) string { } // generateEvent generates code for smart contract events -func generateEvent(generatedData *generatedData, contractName string, event *abi.Event) { +func generateEvent(generatedData *generatedData, contractName string, event *abi.Event) error { name := fmt.Sprintf(eventNameFormat, event.Name) - res := []string{} - generateType(generatedData, name, event.Inputs, &res) + + _, err := generateType(generatedData, name, event.Inputs, &res) + if err != nil { + return err + } // write encode/decode functions tmplStr := ` @@ -305,11 +338,18 @@ func ({{.Sig}} *{{.TName}}) ParseLog(log *ethgo.Log) error { "ContractName": contractName, } - generatedData.resultString = append(generatedData.resultString, renderTmpl(tmplStr, inputs)) + renderedString, err := renderTmpl(tmplStr, inputs) + if err != nil { + return err + } + + generatedData.resultString = append(generatedData.resultString, renderedString) + + return nil } // generateFunction generates code for smart contract function and its parameters -func generateFunction(generatedData *generatedData, contractName string, method *abi.Method) { +func generateFunction(generatedData *generatedData, contractName string, method *abi.Method) error { methodName := method.Name if methodName == "initialize" { // most of the contracts have initialize function, which differ in params @@ -320,7 +360,11 @@ func generateFunction(generatedData *generatedData, contractName string, method methodName = fmt.Sprintf(functionNameFormat, methodName) res := []string{} - generateType(generatedData, methodName, method.Inputs, &res) + + _, err := generateType(generatedData, methodName, method.Inputs, &res) + if err != nil { + return err + } // write encode/decode functions tmplStr := ` @@ -336,51 +380,34 @@ func ({{.Sig}} *{{.TName}}) DecodeAbi(buf []byte) error { return decodeMethod({{.ContractName}}.Abi.Methods["{{.Name}}"], buf, {{.Sig}}) }` - methodType := "function " + method.Name + "(" - if len(method.Inputs.TupleElems()) != 0 { - methodType += encodeFuncTuple(method.Inputs) - } - - methodType += ")" - - if len(method.Outputs.TupleElems()) != 0 { - methodType += "(" + encodeFuncTuple(method.Outputs) + ")" - } - inputs := map[string]interface{}{ "Structs": res, - "Type": methodType, "Sig": strings.ToLower(string(methodName[0])), "Name": method.Name, "ContractName": contractName, "TName": strings.Title(methodName), } - generatedData.resultString = append(generatedData.resultString, renderTmpl(tmplStr, inputs)) + renderedString, err := renderTmpl(tmplStr, inputs) + if err != nil { + return err + } + + generatedData.resultString = append(generatedData.resultString, renderedString) + + return nil } -func renderTmpl(tmplStr string, inputs map[string]interface{}) string { +func renderTmpl(tmplStr string, inputs map[string]interface{}) (string, error) { tmpl, err := template.New("name").Parse(tmplStr) if err != nil { - panic(fmt.Sprintf("BUG: Failed to load template: %v", err)) + return "", fmt.Errorf("failed to load template: %w", err) } var tpl bytes.Buffer if err = tmpl.Execute(&tpl, inputs); err != nil { - panic(fmt.Sprintf("BUG: Failed to render template: %v", err)) + return "", fmt.Errorf("failed to render template: %w", err) } - return tpl.String() -} - -func encodeFuncTuple(t *abi.Type) string { - if t.Kind() != abi.KindTuple { - panic("BUG: Kind different than tuple not expected") - } - - str := t.Format(true) - str = strings.TrimPrefix(str, "tuple(") - str = strings.TrimSuffix(str, ")") - - return str + return tpl.String(), nil } diff --git a/consensus/polybft/contractsapi/init.go b/consensus/polybft/contractsapi/init.go index 2c5266778f..43870d2829 100644 --- a/consensus/polybft/contractsapi/init.go +++ b/consensus/polybft/contractsapi/init.go @@ -2,6 +2,7 @@ package contractsapi import ( "embed" + "log" "path" "github.com/0xPolygon/polygon-edge/consensus/polybft/contractsapi/artifact" @@ -41,94 +42,94 @@ func init() { CheckpointManager, err = artifact.DecodeArtifact([]byte(CheckpointManagerArtifact)) if err != nil { - panic(err) + log.Fatal(err) } ExitHelper, err = artifact.DecodeArtifact([]byte(ExitHelperArtifact)) if err != nil { - panic(err) + log.Fatal(err) } L2StateSender, err = artifact.DecodeArtifact([]byte(L2StateSenderArtifact)) if err != nil { - panic(err) + log.Fatal(err) } BLS, err = artifact.DecodeArtifact([]byte(BLSArtifact)) if err != nil { - panic(err) + log.Fatal(err) } BLS256, err = artifact.DecodeArtifact([]byte(BN256G2Artifact)) if err != nil { - panic(err) + log.Fatal(err) } Merkle, err = artifact.DecodeArtifact([]byte(MerkleArtifact)) if err != nil { - panic(err) + log.Fatal(err) } StateSender, err = artifact.DecodeArtifact([]byte(StateSenderArtifact)) if err != nil { - panic(err) + log.Fatal(err) } RootERC20Predicate, err = artifact.DecodeArtifact([]byte(RootERC20PredicateArtifact)) if err != nil { - panic(err) + log.Fatal(err) } StateReceiver, err = artifact.DecodeArtifact([]byte(StateReceiverArtifact)) if err != nil { - panic(err) + log.Fatal(err) } System, err = artifact.DecodeArtifact([]byte(SystemArtifact)) if err != nil { - panic(err) + log.Fatal(err) } ChildERC20, err = artifact.DecodeArtifact([]byte(ChildERC20Artifact)) if err != nil { - panic(err) + log.Fatal(err) } ChildERC20Predicate, err = artifact.DecodeArtifact([]byte(ChildERC20PredicateArtifact)) if err != nil { - panic(err) + log.Fatal(err) } ChildValidatorSet, err = artifact.DecodeArtifact([]byte(ChildValidatorSetArtifact)) if err != nil { - panic(err) + log.Fatal(err) } NativeERC20, err = artifact.DecodeArtifact([]byte(NativeERC20Artifact)) if err != nil { - panic(err) + log.Fatal(err) } RootERC20, err = artifact.DecodeArtifact([]byte(MockERC20Artifact)) if err != nil { - panic(err) + log.Fatal(err) } TestL1StateReceiver, err = artifact.DecodeArtifact(readTestContractContent("TestL1StateReceiver.json")) if err != nil { - panic(err) + log.Fatal(err) } TestWriteBlockMetadata, err = artifact.DecodeArtifact(readTestContractContent("TestWriteBlockMetadata.json")) if err != nil { - panic(err) + log.Fatal(err) } } func readTestContractContent(contractFileName string) []byte { contractRaw, err := testContracts.ReadFile(path.Join(testContractsDir, contractFileName)) if err != nil { - panic(err) + log.Fatal(err) } return contractRaw diff --git a/consensus/polybft/extra_test.go b/consensus/polybft/extra_test.go index f6c661bfc9..502508496a 100644 --- a/consensus/polybft/extra_test.go +++ b/consensus/polybft/extra_test.go @@ -27,7 +27,7 @@ func TestExtra_Encoding(t *testing.T) { committedStr := []byte("Here is the committed signature") bitmapStr := []byte("Here are the bitmap bytes") - addedValidators := newTestValidatorsWithAliases([]string{"A", "B", "C"}).getPublicIdentities() + addedValidators := newTestValidatorsWithAliases(t, []string{"A", "B", "C"}).getPublicIdentities() removedValidators := bitmap.Bitmap{} removedValidators.Set(2) @@ -186,7 +186,9 @@ func TestExtra_UnmarshalRLPWith_NegativeCases(t *testing.T) { extraMarshalled.Set(ar.NewBytes([]byte{})) // Seal // Parent - key := wallet.GenerateAccount() + key, err := wallet.GenerateAccount() + require.NoError(t, err) + parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash([]byte("This is test hash"))) extraMarshalled.Set(parentSignature.MarshalRLPWith(ar)) @@ -207,7 +209,9 @@ func TestExtra_UnmarshalRLPWith_NegativeCases(t *testing.T) { extraMarshalled.Set(ar.NewBytes([]byte{})) // Seal // Parent - key := wallet.GenerateAccount() + key, err := wallet.GenerateAccount() + require.NoError(t, err) + parentSignature := createSignature(t, []*wallet.Account{key}, types.BytesToHash(generateRandomBytes(t))) extraMarshalled.Set(parentSignature.MarshalRLPWith(ar)) @@ -242,7 +246,7 @@ func TestExtra_ValidateFinalizedData_UnhappyPath(t *testing.T) { Hash: types.BytesToHash(generateRandomBytes(t)), } - validators := newTestValidators(6) + validators := newTestValidators(t, 6) polyBackendMock := new(polybftBackendMock) polyBackendMock.On("GetValidators", mock.Anything, mock.Anything).Return(nil, errors.New("validators not found")) @@ -317,7 +321,7 @@ func TestExtra_ValidateParentSignatures(t *testing.T) { require.ErrorContains(t, err, fmt.Sprintf("failed to verify signatures for parent of block %d because signatures are not present", headerNum)) // validators not found - validators := newTestValidators(5) + validators := newTestValidators(t, 5) incorrectHash := types.BytesToHash([]byte("Hello World")) invalidSig := createSignature(t, validators.getPrivateIdentities(), incorrectHash) extra = &Extra{Parent: invalidSig} @@ -359,7 +363,7 @@ func TestSignature_Verify(t *testing.T) { numValidators := 100 msgHash := types.Hash{0x1} - vals := newTestValidators(numValidators) + vals := newTestValidators(t, numValidators) validatorsMetadata := vals.getPublicIdentities() validatorSet := vals.toValidatorSet() @@ -396,7 +400,7 @@ func TestSignature_Verify(t *testing.T) { t.Run("Invalid bitmap provided", func(t *testing.T) { t.Parallel() - validatorSet := newTestValidators(3).getPublicIdentities() + validatorSet := newTestValidators(t, 3).getPublicIdentities() bmp := bitmap.Bitmap{} // Make bitmap invalid, by setting some flag larger than length of validator set to 1 @@ -444,7 +448,7 @@ func TestSignature_VerifyRandom(t *testing.T) { t.Parallel() numValidators := 100 - vals := newTestValidators(numValidators) + vals := newTestValidators(t, numValidators) msgHash := types.Hash{0x1} var signature bls.Signatures @@ -501,13 +505,13 @@ func TestExtra_CreateValidatorSetDelta_Cases(t *testing.T) { t.Run(c.name, func(t *testing.T) { t.Parallel() - vals := newTestValidatorsWithAliases([]string{}) + vals := newTestValidatorsWithAliases(t, []string{}) for _, name := range c.oldSet { - vals.create(name, 1) + vals.create(t, name, 1) } for _, name := range c.newSet { - vals.create(name, 1) + vals.create(t, name, 1) } oldValidatorSet := vals.getPublicIdentities(c.oldSet...) @@ -548,7 +552,7 @@ func TestExtra_CreateValidatorSetDelta_Cases(t *testing.T) { func TestExtra_CreateValidatorSetDelta_BlsDiffer(t *testing.T) { t.Parallel() - vals := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + vals := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) oldValidatorSet := vals.getPublicIdentities("A", "B", "C", "D") // change the public bls key of 'B' @@ -608,7 +612,7 @@ func TestExtra_ValidateDelta(t *testing.T) { t.Run(c.name, func(t *testing.T) { t.Parallel() - vals := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + vals := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) oldValidators := vals.getPublicIdentities(c.oldValidators...) newValidators := vals.getPublicIdentities(c.originalNewValidators...) for i, votingPower := range c.updatedVotingPowers { @@ -639,7 +643,7 @@ func TestExtra_InitGenesisValidatorsDelta(t *testing.T) { t.Parallel() const validatorsCount = 7 - vals := newTestValidators(validatorsCount) + vals := newTestValidators(t, validatorsCount) polyBftConfig := PolyBFTConfig{InitialValidatorSet: vals.getParamValidators()} @@ -676,7 +680,7 @@ func TestExtra_InitGenesisValidatorsDelta(t *testing.T) { t.Run("Invalid Extra data", func(t *testing.T) { t.Parallel() - validators := newTestValidators(5) + validators := newTestValidators(t, 5) polyBftConfig := PolyBFTConfig{InitialValidatorSet: validators.getParamValidators()} genesis := &chain.Genesis{ @@ -700,7 +704,7 @@ func TestValidatorSetDelta_Copy(t *testing.T) { addedValidatorsCount = 2 ) - oldValidatorSet := newTestValidators(originalValidatorsCount).getPublicIdentities() + oldValidatorSet := newTestValidators(t, originalValidatorsCount).getPublicIdentities() newValidatorSet := oldValidatorSet[:len(oldValidatorSet)-2] originalDelta, err := createValidatorSetDelta(oldValidatorSet, newValidatorSet) require.NoError(t, err) @@ -714,7 +718,7 @@ func TestValidatorSetDelta_Copy(t *testing.T) { require.Empty(t, copiedDelta.Added) require.Equal(t, copiedDelta.Removed.Len(), originalDelta.Removed.Len()) - newValidators := newTestValidators(addedValidatorsCount).getPublicIdentities() + newValidators := newTestValidators(t, addedValidatorsCount).getPublicIdentities() copiedDelta.Added = append(copiedDelta.Added, newValidators...) require.Empty(t, originalDelta.Added) require.Len(t, copiedDelta.Added, addedValidatorsCount) @@ -784,7 +788,7 @@ func TestValidatorSetDelta_UnmarshalRLPWith_NegativeCases(t *testing.T) { ar := &fastrlp.Arena{} deltaMarshalled := ar.NewArray() - addedValidators := newTestValidators(3).getPublicIdentities() + addedValidators := newTestValidators(t, 3).getPublicIdentities() addedArray := ar.NewArray() updatedArray := ar.NewArray() for _, validator := range addedValidators { @@ -872,8 +876,8 @@ func TestCheckpointData_Hash(t *testing.T) { func TestCheckpointData_Validate(t *testing.T) { t.Parallel() - currentValidators := newTestValidators(5).getPublicIdentities() - nextValidators := newTestValidators(3).getPublicIdentities() + currentValidators := newTestValidators(t, 5).getPublicIdentities() + nextValidators := newTestValidators(t, 3).getPublicIdentities() currentValidatorsHash, err := currentValidators.Hash() require.NoError(t, err) @@ -982,7 +986,7 @@ func TestCheckpointData_Validate(t *testing.T) { func TestCheckpointData_Copy(t *testing.T) { t.Parallel() - validatorAccs := newTestValidators(5) + validatorAccs := newTestValidators(t, 5) currentValidatorsHash, err := validatorAccs.getPublicIdentities("0", "1", "2").Hash() require.NoError(t, err) diff --git a/consensus/polybft/fsm_test.go b/consensus/polybft/fsm_test.go index a52c640677..cf510d6075 100644 --- a/consensus/polybft/fsm_test.go +++ b/consensus/polybft/fsm_test.go @@ -105,7 +105,7 @@ func TestFSM_BuildProposal_WithoutCommitEpochTxGood(t *testing.T) { eventRoot := types.ZeroHash - validators := newTestValidators(accountCount) + validators := newTestValidators(t, accountCount) validatorSet := validators.getPublicIdentities() extra := createTestExtra(validatorSet, AccountSet{}, accountCount-1, committedCount, parentCount) @@ -170,7 +170,7 @@ func TestFSM_BuildProposal_WithCommitEpochTxGood(t *testing.T) { eventRoot := types.ZeroHash - validators := newTestValidators(accountCount) + validators := newTestValidators(t, accountCount) extra := createTestExtra(validators.getPublicIdentities(), AccountSet{}, accountCount-1, committedCount, parentCount) parent := &types.Header{Number: parentBlockNumber, ExtraData: extra} @@ -250,7 +250,7 @@ func TestFSM_BuildProposal_EpochEndingBlock_FailedToApplyStateTx(t *testing.T) { parentBlockNumber = 1023 ) - validators := newTestValidators(accountCount) + validators := newTestValidators(t, accountCount) extra := createTestExtra(validators.getPublicIdentities(), AccountSet{}, accountCount-1, committedCount, parentCount) parent := &types.Header{Number: parentBlockNumber, ExtraData: extra} @@ -283,7 +283,7 @@ func TestFSM_BuildProposal_EpochEndingBlock_ValidatorsDeltaExists(t *testing.T) parentBlockNumber = 49 ) - validators := newTestValidators(validatorsCount).getPublicIdentities() + validators := newTestValidators(t, validatorsCount).getPublicIdentities() extra := createTestExtra(validators, AccountSet{}, validatorsCount-1, signaturesCount, signaturesCount) parent := &types.Header{Number: parentBlockNumber, ExtraData: extra} parent.ComputeHash() @@ -295,7 +295,7 @@ func TestFSM_BuildProposal_EpochEndingBlock_ValidatorsDeltaExists(t *testing.T) blockBuilderMock.On("GetState").Return(transition).Once() newValidators := validators[:remainingValidatorsCount].Copy() - addedValidators := newTestValidators(2).getPublicIdentities() + addedValidators := newTestValidators(t, 2).getPublicIdentities() newValidators = append(newValidators, addedValidators...) systemStateMock := new(systemStateMock) systemStateMock.On("GetValidatorSet").Return(newValidators).Once() @@ -356,7 +356,7 @@ func TestFSM_BuildProposal_NonEpochEndingBlock_ValidatorsDeltaEmpty(t *testing.T parentBlockNumber = 9 ) - testValidators := newTestValidators(accountCount) + testValidators := newTestValidators(t, accountCount) extra := createTestExtra(testValidators.getPublicIdentities(), AccountSet{}, accountCount-1, signaturesCount, signaturesCount) parent := &types.Header{Number: parentBlockNumber, ExtraData: extra} parent.ComputeHash() @@ -395,7 +395,7 @@ func TestFSM_BuildProposal_EpochEndingBlock_FailToCreateValidatorsDelta(t *testi parentBlockNumber = 49 ) - testValidators := newTestValidators(accountCount) + testValidators := newTestValidators(t, accountCount) allAccounts := testValidators.getPublicIdentities() extra := createTestExtra(allAccounts, AccountSet{}, accountCount-1, signaturesCount, signaturesCount) @@ -509,7 +509,7 @@ func TestFSM_VerifyStateTransactions_EndOfEpochMoreThanOneCommitEpochTx(t *testi func TestFSM_VerifyStateTransactions_StateTransactionPass(t *testing.T) { t.Parallel() - validators := newTestValidators(5) + validators := newTestValidators(t, 5) validatorSet := NewValidatorSet(validators.getPublicIdentities(), hclog.NewNullLogger()) @@ -536,7 +536,7 @@ func TestFSM_VerifyStateTransactions_StateTransactionPass(t *testing.T) { func TestFSM_VerifyStateTransactions_StateTransactionQuorumNotReached(t *testing.T) { t.Parallel() - validators := newTestValidators(5) + validators := newTestValidators(t, 5) commitment := createTestCommitment(t, validators.getPrivateIdentities()) commitment.AggSignature = Signature{ AggregatedSignature: []byte{1, 2}, @@ -570,9 +570,9 @@ func TestFSM_VerifyStateTransactions_StateTransactionQuorumNotReached(t *testing func TestFSM_VerifyStateTransactions_StateTransactionInvalidSignature(t *testing.T) { t.Parallel() - validators := newTestValidators(5) + validators := newTestValidators(t, 5) commitment := createTestCommitment(t, validators.getPrivateIdentities()) - nonValidators := newTestValidators(3) + nonValidators := newTestValidators(t, 3) aggregatedSigs := bls.Signatures{} nonValidators.iterAcct(nil, func(t *testValidator) { @@ -616,7 +616,7 @@ func TestFSM_ValidateCommit_WrongValidator(t *testing.T) { parentBlockNumber = 10 ) - validators := newTestValidators(accountsCount) + validators := newTestValidators(t, accountsCount) parent := &types.Header{ Number: parentBlockNumber, ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 5, 3, 3), @@ -643,7 +643,7 @@ func TestFSM_ValidateCommit_InvalidHash(t *testing.T) { parentBlockNumber = 10 ) - validators := newTestValidators(accountsCount) + validators := newTestValidators(t, accountsCount) parent := &types.Header{ Number: parentBlockNumber, @@ -659,7 +659,7 @@ func TestFSM_ValidateCommit_InvalidHash(t *testing.T) { _, err := fsm.BuildProposal(0) assert.NoError(t, err) - nonValidatorAcc := newTestValidator("non_validator", 1) + nonValidatorAcc := newTestValidator(t, "non_validator", 1) wrongSignature, err := nonValidatorAcc.mustSign([]byte("Foo")).Marshal() require.NoError(t, err) @@ -672,7 +672,7 @@ func TestFSM_ValidateCommit_Good(t *testing.T) { const parentBlockNumber = 10 - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}) validatorsMetadata := validators.getPublicIdentities() parent := &types.Header{Number: parentBlockNumber, ExtraData: createTestExtra(validatorsMetadata, AccountSet{}, 5, 3, 3)} @@ -709,7 +709,7 @@ func TestFSM_Validate_IncorrectHeaderParentHash(t *testing.T) { signaturesCount = 3 ) - validators := newTestValidators(accountsCount) + validators := newTestValidators(t, accountsCount) parent := &types.Header{ Number: parentBlockNumber, ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 4, signaturesCount, signaturesCount), @@ -740,7 +740,7 @@ func TestFSM_Validate_InvalidNumber(t *testing.T) { signaturesCount = 3 ) - validators := newTestValidators(accountsCount) + validators := newTestValidators(t, accountsCount) parent := &types.Header{ Number: parentBlockNumber, ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 4, signaturesCount, signaturesCount), @@ -770,7 +770,7 @@ func TestFSM_Validate_TimestampOlder(t *testing.T) { const parentBlockNumber = 10 - validators := newTestValidators(5) + validators := newTestValidators(t, 5) parent := &types.Header{ Number: parentBlockNumber, ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 4, 3, 3), @@ -806,7 +806,7 @@ func TestFSM_Validate_IncorrectMixHash(t *testing.T) { const parentBlockNumber = 10 - validators := newTestValidators(5) + validators := newTestValidators(t, 5) parent := &types.Header{ Number: parentBlockNumber, ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 4, 3, 3), @@ -850,7 +850,7 @@ func TestFSM_Insert_Good(t *testing.T) { ) setupFn := func() (*fsm, []*messages.CommittedSeal, *types.FullBlock, *blockchainMock) { - validators := newTestValidators(accountCount) + validators := newTestValidators(t, accountCount) allAccounts := validators.getPrivateIdentities() validatorsMetadata := validators.getPublicIdentities() @@ -943,7 +943,7 @@ func TestFSM_Insert_InvalidNode(t *testing.T) { signaturesCount = 3 ) - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}) validatorsMetadata := validators.getPublicIdentities() parent := &types.Header{Number: parentBlockNumber} @@ -975,7 +975,7 @@ func TestFSM_Insert_InvalidNode(t *testing.T) { require.NoError(t, err) // create test account outside of validator set - nonValidatorAccount := newTestValidator("non_validator", 1) + nonValidatorAccount := newTestValidator(t, "non_validator", 1) nonValidatorSignature, err := nonValidatorAccount.mustSign(proposalHash).Marshal() require.NoError(t, err) @@ -1060,7 +1060,7 @@ func TestFSM_VerifyStateTransaction_ValidBothTypesOfStateTransactions(t *testing signedCommitments [2]*CommitmentMessageSigned ) - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}) commitments[0], signedCommitments[0], stateSyncs[0] = buildCommitmentAndStateSyncs(t, 10, uint64(3), 2) commitments[1], signedCommitments[1], stateSyncs[1] = buildCommitmentAndStateSyncs(t, 10, uint64(3), 12) @@ -1116,7 +1116,7 @@ func TestFSM_VerifyStateTransaction_InvalidTypeOfStateTransactions(t *testing.T) func TestFSM_VerifyStateTransaction_QuorumNotReached(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) _, commitmentMessageSigned, _ := buildCommitmentAndStateSyncs(t, 10, uint64(3), 2) f := &fsm{ isEndOfSprint: true, @@ -1145,7 +1145,7 @@ func TestFSM_VerifyStateTransaction_QuorumNotReached(t *testing.T) { func TestFSM_VerifyStateTransaction_InvalidSignature(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) _, commitmentMessageSigned, _ := buildCommitmentAndStateSyncs(t, 10, uint64(3), 2) f := &fsm{ isEndOfSprint: true, @@ -1159,7 +1159,7 @@ func TestFSM_VerifyStateTransaction_InvalidSignature(t *testing.T) { var txns []*types.Transaction signature := createSignature(t, validators.getPrivateIdentities("A", "B", "C", "D"), hash) - invalidValidator := newTestValidator("G", 1) + invalidValidator := newTestValidator(t, "G", 1) invalidSignature, err := invalidValidator.mustSign([]byte("malicious message")).Marshal() require.NoError(t, err) @@ -1181,7 +1181,7 @@ func TestFSM_VerifyStateTransaction_InvalidSignature(t *testing.T) { func TestFSM_VerifyStateTransaction_TwoCommitmentMessages(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) _, commitmentMessageSigned, _ := buildCommitmentAndStateSyncs(t, 10, uint64(3), 2) validatorSet := NewValidatorSet(validators.getPublicIdentities(), hclog.NewNullLogger()) @@ -1223,7 +1223,7 @@ func TestFSM_Validate_FailToVerifySignatures(t *testing.T) { signaturesCount = 3 ) - validators := newTestValidators(accountsCount) + validators := newTestValidators(t, accountsCount) validatorsMetadata := validators.getPublicIdentities() extra := createTestExtraObject(validatorsMetadata, AccountSet{}, 4, signaturesCount, signaturesCount) diff --git a/consensus/polybft/hash_test.go b/consensus/polybft/hash_test.go index e5164cf2ab..8af47b2e0f 100644 --- a/consensus/polybft/hash_test.go +++ b/consensus/polybft/hash_test.go @@ -12,7 +12,7 @@ import ( func Test_setupHeaderHashFunc(t *testing.T) { extra := &Extra{ Validators: &ValidatorSetDelta{Removed: bitmap.Bitmap{1}}, - Parent: createSignature(t, []*wallet.Account{wallet.GenerateAccount()}, types.ZeroHash), + Parent: createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash), Checkpoint: &CheckpointData{}, Seal: []byte{}, Committed: &Signature{}, @@ -28,7 +28,7 @@ func Test_setupHeaderHashFunc(t *testing.T) { notFullExtraHash := types.HeaderHash(header) extra.Seal = []byte{1, 2, 3, 255} - extra.Committed = createSignature(t, []*wallet.Account{wallet.GenerateAccount()}, types.ZeroHash) + extra.Committed = createSignature(t, []*wallet.Account{generateTestAccount(t)}, types.ZeroHash) header.ExtraData = append(make([]byte, ExtraVanity), extra.MarshalRLPTo(nil)...) fullExtraHash := types.HeaderHash(header) diff --git a/consensus/polybft/helpers_test.go b/consensus/polybft/helpers_test.go index 295511d8b0..857ed75d9f 100644 --- a/consensus/polybft/helpers_test.go +++ b/consensus/polybft/helpers_test.go @@ -21,7 +21,7 @@ import ( func createTestKey(t *testing.T) *wallet.Key { t.Helper() - return wallet.NewKey(wallet.GenerateAccount(), bls.DomainCheckpointManager) + return wallet.NewKey(generateTestAccount(t), bls.DomainCheckpointManager) } func createRandomTestKeys(t *testing.T, numberOfKeys int) []*wallet.Key { @@ -30,7 +30,7 @@ func createRandomTestKeys(t *testing.T, numberOfKeys int) []*wallet.Key { result := make([]*wallet.Key, numberOfKeys, numberOfKeys) for i := 0; i < numberOfKeys; i++ { - result[i] = wallet.NewKey(wallet.GenerateAccount(), bls.DomainCheckpointManager) + result[i] = wallet.NewKey(generateTestAccount(t), bls.DomainCheckpointManager) } return result @@ -61,7 +61,7 @@ func createTestCommitEpochInput(t *testing.T, epochID uint64, validatorSet Accou t.Helper() if validatorSet == nil { - validatorSet = newTestValidators(5).getPublicIdentities() + validatorSet = newTestValidators(t, 5).getPublicIdentities() } var startBlock uint64 = 0 @@ -156,3 +156,12 @@ func newTestState(t *testing.T) *State { return state } + +func generateTestAccount(t *testing.T) *wallet.Account { + t.Helper() + + acc, err := wallet.GenerateAccount() + require.NoError(t, err) + + return acc +} diff --git a/consensus/polybft/mocks_test.go b/consensus/polybft/mocks_test.go index 81f0000ac4..3a08334809 100644 --- a/consensus/polybft/mocks_test.go +++ b/consensus/polybft/mocks_test.go @@ -5,6 +5,7 @@ import ( "math/big" "sort" "strconv" + "testing" "time" "github.com/0xPolygon/polygon-edge/blockchain" @@ -86,7 +87,7 @@ func (m *blockchainMock) GetHeaderByNumber(number uint64) (*types.Header, bool) return args.Get(0).(*types.Header), args.Get(1).(bool) //nolint:forcetypeassert } - panic("Unsupported mock for GetHeaderByNumber") + panic("Unsupported mock for GetHeaderByNumber") //nolint:gocritic } func (m *blockchainMock) GetHeaderByHash(hash types.Hash) (*types.Header, bool) { @@ -104,7 +105,7 @@ func (m *blockchainMock) GetHeaderByHash(hash types.Hash) (*types.Header, bool) return h, h != nil } - panic("Unsupported mock for GetHeaderByHash") + panic("Unsupported mock for GetHeaderByHash") //nolint:gocritic } func (m *blockchainMock) GetSystemState(config *PolyBFTConfig, provider contract.Provider) SystemState { @@ -144,7 +145,7 @@ func (p *polybftBackendMock) GetValidators(blockNumber uint64, parents []*types. return accountSet, args.Error(1) } - panic("polybftBackendMock.GetValidators doesn't support such combination of arguments") + panic("polybftBackendMock.GetValidators doesn't support such combination of arguments") //nolint:gocritic } var _ blockBuilder = (*blockBuilderMock)(nil) @@ -215,7 +216,7 @@ func (m *systemStateMock) GetValidatorSet() (AccountSet, error) { return accountSet, args.Error(1) } - panic("systemStateMock.GetValidatorSet doesn't support such combination of arguments") + panic("systemStateMock.GetValidatorSet doesn't support such combination of arguments") //nolint:gocritic } func (m *systemStateMock) GetNextCommittedIndex() (uint64, error) { @@ -281,16 +282,20 @@ type testValidators struct { validators map[string]*testValidator } -func newTestValidators(validatorsCount int) *testValidators { +func newTestValidators(t *testing.T, validatorsCount int) *testValidators { + t.Helper() + aliases := make([]string, validatorsCount) for i := 0; i < validatorsCount; i++ { aliases[i] = strconv.Itoa(i) } - return newTestValidatorsWithAliases(aliases) + return newTestValidatorsWithAliases(t, aliases) } -func newTestValidatorsWithAliases(aliases []string, votingPowers ...[]uint64) *testValidators { +func newTestValidatorsWithAliases(t *testing.T, aliases []string, votingPowers ...[]uint64) *testValidators { + t.Helper() + validators := map[string]*testValidator{} for i, alias := range aliases { @@ -299,15 +304,17 @@ func newTestValidatorsWithAliases(aliases []string, votingPowers ...[]uint64) *t votingPower = votingPowers[0][i] } - validators[alias] = newTestValidator(alias, votingPower) + validators[alias] = newTestValidator(t, alias, votingPower) } return &testValidators{validators: validators} } -func (v *testValidators) create(alias string, votingPower uint64) { +func (v *testValidators) create(t *testing.T, alias string, votingPower uint64) { + t.Helper() + if _, ok := v.validators[alias]; !ok { - v.validators[alias] = newTestValidator(alias, votingPower) + v.validators[alias] = newTestValidator(t, alias, votingPower) } } @@ -361,7 +368,7 @@ func (v *testValidators) getPrivateIdentities(aliases ...string) (res []*wallet. func (v *testValidators) getValidator(alias string) *testValidator { vv, ok := v.validators[alias] if !ok { - panic(fmt.Sprintf("BUG: validator %s does not exist", alias)) + panic(fmt.Sprintf("Validator %s does not exist", alias)) //nolint:gocritic } return vv @@ -394,11 +401,13 @@ type testValidator struct { votingPower uint64 } -func newTestValidator(alias string, votingPower uint64) *testValidator { +func newTestValidator(t *testing.T, alias string, votingPower uint64) *testValidator { + t.Helper() + return &testValidator{ alias: alias, votingPower: votingPower, - account: wallet.GenerateAccount(), + account: generateTestAccount(t), } } @@ -431,7 +440,7 @@ func (v *testValidator) ValidatorMetadata() *ValidatorMetadata { func (v *testValidator) mustSign(hash []byte) *bls.Signature { signature, err := v.account.Bls.Sign(hash, bls.DomainCheckpointManager) if err != nil { - panic(fmt.Sprintf("BUG: failed to sign: %v", err)) + panic(fmt.Sprintf("BUG: failed to sign: %v", err)) //nolint:gocritic } return signature diff --git a/consensus/polybft/polybft_test.go b/consensus/polybft/polybft_test.go index 8263c6aaff..90ae145cf4 100644 --- a/consensus/polybft/polybft_test.go +++ b/consensus/polybft/polybft_test.go @@ -62,7 +62,7 @@ func TestPolybft_VerifyHeader(t *testing.T) { } // create all validators - validators := newTestValidators(allValidatorsSize) + validators := newTestValidators(t, allValidatorsSize) // create configuration polyBftConfig := PolyBFTConfig{ diff --git a/consensus/polybft/proposer_calculator_test.go b/consensus/polybft/proposer_calculator_test.go index a314d7d2fc..1d6dd23144 100644 --- a/consensus/polybft/proposer_calculator_test.go +++ b/consensus/polybft/proposer_calculator_test.go @@ -15,7 +15,7 @@ import ( func TestProposerCalculator_SetIndex(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}, []uint64{10, 100, 1, 50, 30}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}, []uint64{10, 100, 1, 50, 30}) metadata := validators.getPublicIdentities() vs := validators.toValidatorSet() @@ -39,7 +39,7 @@ func TestProposerCalculator_SetIndex(t *testing.T) { func TestProposerCalculator_RegularFlow(t *testing.T) { t.Parallel() - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E"}, []uint64{1, 2, 3, 4, 5}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E"}, []uint64{1, 2, 3, 4, 5}) metadata := validators.getPublicIdentities() snapshot := NewProposerSnapshot(0, metadata) @@ -414,7 +414,7 @@ func TestProposerCalculator_GetLatestProposer(t *testing.T) { count = 10 ) - validatorSet := newTestValidators(count).getPublicIdentities() + validatorSet := newTestValidators(t, count).getPublicIdentities() snapshot := NewProposerSnapshot(0, validatorSet) snapshot.Validators[bestIdx].ProposerPriority = big.NewInt(1000000) diff --git a/consensus/polybft/runtime_helpers_test.go b/consensus/polybft/runtime_helpers_test.go index 1806097cf8..fdf1fa1e43 100644 --- a/consensus/polybft/runtime_helpers_test.go +++ b/consensus/polybft/runtime_helpers_test.go @@ -13,7 +13,7 @@ import ( func TestHelpers_isEpochEndingBlock_DeltaNotEmpty(t *testing.T) { t.Parallel() - validators := newTestValidators(3).getPublicIdentities() + validators := newTestValidators(t, 3).getPublicIdentities() bitmap := bitmap.Bitmap{} bitmap.Set(0) diff --git a/consensus/polybft/sc_integration_test.go b/consensus/polybft/sc_integration_test.go index 20fc34ee04..54922172ca 100644 --- a/consensus/polybft/sc_integration_test.go +++ b/consensus/polybft/sc_integration_test.go @@ -28,7 +28,7 @@ func TestIntegratoin_PerformExit(t *testing.T) { t.Parallel() // create validator set - currentValidators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D"}, []uint64{100, 100, 100, 100}) + currentValidators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D"}, []uint64{100, 100, 100, 100}) accSet := currentValidators.getPublicIdentities() senderAddress := types.Address{1} @@ -216,7 +216,7 @@ func TestIntegration_CommitEpoch(t *testing.T) { vps[j] = intialBalance } - validatorSets[i] = newTestValidatorsWithAliases(aliases, vps) + validatorSets[i] = newTestValidatorsWithAliases(t, aliases, vps) } // iterate through the validator set and do the test for each of them diff --git a/consensus/polybft/signer/common.go b/consensus/polybft/signer/common.go index defd877ea2..76aad30e66 100644 --- a/consensus/polybft/signer/common.go +++ b/consensus/polybft/signer/common.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "fmt" "io" + "log" "math/big" pcrypto "github.com/0xPolygon/polygon-edge/crypto" @@ -30,13 +31,13 @@ var ( func mustG2Point(str string) *bn256.G2 { buf, err := hex.DecodeString(str) if err != nil { - panic(err) + log.Fatal(err) } b := new(bn256.G2) if _, err := b.Unmarshal(buf); err != nil { - panic(err) + log.Fatal(err) } return b diff --git a/consensus/polybft/state_sync_manager_test.go b/consensus/polybft/state_sync_manager_test.go index ccf563beff..823f53b434 100644 --- a/consensus/polybft/state_sync_manager_test.go +++ b/consensus/polybft/state_sync_manager_test.go @@ -1,7 +1,6 @@ package polybft import ( - "fmt" "math/big" "math/rand" "os" @@ -50,7 +49,7 @@ func newTestStateSyncManager(t *testing.T, key *testValidator) *stateSyncManager } func TestStateSyncManager_PostEpoch_BuildCommitment(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) // there are no state syncs @@ -86,7 +85,7 @@ func TestStateSyncManager_PostEpoch_BuildCommitment(t *testing.T) { } func TestStateSyncManager_MessagePool_OldEpoch(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.epoch = 1 @@ -116,10 +115,10 @@ func (m *mockMsg) WithHash(hash []byte) *mockMsg { return m } -func (m *mockMsg) sign(val *testValidator) *TransportMessage { +func (m *mockMsg) sign(val *testValidator) (*TransportMessage, error) { signature, err := val.mustSign(m.hash).Marshal() if err != nil { - panic(fmt.Errorf("BUG: %w", err)) + return nil, err } return &TransportMessage{ @@ -127,36 +126,37 @@ func (m *mockMsg) sign(val *testValidator) *TransportMessage { Signature: signature, From: val.Address().String(), EpochNumber: m.epoch, - } + }, nil } func TestStateSyncManager_MessagePool_SenderIsNoValidator(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.validatorSet = vals.toValidatorSet() - badVal := newTestValidator("a", 0) - msg := newMockMsg().sign(badVal) + badVal := newTestValidator(t, "a", 0) + msg, err := newMockMsg().sign(badVal) + require.NoError(t, err) - err := s.saveVote(msg) - require.Error(t, err) + require.Error(t, s.saveVote(msg)) } func TestStateSyncManager_MessagePool_InvalidEpoch(t *testing.T) { t.Parallel() - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.validatorSet = vals.toValidatorSet() val := newMockMsg() - msg := val.sign(vals.getValidator("0")) + msg, err := val.sign(vals.getValidator("0")) + require.NoError(t, err) + msg.EpochNumber = 1 - err := s.saveVote(msg) - require.NoError(t, err) + require.NoError(t, s.saveVote(msg)) // no votes for the current epoch votes, err := s.state.StateSyncStore.getMessageVotes(0, msg.Hash) @@ -171,35 +171,40 @@ func TestStateSyncManager_MessagePool_InvalidEpoch(t *testing.T) { func TestStateSyncManager_MessagePool_SenderAndSignatureMissmatch(t *testing.T) { t.Parallel() - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.validatorSet = vals.toValidatorSet() // validator signs the msg in behalf of another validator val := newMockMsg() - msg := val.sign(vals.getValidator("0")) + msg, err := val.sign(vals.getValidator("0")) + require.NoError(t, err) + msg.From = vals.getValidator("1").Address().String() - err := s.saveVote(msg) - require.Error(t, err) + require.Error(t, s.saveVote(msg)) // non validator signs the msg in behalf of a validator - badVal := newTestValidator("a", 0) - msg = newMockMsg().sign(badVal) + badVal := newTestValidator(t, "a", 0) + msg, err = newMockMsg().sign(badVal) + require.NoError(t, err) + msg.From = vals.getValidator("1").Address().String() - err = s.saveVote(msg) - require.Error(t, err) + require.Error(t, s.saveVote(msg)) } func TestStateSyncManager_MessagePool_SenderVotes(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.validatorSet = vals.toValidatorSet() msg := newMockMsg() - val1signed := msg.sign(vals.getValidator("1")) - val2signed := msg.sign(vals.getValidator("2")) + val1signed, err := msg.sign(vals.getValidator("1")) + require.NoError(t, err) + + val2signed, err := msg.sign(vals.getValidator("2")) + require.NoError(t, err) // vote with validator 1 require.NoError(t, s.saveVote(val1signed)) @@ -220,7 +225,7 @@ func TestStateSyncManager_MessagePool_SenderVotes(t *testing.T) { } func TestStateSyncManager_BuildCommitment(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) s.validatorSet = vals.toValidatorSet() @@ -251,16 +256,29 @@ func TestStateSyncManager_BuildCommitment(t *testing.T) { // validators 0 and 1 vote for the proposal, there is not enough // voting power for the proposal - require.NoError(t, s.saveVote(msg.sign(vals.getValidator("0")))) - require.NoError(t, s.saveVote(msg.sign(vals.getValidator("1")))) + signedMsg1, err := msg.sign(vals.getValidator("0")) + require.NoError(t, err) + + signedMsg2, err := msg.sign(vals.getValidator("1")) + require.NoError(t, err) + + require.NoError(t, s.saveVote(signedMsg1)) + require.NoError(t, s.saveVote(signedMsg2)) commitment, err = s.Commitment() require.NoError(t, err) // there is no error if quorum is not met, since its a valid case require.Nil(t, commitment) // validator 2 and 3 vote for the proposal, there is enough voting power now - require.NoError(t, s.saveVote(msg.sign(vals.getValidator("2")))) - require.NoError(t, s.saveVote(msg.sign(vals.getValidator("3")))) + + signedMsg1, err = msg.sign(vals.getValidator("2")) + require.NoError(t, err) + + signedMsg2, err = msg.sign(vals.getValidator("3")) + require.NoError(t, err) + + require.NoError(t, s.saveVote(signedMsg1)) + require.NoError(t, s.saveVote(signedMsg2)) commitment, err = s.Commitment() require.NoError(t, err) @@ -268,7 +286,7 @@ func TestStateSyncManager_BuildCommitment(t *testing.T) { } func TestStateSyncerManager_BuildProofs(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) @@ -310,7 +328,7 @@ func TestStateSyncerManager_BuildProofs(t *testing.T) { } func TestStateSyncerManager_AddLog_BuildCommitments(t *testing.T) { - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) @@ -375,7 +393,7 @@ func TestStateSyncerManager_AddLog_BuildCommitments(t *testing.T) { func TestStateSyncerManager_EventTracker_Sync(t *testing.T) { t.Parallel() - vals := newTestValidators(5) + vals := newTestValidators(t, 5) s := newTestStateSyncManager(t, vals.getValidator("0")) server := testutil.DeployTestServer(t, nil) @@ -419,7 +437,7 @@ func TestStateSyncerManager_EventTracker_Sync(t *testing.T) { func TestStateSyncManager_Close(t *testing.T) { t.Parallel() - mgr := newTestStateSyncManager(t, newTestValidator("A", 100)) + mgr := newTestStateSyncManager(t, newTestValidator(t, "A", 100)) require.NotPanics(t, func() { mgr.Close() }) } diff --git a/consensus/polybft/system_state_test.go b/consensus/polybft/system_state_test.go index d637afdb49..867fb899ae 100644 --- a/consensus/polybft/system_state_test.go +++ b/consensus/polybft/system_state_test.go @@ -187,8 +187,8 @@ func TestStateProvider_Txn_NotSupported(t *testing.T) { transition: transition, } - require.PanicsWithError(t, errSendTxnUnsupported.Error(), - func() { _, _ = provider.Txn(ethgo.ZeroAddress, createTestKey(t), []byte{0x1}) }) + _, err := provider.Txn(ethgo.ZeroAddress, createTestKey(t), []byte{0x1}) + require.ErrorIs(t, err, errSendTxnUnsupported) } func newTestTransition(t *testing.T, alloc map[types.Address]*chain.GenesisAccount) *state.Transition { @@ -200,7 +200,8 @@ func newTestTransition(t *testing.T, alloc map[types.Address]*chain.GenesisAccou Forks: chain.AllForksEnabled, }, st, hclog.NewNullLogger()) - rootHash := ex.WriteGenesis(alloc) + rootHash, err := ex.WriteGenesis(alloc) + require.NoError(t, err) ex.GetHash = func(h *types.Header) state.GetHashByNumber { return func(i uint64) types.Hash { diff --git a/consensus/polybft/validator_metadata_test.go b/consensus/polybft/validator_metadata_test.go index eb7f1010f1..164a60958f 100644 --- a/consensus/polybft/validator_metadata_test.go +++ b/consensus/polybft/validator_metadata_test.go @@ -14,7 +14,7 @@ import ( func TestValidatorMetadata_Equals(t *testing.T) { t.Parallel() - v := newTestValidator("A", 10) + v := newTestValidator(t, "A", 10) validatorAcc := v.ValidatorMetadata() // proper validator metadata instance doesn't equal to nil require.False(t, validatorAcc.Equals(nil)) @@ -29,7 +29,7 @@ func TestValidatorMetadata_Equals(t *testing.T) { func TestValidatorMetadata_EqualAddressAndBlsKey(t *testing.T) { t.Parallel() - v := newTestValidator("A", 10) + v := newTestValidator(t, "A", 10) validatorAcc := v.ValidatorMetadata() // proper validator metadata instance doesn't equal to nil require.False(t, validatorAcc.EqualAddressAndBlsKey(nil)) @@ -82,7 +82,7 @@ func TestAccountSet_IndexContainsAddressesAndContainsNodeId(t *testing.T) { const count = 10 dummy := types.Address{2, 3, 4} - validators := newTestValidators(count).getPublicIdentities() + validators := newTestValidators(t, count).getPublicIdentities() addresses := [count]types.Address{} for i, validator := range validators { @@ -195,7 +195,7 @@ func TestAccountSet_ApplyDelta(t *testing.T) { snapshot := AccountSet{} // Add a couple of validators to the snapshot => validators are present in the snapshot after applying such delta - vals := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + vals := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) for _, step := range cc.steps { addedValidators := AccountSet{} @@ -239,7 +239,7 @@ func TestAccountSet_ApplyDelta(t *testing.T) { func TestAccountSet_ApplyEmptyDelta(t *testing.T) { t.Parallel() - v := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + v := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) validatorAccs := v.getPublicIdentities() validators, err := validatorAccs.ApplyDelta(nil) require.NoError(t, err) @@ -252,7 +252,7 @@ func TestAccountSet_Hash(t *testing.T) { t.Run("Hash non-empty account set", func(t *testing.T) { t.Parallel() - v := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F"}) + v := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F"}) hash, err := v.getPublicIdentities().Hash() require.NoError(t, err) require.NotEqual(t, types.ZeroHash, hash) diff --git a/consensus/polybft/validator_set_test.go b/consensus/polybft/validator_set_test.go index de807a522b..f7faa5a678 100644 --- a/consensus/polybft/validator_set_test.go +++ b/consensus/polybft/validator_set_test.go @@ -12,7 +12,7 @@ func TestValidatorSet_HasQuorum(t *testing.T) { t.Parallel() // enough signers for quorum (2/3 super-majority of validators are signers) - validators := newTestValidatorsWithAliases([]string{"A", "B", "C", "D", "E", "F", "G"}) + validators := newTestValidatorsWithAliases(t, []string{"A", "B", "C", "D", "E", "F", "G"}) vs := validators.toValidatorSet() signers := make(map[types.Address]struct{}) diff --git a/consensus/polybft/validators_snapshot_test.go b/consensus/polybft/validators_snapshot_test.go index 6176849ea3..f22b633d9d 100644 --- a/consensus/polybft/validators_snapshot_test.go +++ b/consensus/polybft/validators_snapshot_test.go @@ -21,7 +21,7 @@ func TestValidatorsSnapshotCache_GetSnapshot_Build(t *testing.T) { epochSize = uint64(10) ) - allValidators := newTestValidators(totalValidators).getPublicIdentities() + allValidators := newTestValidators(t, totalValidators).getPublicIdentities() var oddValidators, evenValidators AccountSet @@ -98,7 +98,7 @@ func TestValidatorsSnapshotCache_GetSnapshot_FetchFromCache(t *testing.T) { validatorSetSize = 5 ) - allValidators := newTestValidators(totalValidators).getPublicIdentities() + allValidators := newTestValidators(t, totalValidators).getPublicIdentities() epochOneValidators := AccountSet{allValidators[0], allValidators[len(allValidators)-1]} epochTwoValidators := allValidators[1 : len(allValidators)-2] @@ -143,7 +143,7 @@ func TestValidatorsSnapshotCache_Cleanup(t *testing.T) { cache := &testValidatorsCache{ validatorsSnapshotCache: newValidatorsSnapshotCache(hclog.NewNullLogger(), newTestState(t), blockchainMock), } - snapshot := newTestValidators(3).getPublicIdentities() + snapshot := newTestValidators(t, 3).getPublicIdentities() maxEpoch := uint64(0) for i := uint64(0); i < validatorSnapshotLimit; i++ { @@ -191,7 +191,7 @@ func TestValidatorsSnapshotCache_ComputeSnapshot_UnknownBlock(t *testing.T) { epochSize = uint64(10) ) - allValidators := newTestValidators(totalValidators).getPublicIdentities() + allValidators := newTestValidators(t, totalValidators).getPublicIdentities() headersMap := &testHeadersMap{} headersMap.addHeader(createValidatorDeltaHeader(t, 0, 0, nil, allValidators[:validatorSetSize])) headersMap.addHeader(createValidatorDeltaHeader(t, 1*epochSize, 1, allValidators[:validatorSetSize], allValidators[validatorSetSize:])) @@ -218,7 +218,7 @@ func TestValidatorsSnapshotCache_ComputeSnapshot_IncorrectExtra(t *testing.T) { epochSize = uint64(10) ) - allValidators := newTestValidators(totalValidators).getPublicIdentities() + allValidators := newTestValidators(t, totalValidators).getPublicIdentities() headersMap := &testHeadersMap{} invalidHeader := createValidatorDeltaHeader(t, 1*epochSize, 1, allValidators[:validatorSetSize], allValidators[validatorSetSize:]) invalidHeader.ExtraData = []byte{0x2, 0x7} @@ -246,7 +246,7 @@ func TestValidatorsSnapshotCache_ComputeSnapshot_ApplyDeltaFail(t *testing.T) { epochSize = uint64(10) ) - allValidators := newTestValidators(totalValidators).getPublicIdentities() + allValidators := newTestValidators(t, totalValidators).getPublicIdentities() headersMap := &testHeadersMap{} headersMap.addHeader(createValidatorDeltaHeader(t, 0, 0, nil, allValidators[:validatorSetSize])) headersMap.addHeader(createValidatorDeltaHeader(t, 1*epochSize, 1, nil, allValidators[:validatorSetSize])) diff --git a/consensus/polybft/wallet/account.go b/consensus/polybft/wallet/account.go index 97fd9a530c..751bfb4938 100644 --- a/consensus/polybft/wallet/account.go +++ b/consensus/polybft/wallet/account.go @@ -17,21 +17,21 @@ type Account struct { } // GenerateAccount generates a new random account -func GenerateAccount() *Account { +func GenerateAccount() (*Account, error) { key, err := wallet.GenerateKey() if err != nil { - panic("Cannot generate key") + return nil, fmt.Errorf("cannot generate key. error: %w", err) } blsKey, err := bls.GenerateBlsKey() if err != nil { - panic("Cannot generate bls key") + return nil, fmt.Errorf("cannot generate bls key. error: %w", err) } return &Account{ Ecdsa: key, Bls: blsKey, - } + }, nil } // NewAccountFromSecret creates new account by using provided secretsManager diff --git a/consensus/polybft/wallet/account_test.go b/consensus/polybft/wallet/account_test.go index 5eab4c2f2a..089bc212bf 100644 --- a/consensus/polybft/wallet/account_test.go +++ b/consensus/polybft/wallet/account_test.go @@ -14,7 +14,7 @@ func TestAccount(t *testing.T) { secretsManager := newSecretsManagerMock() - key := GenerateAccount() + key := generateTestAccount(t) pubKeyMarshalled := key.Bls.PublicKey().Marshal() privKeyMarshalled, err := key.Bls.Marshal() require.NoError(t, err) @@ -37,6 +37,15 @@ func newSecretsManagerMock() secrets.SecretsManager { return &secretsManagerMock{cache: make(map[string][]byte)} } +func generateTestAccount(t *testing.T) *Account { + t.Helper() + + acc, err := GenerateAccount() + require.NoError(t, err) + + return acc +} + type secretsManagerMock struct { cache map[string][]byte } diff --git a/consensus/polybft/wallet/key_test.go b/consensus/polybft/wallet/key_test.go index e43c8a3106..67d23b715f 100644 --- a/consensus/polybft/wallet/key_test.go +++ b/consensus/polybft/wallet/key_test.go @@ -12,7 +12,7 @@ import ( func Test_RecoverAddressFromSignature(t *testing.T) { t.Parallel() - for _, account := range []*Account{GenerateAccount(), GenerateAccount(), GenerateAccount()} { + for _, account := range []*Account{generateTestAccount(t), generateTestAccount(t), generateTestAccount(t)} { key := NewKey(account, bls.DomainCheckpointManager) msgNoSig := &proto.Message{ From: key.Address().Bytes(), @@ -37,7 +37,7 @@ func Test_Sign(t *testing.T) { msg := []byte("some message") - for _, account := range []*Account{GenerateAccount(), GenerateAccount()} { + for _, account := range []*Account{generateTestAccount(t), generateTestAccount(t)} { key := NewKey(account, bls.DomainCheckpointManager) ser, err := key.Sign(msg) @@ -53,7 +53,7 @@ func Test_Sign(t *testing.T) { func Test_String(t *testing.T) { t.Parallel() - for _, account := range []*Account{GenerateAccount(), GenerateAccount(), GenerateAccount()} { + for _, account := range []*Account{generateTestAccount(t), generateTestAccount(t), generateTestAccount(t)} { key := NewKey(account, bls.DomainCheckpointManager) assert.Equal(t, key.Address().String(), key.String()) } diff --git a/e2e/framework/testserver.go b/e2e/framework/testserver.go index 77d015d7b6..8fd54c7c5c 100644 --- a/e2e/framework/testserver.go +++ b/e2e/framework/testserver.go @@ -653,14 +653,14 @@ func (t *Txn) sendImpl() error { return nil } -func (t *Txn) Send() *Txn { +func (t *Txn) Send() (*Txn, error) { if t.hash != nil { - panic("BUG: txn already sent") + return nil, errors.New("txn already sent") } t.sendErr = t.sendImpl() - return t + return t, nil } func (t *Txn) Receipt() *ethgo.Receipt { diff --git a/e2e/genesis_test.go b/e2e/genesis_test.go index 62e2671bd6..5fb8fbfef5 100644 --- a/e2e/genesis_test.go +++ b/e2e/genesis_test.go @@ -406,6 +406,7 @@ func TestGenesis_Predeployment(t *testing.T) { }) for humanIndex := range group.people { + humanIndex := humanIndex t.Run(fmt.Sprintf("groups[%d].people[%d] is set correctly", groupIndex, humanIndex), func(t *testing.T) { t.Parallel() @@ -415,6 +416,7 @@ func TestGenesis_Predeployment(t *testing.T) { } for idx := range groups { + idx := idx t.Run(fmt.Sprintf("groups[%d] is set correctly", idx), func(t *testing.T) { t.Parallel() diff --git a/e2e/jsonrpc_test.go b/e2e/jsonrpc_test.go index d4f70fd0df..2326e61c29 100644 --- a/e2e/jsonrpc_test.go +++ b/e2e/jsonrpc_test.go @@ -50,7 +50,9 @@ func TestJsonRPC(t *testing.T) { // Test. return the balance of an account newBalance := big.NewInt(22000) - srv.Txn(fund).Transfer(key1.Address(), newBalance).Send().NoFail(t) + txn, err := srv.Txn(fund).Transfer(key1.Address(), newBalance).Send() + require.NoError(t, err) + txn.NoFail(t) balance1, err = client.GetBalance(key1.Address(), ethgo.Latest) require.NoError(t, err) @@ -67,11 +69,15 @@ func TestJsonRPC(t *testing.T) { _, err := client.GetNonce(key1.Address(), ethgo.Latest) require.NoError(t, err) - srv.Txn(fund).Transfer(key1.Address(), big.NewInt(10000000000000000)).Send().NoFail(t) + txn, err := srv.Txn(fund).Transfer(key1.Address(), big.NewInt(10000000000000000)).Send() + require.NoError(t, err) + txn.NoFail(t) // Test. increase the nonce with new transactions - txn := srv.Txn(key1) - txn.Transfer(ethgo.ZeroAddress, one).Send().NoFail(t) + txn = srv.Txn(key1) + txn, err = txn.Send() + require.NoError(t, err) + txn.NoFail(t) nonce1, err := client.GetNonce(key1.Address(), ethgo.Latest) require.NoError(t, err) @@ -101,7 +107,9 @@ func TestJsonRPC(t *testing.T) { key1, _ := wallet.NewWalletFromPrivKey(priv) // fund the account so that it can deploy a contract - srv.Txn(fund).Transfer(key1.Address(), big.NewInt(10000000000000000)).Send().NoFail(t) + txn, err := srv.Txn(fund).Transfer(key1.Address(), big.NewInt(10000000000000000)).Send() + require.NoError(t, err) + txn.NoFail(t) codeAddr := ethgo.HexToAddress("0xDBfca0c43cA12759256a7Dd587Dc4c6EEC1D89A5") @@ -110,8 +118,10 @@ func TestJsonRPC(t *testing.T) { require.NoError(t, err) require.Equal(t, code, "0x") - txn := srv.Txn(key1) - txn.Deploy(bytecode).Send().NoFail(t) + txn = srv.Txn(key1) + txn, err = txn.Deploy(bytecode).Send() + require.NoError(t, err) + txn.NoFail(t) receipt := txn.Receipt() @@ -149,7 +159,9 @@ func TestJsonRPC(t *testing.T) { key1, _ := wallet.GenerateKey() txn := srv.Txn(fund) - txn.Transfer(key1.Address(), one).Send().NoFail(t) + txn, err := txn.Transfer(key1.Address(), one).Send() + require.NoError(t, err) + txn.NoFail(t) // Test. We cannot retrieve a receipt of an empty hash emptyReceipt, err := client.GetTransactionReceipt(ethgo.ZeroHash) @@ -170,7 +182,9 @@ func TestJsonRPC(t *testing.T) { // Test. The receipt of a deployed contract has the 'ContractAddress' field. txn = srv.Txn(fund) - txn.Deploy(bytecode).Send().NoFail(t) + txn, err = txn.Deploy(bytecode).Send() + require.NoError(t, err) + txn.NoFail(t) require.NotEqual(t, txn.Receipt().ContractAddress, ethgo.ZeroAddress) }) @@ -180,7 +194,9 @@ func TestJsonRPC(t *testing.T) { // Test. We should be able to query the transaction by its hash txn := srv.Txn(fund) - txn.Transfer(key1.Address(), one).Send().NoFail(t) + txn, err := txn.Transfer(key1.Address(), one).Send() + require.NoError(t, err) + txn.NoFail(t) ethTxn, err := client.GetTransactionByHash(txn.Receipt().TransactionHash) require.NoError(t, err) diff --git a/gorules/rules.go b/gorules/rules.go index 888057a5d6..81b2bb52a7 100644 --- a/gorules/rules.go +++ b/gorules/rules.go @@ -13,3 +13,7 @@ func OsFilePermissionRule(m dsl.Matcher) { m.Match(`os.$name($file, os.ModePerm)`).Report("os.$name called with file mode os.ModePerm (0777)") m.Match(`os.$name(os.ModePerm)`).Report("os.$name called with file mode os.ModePerm (0777)") } + +func ForbidPanicsRule(m dsl.Matcher) { + m.Match(`panic($_)`).Report("panics should not be manually used") +} diff --git a/gorules/testdata/rules_test_data.go b/gorules/testdata/rules_test_data.go index 120b4465a9..b78a3ec779 100644 --- a/gorules/testdata/rules_test_data.go +++ b/gorules/testdata/rules_test_data.go @@ -1,8 +1,14 @@ package target -import "os" +import ( + "errors" + "fmt" + "os" +) func testLintError() { + err := errors.New("test") + os.Mkdir("test", 0777) // want `OsFilePermissionRule: os.Mkdir called with file mode` os.Mkdir("test", os.ModePerm) // want `OsFilePermissionRule: os.Mkdir called with file mode` os.MkdirAll("test", 0777) // want `OsFilePermissionRule: os.MkdirAll called with file mode` @@ -11,6 +17,9 @@ func testLintError() { os.Chmod("test", os.ModePerm) // want `OsFilePermissionRule: os.Chmod called with file mode` os.OpenFile("test", 0, 0777) // want `OsFilePermissionRule: os.OpenFile called with file mode` os.OpenFile("test", 0, os.ModePerm) // want `OsFilePermissionRule: os.OpenFile called with file mode` + panic("test") // want `ForbidPanicsRule: panics should not be manually used` + panic(fmt.Sprintf("test error")) // want `ForbidPanicsRule: panics should not be manually used` + panic(err) // want `ForbidPanicsRule: panics should not be manually used` } func testNoLintError() { diff --git a/helper/hex/hex.go b/helper/hex/hex.go index 1b983c3205..7ab38d903d 100644 --- a/helper/hex/hex.go +++ b/helper/hex/hex.go @@ -38,7 +38,7 @@ func DecodeHex(str string) ([]byte, error) { func MustDecodeHex(str string) []byte { buf, err := DecodeHex(str) if err != nil { - panic(fmt.Errorf("could not decode hex: %w", err)) + panic(fmt.Errorf("could not decode hex: %w", err)) //nolint:gocritic } return buf diff --git a/jsonrpc/bridge_endpoint_test.go b/jsonrpc/bridge_endpoint_test.go index 04f3554b50..a035de4bf3 100644 --- a/jsonrpc/bridge_endpoint_test.go +++ b/jsonrpc/bridge_endpoint_test.go @@ -11,7 +11,7 @@ import ( func TestBridgeEndpoint(t *testing.T) { store := newMockStore() - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), store, &dispatcherParams{ diff --git a/jsonrpc/dispatcher.go b/jsonrpc/dispatcher.go index 8423786cb1..77e2ba5161 100644 --- a/jsonrpc/dispatcher.go +++ b/jsonrpc/dispatcher.go @@ -62,7 +62,7 @@ func newDispatcher( logger hclog.Logger, store JSONRPCStore, params *dispatcherParams, -) *Dispatcher { +) (*Dispatcher, error) { d := &Dispatcher{ logger: logger.Named("dispatcher"), params: params, @@ -73,12 +73,14 @@ func newDispatcher( go d.filterManager.Run() } - d.registerEndpoints(store) + if err := d.registerEndpoints(store); err != nil { + return nil, err + } - return d + return d, nil } -func (d *Dispatcher) registerEndpoints(store JSONRPCStore) { +func (d *Dispatcher) registerEndpoints(store JSONRPCStore) error { d.endpoints.Eth = &Eth{ d.logger, store, @@ -104,12 +106,29 @@ func (d *Dispatcher) registerEndpoints(store JSONRPCStore) { store, } - d.registerService("eth", d.endpoints.Eth) - d.registerService("net", d.endpoints.Net) - d.registerService("web3", d.endpoints.Web3) - d.registerService("txpool", d.endpoints.TxPool) - d.registerService("bridge", d.endpoints.Bridge) - d.registerService("debug", d.endpoints.Debug) + var err error + + if err = d.registerService("eth", d.endpoints.Eth); err != nil { + return err + } + + if err = d.registerService("net", d.endpoints.Net); err != nil { + return err + } + + if err = d.registerService("web3", d.endpoints.Web3); err != nil { + return err + } + + if err = d.registerService("txpool", d.endpoints.TxPool); err != nil { + return err + } + + if err = d.registerService("bridge", d.endpoints.Bridge); err != nil { + return err + } + + return d.registerService("debug", d.endpoints.Debug) } func (d *Dispatcher) getFnHandler(req Request) (*serviceData, *funcData, Error) { @@ -380,18 +399,18 @@ func (d *Dispatcher) logInternalError(method string, err error) { d.logger.Error("failed to dispatch", "method", method, "err", err) } -func (d *Dispatcher) registerService(serviceName string, service interface{}) { +func (d *Dispatcher) registerService(serviceName string, service interface{}) error { if d.serviceMap == nil { d.serviceMap = map[string]*serviceData{} } if serviceName == "" { - panic("jsonrpc: serviceName cannot be empty") + return errors.New("jsonrpc: serviceName cannot be empty") } st := reflect.TypeOf(service) if st.Kind() == reflect.Struct { - panic(fmt.Sprintf("jsonrpc: service '%s' must be a pointer to struct", serviceName)) + return errors.New(fmt.Sprintf("jsonrpc: service '%s' must be a pointer to struct", serviceName)) } funcMap := make(map[string]*funcData) @@ -412,7 +431,7 @@ func (d *Dispatcher) registerService(serviceName string, service interface{}) { var err error if fd.inNum, fd.reqt, err = validateFunc(funcName, fd.fv, true); err != nil { - panic(fmt.Sprintf("jsonrpc: %s", err)) + return fmt.Errorf("jsonrpc: %w", err) } // check if last item is a pointer if fd.numParams() != 0 { @@ -429,6 +448,8 @@ func (d *Dispatcher) registerService(serviceName string, service interface{}) { sv: reflect.ValueOf(service), funcMap: funcMap, } + + return nil } func validateFunc(funcName string, fv reflect.Value, _ bool) (inNum int, reqt []reflect.Type, err error) { diff --git a/jsonrpc/dispatcher_test.go b/jsonrpc/dispatcher_test.go index 315515febb..3c5ca9ad8a 100644 --- a/jsonrpc/dispatcher_test.go +++ b/jsonrpc/dispatcher_test.go @@ -10,6 +10,7 @@ import ( "github.com/0xPolygon/polygon-edge/types" "github.com/hashicorp/go-hclog" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -62,7 +63,7 @@ func TestDispatcher_HandleWebsocketConnection_EthSubscribe(t *testing.T) { t.Parallel() store := newMockStore() - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), store, &dispatcherParams{ @@ -72,7 +73,6 @@ func TestDispatcher_HandleWebsocketConnection_EthSubscribe(t *testing.T) { blockRangeLimit: 1000, }, ) - mockConnection, msgCh := newMockWsConnWithMsgCh() req := []byte(`{ @@ -103,7 +103,7 @@ func TestDispatcher_HandleWebsocketConnection_EthSubscribe(t *testing.T) { func TestDispatcher_WebsocketConnection_RequestFormats(t *testing.T) { store := newMockStore() - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), store, &dispatcherParams{ @@ -214,7 +214,7 @@ func (m *mockService) Filter(f LogQuery) (interface{}, error) { func TestDispatcherFuncDecode(t *testing.T) { srv := &mockService{msgCh: make(chan interface{}, 10)} - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -224,7 +224,8 @@ func TestDispatcherFuncDecode(t *testing.T) { blockRangeLimit: 1000, }, ) - dispatcher.registerService("mock", srv) + + require.NoError(t, dispatcher.registerService("mock", srv)) handleReq := func(typ string, msg string) interface{} { _, err := dispatcher.handleReq(Request{ @@ -306,7 +307,7 @@ func TestDispatcherBatchRequest(t *testing.T) { { "leading-whitespace", "test with leading whitespace (\" \\t\\n\\n\\r\\)", - newDispatcher( + newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -331,7 +332,7 @@ func TestDispatcherBatchRequest(t *testing.T) { { "valid-batch-req", "test with batch req length within batchRequestLengthLimit", - newDispatcher( + newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -360,7 +361,7 @@ func TestDispatcherBatchRequest(t *testing.T) { { "invalid-batch-req", "test with batch req length exceeding batchRequestLengthLimit", - newDispatcher( + newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -383,7 +384,7 @@ func TestDispatcherBatchRequest(t *testing.T) { { "no-limits", "test when limits are not set", - newDispatcher( + newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -455,3 +456,12 @@ func TestDispatcherBatchRequest(t *testing.T) { } } } + +func newTestDispatcher(t *testing.T, logger hclog.Logger, store JSONRPCStore, params *dispatcherParams) *Dispatcher { + t.Helper() + + d, err := newDispatcher(logger, store, params) + require.NoError(t, err) + + return d +} diff --git a/jsonrpc/jsonrpc.go b/jsonrpc/jsonrpc.go index 4737c60c7a..6df997eb58 100644 --- a/jsonrpc/jsonrpc.go +++ b/jsonrpc/jsonrpc.go @@ -31,7 +31,7 @@ func (s serverType) String() string { case serverWS: return "ws" default: - panic("BUG: Not expected") + panic("BUG: Not expected") //nolint:gocritic } } @@ -72,20 +72,26 @@ type Config struct { // NewJSONRPC returns the JSONRPC http server func NewJSONRPC(logger hclog.Logger, config *Config) (*JSONRPC, error) { + d, err := newDispatcher( + logger, + config.Store, + &dispatcherParams{ + chainID: config.ChainID, + chainName: config.ChainName, + priceLimit: config.PriceLimit, + jsonRPCBatchLengthLimit: config.BatchLengthLimit, + blockRangeLimit: config.BlockRangeLimit, + }, + ) + + if err != nil { + return nil, err + } + srv := &JSONRPC{ - logger: logger.Named("jsonrpc"), - config: config, - dispatcher: newDispatcher( - logger, - config.Store, - &dispatcherParams{ - chainID: config.ChainID, - chainName: config.ChainName, - priceLimit: config.PriceLimit, - jsonRPCBatchLengthLimit: config.BatchLengthLimit, - blockRangeLimit: config.BlockRangeLimit, - }, - ), + logger: logger.Named("jsonrpc"), + config: config, + dispatcher: d, } // start http server diff --git a/jsonrpc/net_endpoint_test.go b/jsonrpc/net_endpoint_test.go index d03d32c856..3b1e39e722 100644 --- a/jsonrpc/net_endpoint_test.go +++ b/jsonrpc/net_endpoint_test.go @@ -8,7 +8,7 @@ import ( ) func TestNetEndpoint_PeerCount(t *testing.T) { - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ diff --git a/jsonrpc/web3_endpoint_test.go b/jsonrpc/web3_endpoint_test.go index abcb4e2631..30fc8c6992 100644 --- a/jsonrpc/web3_endpoint_test.go +++ b/jsonrpc/web3_endpoint_test.go @@ -11,7 +11,7 @@ import ( ) func TestWeb3EndpointSha3(t *testing.T) { - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ @@ -39,7 +39,7 @@ func TestWeb3EndpointClientVersion(t *testing.T) { chainID = uint64(100) ) - dispatcher := newDispatcher( + dispatcher := newTestDispatcher(t, hclog.NewNullLogger(), newMockStore(), &dispatcherParams{ diff --git a/network/common/common.go b/network/common/common.go index 1b2d2d1590..168b71a641 100644 --- a/network/common/common.go +++ b/network/common/common.go @@ -57,10 +57,10 @@ var ( ) // AddrInfoToString converts an AddrInfo into a string representation that can be dialed from another node -func AddrInfoToString(addr *peer.AddrInfo) string { +func AddrInfoToString(addr *peer.AddrInfo) (string, error) { // Safety check if len(addr.Addrs) == 0 { - panic("No dial addresses found") + return "", errors.New("no dial addresses found") } dialAddress := addr.Addrs[0].String() @@ -79,7 +79,7 @@ func AddrInfoToString(addr *peer.AddrInfo) string { } // Format output and return - return dialAddress + "/p2p/" + addr.ID.String() + return dialAddress + "/p2p/" + addr.ID.String(), nil } // MultiAddrFromDNS constructs a multiAddr from the passed in DNS address and port combination diff --git a/network/discovery/discovery.go b/network/discovery/discovery.go index 2d5e899c3f..ba25dabe7b 100644 --- a/network/discovery/discovery.go +++ b/network/discovery/discovery.go @@ -424,7 +424,12 @@ func (d *DiscoveryService) FindPeers( } if info := d.baseServer.GetPeerInfo(id); len(info.Addrs) > 0 { - filteredPeers = append(filteredPeers, common.AddrInfoToString(info)) + addr, err := common.AddrInfoToString(info) + if err != nil { + return nil, err + } + + filteredPeers = append(filteredPeers, addr) } } diff --git a/network/discovery/discovery_test.go b/network/discovery/discovery_test.go index 4355a3b654..e4a261a887 100644 --- a/network/discovery/discovery_test.go +++ b/network/discovery/discovery_test.go @@ -141,7 +141,12 @@ func TestDiscoveryService_BootnodePeerDiscovery(t *testing.T) { for i, peerInfo := range randomPeers { // The peer info needs to be formatted as a MultiAddr - peers[i] = common.AddrInfoToString(peerInfo) + addr, err := common.AddrInfoToString(peerInfo) + if err != nil { + return nil, err + } + + peers[i] = addr } return &proto.FindPeersResp{ diff --git a/network/grpc/grpc.go b/network/grpc/grpc.go index 945a043f46..4967226294 100644 --- a/network/grpc/grpc.go +++ b/network/grpc/grpc.go @@ -126,7 +126,7 @@ func WrapClient(s network.Stream) *grpc.ClientConn { if err != nil { // TODO: this should not fail at all - panic(err) + panic(err) //nolint:gocritic } return conn diff --git a/network/server.go b/network/server.go index a638a3f813..51c097d96f 100644 --- a/network/server.go +++ b/network/server.go @@ -242,7 +242,12 @@ func setupLibp2pKey(secretsManager secrets.SecretsManager) (crypto.PrivKey, erro // Start starts the networking services func (s *Server) Start() error { - s.logger.Info("LibP2P server running", "addr", common.AddrInfoToString(s.AddrInfo())) + addr, err := common.AddrInfoToString(s.AddrInfo()) + if err != nil { + return err + } + + s.logger.Info("LibP2P server running", "addr", addr) if setupErr := s.setupIdentity(); setupErr != nil { return fmt.Errorf("unable to setup identity, %w", setupErr) diff --git a/network/server_test.go b/network/server_test.go index a7753939a3..2b82dc7c97 100644 --- a/network/server_test.go +++ b/network/server_test.go @@ -209,7 +209,9 @@ func TestEncodingPeerAddr(t *testing.T) { Addrs: []multiaddr.Multiaddr{addr}, } - str := common.AddrInfoToString(info) + str, err := common.AddrInfoToString(info) + assert.NoError(t, err) + info2, err := common.StringToAddrInfo(str) assert.NoError(t, err) assert.Equal(t, info, info2) @@ -287,11 +289,12 @@ func TestAddrInfoToString(t *testing.T) { t.Fatalf("Unable to construct multiaddrs, %v", constructErr) } - dialAddress := common.AddrInfoToString(&peer.AddrInfo{ + dialAddress, err := common.AddrInfoToString(&peer.AddrInfo{ ID: defaultPeerID, Addrs: multiAddrs, }) + assert.NoError(t, err) assert.Equal(t, testCase.expected, dialAddress) }) } @@ -394,10 +397,13 @@ func TestPeerReconnection(t *testing.T) { c.NoDiscover = false }, ServerCallback: func(server *Server) { - server.config.Chain.Bootnodes = []string{ - common.AddrInfoToString(bootnodes[0].AddrInfo()), - common.AddrInfoToString(bootnodes[1].AddrInfo()), - } + addr1, err := common.AddrInfoToString(bootnodes[0].AddrInfo()) + assert.NoError(t, err) + + addr2, err := common.AddrInfoToString(bootnodes[1].AddrInfo()) + assert.NoError(t, err) + + server.config.Chain.Bootnodes = []string{addr1, addr2} }, } diff --git a/server/server.go b/server/server.go index 864f024cbe..7acff4ffdc 100644 --- a/server/server.go +++ b/server/server.go @@ -202,7 +202,11 @@ func NewServer(config *Config) (*Server, error) { } // compute the genesis root state - genesisRoot := m.executor.WriteGenesis(config.Chain.Genesis.Alloc) + genesisRoot, err := m.executor.WriteGenesis(config.Chain.Genesis.Alloc) + if err != nil { + return nil, err + } + config.Chain.Genesis.StateRoot = genesisRoot // use the eip155 signer diff --git a/server/system_service.go b/server/system_service.go index d6cf0b00e0..7bb27ab827 100644 --- a/server/system_service.go +++ b/server/system_service.go @@ -30,13 +30,18 @@ type systemService struct { func (s *systemService) GetStatus(ctx context.Context, req *empty.Empty) (*proto.ServerStatus, error) { header := s.server.blockchain.Header() + addr, err := common.AddrInfoToString(s.server.network.AddrInfo()) + if err != nil { + return nil, err + } + status := &proto.ServerStatus{ Network: s.server.chain.Params.ChainID, Current: &proto.ServerStatus_Block{ Number: int64(header.Number), Hash: header.Hash.String(), }, - P2PAddr: common.AddrInfoToString(s.server.network.AddrInfo()), + P2PAddr: addr, } return status, nil diff --git a/state/executor.go b/state/executor.go index 99cf380ac7..46edc66e96 100644 --- a/state/executor.go +++ b/state/executor.go @@ -51,7 +51,7 @@ func NewExecutor(config *chain.Params, s State, logger hclog.Logger) *Executor { } } -func (e *Executor) WriteGenesis(alloc map[types.Address]*chain.GenesisAccount) types.Hash { +func (e *Executor) WriteGenesis(alloc map[types.Address]*chain.GenesisAccount) (types.Hash, error) { snap := e.state.NewSnapshot() txn := NewTxn(snap) config := e.config.Forks.At(0) @@ -90,14 +90,14 @@ func (e *Executor) WriteGenesis(alloc map[types.Address]*chain.GenesisAccount) t if e.GenesisPostHook != nil { if err := e.GenesisPostHook(transition); err != nil { - panic(fmt.Errorf("Error writing genesis block: %w", err)) + return types.Hash{}, fmt.Errorf("Error writing genesis block: %w", err) } } objs := txn.Commit(false) _, root := snap.Commit(objs) - return types.BytesToHash(root) + return types.BytesToHash(root), nil } type BlockResult struct { diff --git a/state/immutable-trie/hasher.go b/state/immutable-trie/hasher.go index 2e3bb841ed..38ea53350c 100644 --- a/state/immutable-trie/hasher.go +++ b/state/immutable-trie/hasher.go @@ -75,11 +75,11 @@ func (h *hasher) Hash(data []byte) []byte { n, err := h.hash.Read(h.tmp[:]) if err != nil { - panic(err) + panic(err) //nolint:gocritic } if n != 32 { - panic("incorrect length") + panic("incorrect length") //nolint:gocritic } return h.tmp[:] @@ -176,7 +176,7 @@ func (t *Txn) hash(node Node, h *hasher, a *fastrlp.Arena, d int) *fastrlp.Value } default: - panic(fmt.Sprintf("unknown node type %v", n)) + panic(fmt.Sprintf("unknown node type %v", n)) //nolint:gocritic } if val.Len() < 32 { diff --git a/state/immutable-trie/snapshot.go b/state/immutable-trie/snapshot.go index 00c298ecee..935fc52da4 100644 --- a/state/immutable-trie/snapshot.go +++ b/state/immutable-trie/snapshot.go @@ -99,7 +99,7 @@ func (s *Snapshot) Commit(objs []*state.Object) (state.Snapshot, []byte) { if len(obj.Storage) != 0 { trie, err := s.state.newTrieAt(obj.Root) if err != nil { - panic(err) + panic(err) //nolint:gocritic } localTxn := trie.Txn(s.state.storage) diff --git a/state/immutable-trie/storage.go b/state/immutable-trie/storage.go index 1212592af0..6ae99e702a 100644 --- a/state/immutable-trie/storage.go +++ b/state/immutable-trie/storage.go @@ -75,7 +75,7 @@ func (kv *KVStorage) Get(k []byte) ([]byte, bool) { if err.Error() == "leveldb: not found" { return nil, false } else { - panic(err) + panic(err) //nolint:gocritic } } diff --git a/state/immutable-trie/trie.go b/state/immutable-trie/trie.go index 3660bc245f..c34b17cb8a 100644 --- a/state/immutable-trie/trie.go +++ b/state/immutable-trie/trie.go @@ -31,7 +31,7 @@ func (v *ValueNode) Hash() ([]byte, bool) { // SetHash implements the node interface func (v *ValueNode) SetHash(b []byte) []byte { - panic("We cannot set hash on value node") + panic("We cannot set hash on value node") //nolint:gocritic } type common struct { @@ -169,7 +169,7 @@ func (t *Txn) lookup(node interface{}, key []byte) (Node, []byte) { if n.hash { nc, ok, err := GetNode(n.buf, t.storage) if err != nil { - panic(err) + panic(err) //nolint:gocritic } if !ok { @@ -215,7 +215,7 @@ func (t *Txn) lookup(node interface{}, key []byte) (Node, []byte) { return nil, res default: - panic(fmt.Sprintf("unknown node type %v", n)) + panic(fmt.Sprintf("unknown node type %v", n)) //nolint:gocritic } } @@ -261,7 +261,7 @@ func (t *Txn) insert(node Node, search, value []byte) Node { if n.hash { nc, ok, err := GetNode(n.buf, t.storage) if err != nil { - panic(err) + panic(err) //nolint:gocritic } if !ok { @@ -327,7 +327,7 @@ func (t *Txn) insert(node Node, search, value []byte) Node { } default: - panic(fmt.Sprintf("unknown node type %v", n)) + panic(fmt.Sprintf("unknown node type %v", n)) //nolint:gocritic } } @@ -376,7 +376,7 @@ func (t *Txn) delete(node Node, search []byte) (Node, bool) { if n.hash { nc, ok, err := GetNode(n.buf, t.storage) if err != nil { - panic(err) + panic(err) //nolint:gocritic } if !ok { @@ -449,7 +449,7 @@ func (t *Txn) delete(node Node, search []byte) (Node, bool) { // This needs better testing aux, ok, err := GetNode(vv.buf, t.storage) if err != nil { - panic(err) + panic(err) //nolint:gocritic } if !ok { @@ -475,7 +475,7 @@ func (t *Txn) delete(node Node, search []byte) (Node, bool) { return ncc, true } - panic("it should not happen") + panic("it should not happen") //nolint:gocritic } func prefixLen(k1, k2 []byte) int { diff --git a/state/runtime/evm/dispatch_table.go b/state/runtime/evm/dispatch_table.go index 74156206cd..7214a18dcd 100644 --- a/state/runtime/evm/dispatch_table.go +++ b/state/runtime/evm/dispatch_table.go @@ -12,7 +12,7 @@ var dispatchTable [256]handler func register(op OpCode, h handler) { if dispatchTable[op].inst != nil { - panic(fmt.Errorf("instruction already exists")) + panic(fmt.Errorf("instruction already exists")) //nolint:gocritic } dispatchTable[op] = h diff --git a/state/runtime/evm/evm_test.go b/state/runtime/evm/evm_test.go index e29cfd2b38..babbf9e51b 100644 --- a/state/runtime/evm/evm_test.go +++ b/state/runtime/evm/evm_test.go @@ -30,11 +30,11 @@ type mockHost struct { } func (m *mockHost) AccountExists(addr types.Address) bool { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetStorage(addr types.Address, key types.Hash) types.Hash { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) SetStorage( @@ -43,55 +43,55 @@ func (m *mockHost) SetStorage( value types.Hash, config *chain.ForksInTime, ) runtime.StorageStatus { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetBalance(addr types.Address) *big.Int { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetCodeSize(addr types.Address) int { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetCodeHash(addr types.Address) types.Hash { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetCode(addr types.Address) []byte { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) Selfdestruct(addr types.Address, beneficiary types.Address) { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetTxContext() runtime.TxContext { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetBlockHash(number int64) types.Hash { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) EmitLog(addr types.Address, topics []types.Hash, data []byte) { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) Callx(*runtime.Contract, runtime.Host) *runtime.ExecutionResult { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) Empty(addr types.Address) bool { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetNonce(addr types.Address) uint64 { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) Transfer(from types.Address, to types.Address, amount *big.Int) error { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func (m *mockHost) GetTracer() runtime.VMTracer { @@ -99,7 +99,7 @@ func (m *mockHost) GetTracer() runtime.VMTracer { } func (m *mockHost) GetRefund() uint64 { - panic("Not implemented in tests") + panic("Not implemented in tests") //nolint:gocritic } func TestRun(t *testing.T) { diff --git a/state/runtime/evm/instructions.go b/state/runtime/evm/instructions.go index e0219f9e5e..773d168914 100644 --- a/state/runtime/evm/instructions.go +++ b/state/runtime/evm/instructions.go @@ -1145,7 +1145,7 @@ func opCall(op OpCode) instruction { callType = runtime.StaticCall default: - panic("not expected") + panic("not expected") //nolint:gocritic } contract, offset, size, err := c.buildCallContract(op) diff --git a/state/runtime/evm/state.go b/state/runtime/evm/state.go index 90d374c057..74199ca4d5 100644 --- a/state/runtime/evm/state.go +++ b/state/runtime/evm/state.go @@ -123,7 +123,7 @@ func (c *state) Halt() { func (c *state) exit(err error) { if err == nil { - panic("cannot stop with none") + return } c.stop = true diff --git a/state/runtime/precompiled/console.go b/state/runtime/precompiled/console.go index eead1c558d..da9e531d43 100644 --- a/state/runtime/precompiled/console.go +++ b/state/runtime/precompiled/console.go @@ -4,6 +4,7 @@ import ( _ "embed" "encoding/hex" "fmt" + "log" "regexp" "github.com/0xPolygon/polygon-edge/chain" @@ -29,7 +30,7 @@ func init() { // objects are defined without bytes (i.e. 256). typ, err := abi.NewType("tuple" + signature) if err != nil { - panic(fmt.Errorf("BUG: Failed to parse %s", signature)) + log.Fatal(fmt.Errorf("BUG: Failed to parse %s", signature)) } // signature of the call. Use the version without the bytes in 'uint'. diff --git a/state/runtime/precompiled/native_transfer_test.go b/state/runtime/precompiled/native_transfer_test.go index 7217810319..e2260abfcb 100644 --- a/state/runtime/precompiled/native_transfer_test.go +++ b/state/runtime/precompiled/native_transfer_test.go @@ -38,11 +38,11 @@ func Test_NativeTransferPrecompile(t *testing.T) { require.ErrorIs(t, err, runtime.ErrUnauthorizedCaller) }) t.Run("Insufficient balance", func(t *testing.T) { - err := run(contracts.NativeERC20TokenContract, sender, receiver, big.NewInt(10), newDummyHost()) + err := run(contracts.NativeERC20TokenContract, sender, receiver, big.NewInt(10), newDummyHost(t)) require.ErrorIs(t, err, runtime.ErrInsufficientBalance) }) t.Run("Correct transfer", func(t *testing.T) { - host := newDummyHost() + host := newDummyHost(t) host.AddBalance(sender, big.NewInt(1000)) err := run(contracts.NativeERC20TokenContract, sender, receiver, big.NewInt(100), host) @@ -56,11 +56,16 @@ func Test_NativeTransferPrecompile(t *testing.T) { var _ runtime.Host = (*dummyHost)(nil) type dummyHost struct { + t *testing.T + balances map[types.Address]*big.Int } -func newDummyHost() *dummyHost { +func newDummyHost(t *testing.T) *dummyHost { + t.Helper() + return &dummyHost{ + t: t, balances: map[types.Address]*big.Int{}, } } @@ -72,15 +77,21 @@ func (d dummyHost) AddBalance(addr types.Address, balance *big.Int) { } func (d dummyHost) AccountExists(addr types.Address) bool { - panic("not implemented") + d.t.Fatalf("AccountExists is not implemented") + + return false } func (d dummyHost) GetStorage(addr types.Address, key types.Hash) types.Hash { - panic("not implemented") + d.t.Fatalf("GetStorage is not implemented") + + return types.ZeroHash } func (d dummyHost) SetStorage(addr types.Address, key types.Hash, value types.Hash, config *chain.ForksInTime) runtime.StorageStatus { - panic("not implemented") + d.t.Fatalf("SetStorage is not implemented") + + return runtime.StorageAdded } func (d dummyHost) GetBalance(addr types.Address) *big.Int { @@ -93,43 +104,59 @@ func (d dummyHost) GetBalance(addr types.Address) *big.Int { } func (d dummyHost) GetCodeSize(addr types.Address) int { - panic("not implemented") + d.t.Fatalf("GetCodeSize is not implemented") + + return -1 } func (d dummyHost) GetCodeHash(addr types.Address) types.Hash { - panic("not implemented") + d.t.Fatalf("GetCodeHash is not implemented") + + return types.ZeroHash } func (d dummyHost) GetCode(addr types.Address) []byte { - panic("not implemented") + d.t.Fatalf("GetCode is not implemented") + + return nil } func (d dummyHost) Selfdestruct(addr types.Address, beneficiary types.Address) { - panic("not implemented") + d.t.Fatalf("Selfdestruct is not implemented") } func (d dummyHost) GetTxContext() runtime.TxContext { - panic("not implemented") + d.t.Fatalf("GetTxContext is not implemented") + + return runtime.TxContext{} } func (d dummyHost) GetBlockHash(number int64) types.Hash { - panic("not implemented") + d.t.Fatalf("GetTxContext is not implemented") + + return types.ZeroHash } func (d dummyHost) EmitLog(addr types.Address, topics []types.Hash, data []byte) { - panic("not implemented") + d.t.Fatalf("EmitLog is not implemented") } func (d dummyHost) Callx(_ *runtime.Contract, _ runtime.Host) *runtime.ExecutionResult { - panic("not implemented") + d.t.Fatalf("Callx is not implemented") + + return nil } func (d dummyHost) Empty(addr types.Address) bool { - panic("not implemented") + d.t.Fatalf("Callx is not implemented") + + return true } func (d dummyHost) GetNonce(addr types.Address) uint64 { - panic("not implemented") + d.t.Fatalf("GetNonce is not implemented") + + return 0 } func (d dummyHost) Transfer(from types.Address, to types.Address, amount *big.Int) error { diff --git a/state/runtime/precompiled/precompiled.go b/state/runtime/precompiled/precompiled.go index 3e18ec45e7..5bce6a85c9 100644 --- a/state/runtime/precompiled/precompiled.go +++ b/state/runtime/precompiled/precompiled.go @@ -2,6 +2,7 @@ package precompiled import ( "encoding/binary" + "log" "github.com/0xPolygon/polygon-edge/chain" "github.com/0xPolygon/polygon-edge/contracts" @@ -14,11 +15,26 @@ import ( var _ runtime.Runtime = &Precompiled{} var ( + abiBoolTrue, abiBoolFalse []byte +) + +func init() { // abiBoolTrue is ABI encoded true boolean value - abiBoolTrue = abiBoolMustEncode(true) + encodedBool, err := abi.MustNewType("bool").Encode(true) + if err != nil { + log.Fatal(err) + } + + abiBoolTrue = encodedBool + // abiBoolFalse is ABI encoded false boolean value - abiBoolFalse = abiBoolMustEncode(false) -) + encodedBool, err = abi.MustNewType("bool").Encode(false) + if err != nil { + log.Fatal(err) + } + + abiBoolFalse = encodedBool +} type contract interface { gas(input []byte, config *chain.ForksInTime) uint64 @@ -187,14 +203,3 @@ func (p *Precompiled) getUint64(input []byte) (uint64, []byte) { return num, input } - -// abiBoolMustEncode encodes the given value using the given ABI type. -// panics if there is an error occurred. -func abiBoolMustEncode(v bool) []byte { - raw, err := abi.MustNewType("bool").Encode(v) - if err != nil { - panic(err) - } - - return raw -} diff --git a/state/runtime/runtime.go b/state/runtime/runtime.go index 253bfd2c6a..58b1ff3f63 100644 --- a/state/runtime/runtime.go +++ b/state/runtime/runtime.go @@ -51,7 +51,7 @@ func (s StorageStatus) String() string { case StorageDeleted: return "StorageDeleted" default: - panic("BUG: storage status not found") + panic("BUG: storage status not found") //nolint:gocritic } } diff --git a/state/txn.go b/state/txn.go index 4084809822..bc5e2b6019 100644 --- a/state/txn.go +++ b/state/txn.go @@ -70,7 +70,7 @@ func (txn *Txn) Snapshot() int { // RevertToSnapshot reverts to a given snapshot func (txn *Txn) RevertToSnapshot(id int) { if id > len(txn.snapshots) { - panic("") + panic("") //nolint:gocritic } tree := txn.snapshots[id] @@ -551,13 +551,13 @@ func (txn *Txn) CleanDeleteObjects(deleteEmptyObjects bool) { for _, k := range remove { v, ok := txn.txn.Get(k) if !ok { - panic("it should not happen") + panic("it should not happen") //nolint:gocritic } obj, ok := v.(*StateObject) if !ok { - panic("it should not happen") + panic("it should not happen") //nolint:gocritic } obj2 := obj.Copy() diff --git a/txpool/txpool_test.go b/txpool/txpool_test.go index 750f0ad687..996d6780b7 100644 --- a/txpool/txpool_test.go +++ b/txpool/txpool_test.go @@ -560,7 +560,7 @@ func TestAddGossipTx(t *testing.T) { signedTx, err := signer.SignTx(tx, key) if err != nil { - t.Fatalf("cannot sign transction - err: %v", err) + t.Fatalf("cannot sign transaction - err: %v", err) } // send tx @@ -1833,11 +1833,11 @@ func (e *eoa) create(t *testing.T) *eoa { return e } -func (e *eoa) signTx(tx *types.Transaction, signer crypto.TxSigner) *types.Transaction { +func (e *eoa) signTx(t *testing.T, tx *types.Transaction, signer crypto.TxSigner) *types.Transaction { + t.Helper() + signedTx, err := signer.SignTx(tx, e.PrivateKey) - if err != nil { - panic("signTx failed") - } + require.NoError(t, err) return signedTx } @@ -1862,30 +1862,30 @@ func TestResetAccounts_Promoted(t *testing.T) { allTxs := map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 0, 1), signerEIP155), // will be pruned - eoa1.signTx(newTx(addr1, 1, 1), signerEIP155), // will be pruned - eoa1.signTx(newTx(addr1, 2, 1), signerEIP155), // will be pruned - eoa1.signTx(newTx(addr1, 3, 1), signerEIP155), // will be pruned + eoa1.signTx(t, newTx(addr1, 0, 1), signerEIP155), // will be pruned + eoa1.signTx(t, newTx(addr1, 1, 1), signerEIP155), // will be pruned + eoa1.signTx(t, newTx(addr1, 2, 1), signerEIP155), // will be pruned + eoa1.signTx(t, newTx(addr1, 3, 1), signerEIP155), // will be pruned }, addr2: { - eoa2.signTx(newTx(addr2, 0, 1), signerEIP155), // will be pruned - eoa2.signTx(newTx(addr2, 1, 1), signerEIP155), // will be pruned + eoa2.signTx(t, newTx(addr2, 0, 1), signerEIP155), // will be pruned + eoa2.signTx(t, newTx(addr2, 1, 1), signerEIP155), // will be pruned }, addr3: { - eoa3.signTx(newTx(addr3, 0, 1), signerEIP155), // will be pruned - eoa3.signTx(newTx(addr3, 1, 1), signerEIP155), // will be pruned - eoa3.signTx(newTx(addr3, 2, 1), signerEIP155), // will be pruned + eoa3.signTx(t, newTx(addr3, 0, 1), signerEIP155), // will be pruned + eoa3.signTx(t, newTx(addr3, 1, 1), signerEIP155), // will be pruned + eoa3.signTx(t, newTx(addr3, 2, 1), signerEIP155), // will be pruned }, addr4: { // all txs will be pruned - eoa4.signTx(newTx(addr4, 0, 1), signerEIP155), // will be pruned - eoa4.signTx(newTx(addr4, 1, 1), signerEIP155), // will be pruned - eoa4.signTx(newTx(addr4, 2, 1), signerEIP155), // will be pruned - eoa4.signTx(newTx(addr4, 3, 1), signerEIP155), // will be pruned - eoa4.signTx(newTx(addr4, 4, 1), signerEIP155), // will be pruned + eoa4.signTx(t, newTx(addr4, 0, 1), signerEIP155), // will be pruned + eoa4.signTx(t, newTx(addr4, 1, 1), signerEIP155), // will be pruned + eoa4.signTx(t, newTx(addr4, 2, 1), signerEIP155), // will be pruned + eoa4.signTx(t, newTx(addr4, 3, 1), signerEIP155), // will be pruned + eoa4.signTx(t, newTx(addr4, 4, 1), signerEIP155), // will be pruned }, } @@ -1993,22 +1993,22 @@ func TestResetAccounts_Enqueued(t *testing.T) { allTxs := map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 3, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 4, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 5, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 3, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 4, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 5, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 2, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 3, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 4, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 5, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 6, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 7, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 2, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 3, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 4, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 5, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 6, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 7, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 7, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 8, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 9, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 7, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 8, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 9, 1), signerEIP155), }, } newNonces := map[types.Address]uint64{ @@ -2540,40 +2540,40 @@ func TestGetTxs(t *testing.T) { name: "get promoted txs", allTxs: map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 0, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 1, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 2, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 0, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 1, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 2, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 0, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 1, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 2, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 0, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 1, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 2, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 0, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 1, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 2, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 0, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 1, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 2, 1), signerEIP155), }, }, expectedPromoted: map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 0, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 1, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 2, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 0, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 1, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 2, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 0, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 1, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 2, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 0, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 1, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 2, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 0, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 1, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 2, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 0, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 1, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 2, 1), signerEIP155), }, }, }, @@ -2581,73 +2581,73 @@ func TestGetTxs(t *testing.T) { name: "get all txs", allTxs: map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 0, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 1, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 2, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 0, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 1, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 2, 1), signerEIP155), // enqueued - eoa1.signTx(newTx(addr1, 10, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 11, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 12, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 10, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 11, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 12, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 0, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 1, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 2, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 0, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 1, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 2, 1), signerEIP155), // enqueued - eoa2.signTx(newTx(addr2, 10, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 11, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 12, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 10, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 11, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 12, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 0, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 1, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 2, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 0, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 1, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 2, 1), signerEIP155), // enqueued - eoa3.signTx(newTx(addr3, 10, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 11, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 12, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 10, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 11, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 12, 1), signerEIP155), }, }, expectedPromoted: map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 0, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 1, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 2, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 0, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 1, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 2, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 0, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 1, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 2, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 0, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 1, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 2, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 0, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 1, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 2, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 0, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 1, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 2, 1), signerEIP155), }, }, expectedEnqueued: map[types.Address][]*types.Transaction{ addr1: { - eoa1.signTx(newTx(addr1, 10, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 11, 1), signerEIP155), - eoa1.signTx(newTx(addr1, 12, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 10, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 11, 1), signerEIP155), + eoa1.signTx(t, newTx(addr1, 12, 1), signerEIP155), }, addr2: { - eoa2.signTx(newTx(addr2, 10, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 11, 1), signerEIP155), - eoa2.signTx(newTx(addr2, 12, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 10, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 11, 1), signerEIP155), + eoa2.signTx(t, newTx(addr2, 12, 1), signerEIP155), }, addr3: { - eoa3.signTx(newTx(addr3, 10, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 11, 1), signerEIP155), - eoa3.signTx(newTx(addr3, 12, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 10, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 11, 1), signerEIP155), + eoa3.signTx(t, newTx(addr3, 12, 1), signerEIP155), }, }, }, diff --git a/validators/store/contract/contract_test.go b/validators/store/contract/contract_test.go index b7d81bb35f..92b34ee1c3 100644 --- a/validators/store/contract/contract_test.go +++ b/validators/store/contract/contract_test.go @@ -17,6 +17,7 @@ import ( "github.com/hashicorp/go-hclog" lru "github.com/hashicorp/golang-lru" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -84,7 +85,8 @@ func newTestTransition( Forks: chain.AllForksEnabled, }, st, hclog.NewNullLogger()) - rootHash := ex.WriteGenesis(nil) + rootHash, err := ex.WriteGenesis(nil) + require.NoError(t, err) ex.GetHash = func(h *types.Header) state.GetHashByNumber { return func(i uint64) types.Hash {