From cdcbd931af2641591b115df69ed33def6fb52b06 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Thu, 13 Jul 2023 13:26:04 +0300 Subject: [PATCH 1/6] updated enableEpochsHandler interface --- core/interface.go | 3 ++- core/mock/enableEpochsHandlerMock.go | 20 ------------------- core/mock/enableEpochsHandlerStub.go | 29 ++++++++++++++++++++++++++++ core/trie.go | 4 ++-- core/trie_test.go | 8 ++++---- 5 files changed, 37 insertions(+), 27 deletions(-) delete mode 100644 core/mock/enableEpochsHandlerMock.go create mode 100644 core/mock/enableEpochsHandlerStub.go diff --git a/core/interface.go b/core/interface.go index 8bde1c04..63c2daa6 100644 --- a/core/interface.go +++ b/core/interface.go @@ -144,6 +144,7 @@ type TrieNodeVersionVerifier interface { // EnableEpochsHandler defines the behavior of a component that can return if a feature is enabled or not type EnableEpochsHandler interface { - IsAutoBalanceDataTriesEnabled() bool + GetCurrentEpoch() uint32 + IsAutoBalanceDataTriesEnabledInEpoch(epoch uint32) bool IsInterfaceNil() bool } diff --git a/core/mock/enableEpochsHandlerMock.go b/core/mock/enableEpochsHandlerMock.go deleted file mode 100644 index 91abd5be..00000000 --- a/core/mock/enableEpochsHandlerMock.go +++ /dev/null @@ -1,20 +0,0 @@ -package mock - -// EnableEpochsHandlerStub - -type EnableEpochsHandlerStub struct { - IsAutoBalanceDataTriesEnabledCalled func() bool -} - -// IsAutoBalanceDataTriesEnabled - -func (e *EnableEpochsHandlerStub) IsAutoBalanceDataTriesEnabled() bool { - if e.IsAutoBalanceDataTriesEnabledCalled != nil { - return e.IsAutoBalanceDataTriesEnabledCalled() - } - - return false -} - -// IsInterfaceNil returns true if there is no value under the interface -func (e *EnableEpochsHandlerStub) IsInterfaceNil() bool { - return e == nil -} diff --git a/core/mock/enableEpochsHandlerStub.go b/core/mock/enableEpochsHandlerStub.go new file mode 100644 index 00000000..74301e48 --- /dev/null +++ b/core/mock/enableEpochsHandlerStub.go @@ -0,0 +1,29 @@ +package mock + +// EnableEpochsHandlerStub - +type EnableEpochsHandlerStub struct { + GetCurrentEpochCalled func() uint32 + IsAutoBalanceDataTriesEnabledInEpochCalled func(epoch uint32) bool +} + +// GetCurrentEpoch - +func (stub *EnableEpochsHandlerStub) GetCurrentEpoch() uint32 { + if stub.GetCurrentEpochCalled != nil { + return stub.GetCurrentEpochCalled() + } + return 0 +} + +// IsAutoBalanceDataTriesEnabledInEpoch - +func (stub *EnableEpochsHandlerStub) IsAutoBalanceDataTriesEnabledInEpoch(epoch uint32) bool { + if stub.IsAutoBalanceDataTriesEnabledInEpochCalled != nil { + return stub.IsAutoBalanceDataTriesEnabledInEpochCalled(epoch) + } + + return false +} + +// IsInterfaceNil returns true if there is no value under the interface +func (stub *EnableEpochsHandlerStub) IsInterfaceNil() bool { + return stub == nil +} diff --git a/core/trie.go b/core/trie.go index de462376..2d736a97 100644 --- a/core/trie.go +++ b/core/trie.go @@ -52,7 +52,7 @@ func NewTrieNodeVersionVerifier(enableEpochsHandler EnableEpochsHandler) (*trieN // IsValidVersion returns true if the given trie node version is valid func (vv *trieNodeVersionVerifier) IsValidVersion(version TrieNodeVersion) bool { - if vv.enableEpochsHandler.IsAutoBalanceDataTriesEnabled() { + if vv.enableEpochsHandler.IsAutoBalanceDataTriesEnabledInEpoch(vv.enableEpochsHandler.GetCurrentEpoch()) { return version <= AutoBalanceEnabled } @@ -66,7 +66,7 @@ func (vv *trieNodeVersionVerifier) IsInterfaceNil() bool { // GetVersionForNewData returns the trie node version that should be used for new data func GetVersionForNewData(handler EnableEpochsHandler) TrieNodeVersion { - if handler.IsAutoBalanceDataTriesEnabled() { + if handler.IsAutoBalanceDataTriesEnabledInEpoch(handler.GetCurrentEpoch()) { return AutoBalanceEnabled } diff --git a/core/trie_test.go b/core/trie_test.go index d5332723..506a87c7 100644 --- a/core/trie_test.go +++ b/core/trie_test.go @@ -35,7 +35,7 @@ func TestTrieNodeVersionVerifier_IsValidVersion(t *testing.T) { vv, _ := NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledCalled: func() bool { + IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { return true }, }, @@ -50,7 +50,7 @@ func TestTrieNodeVersionVerifier_IsValidVersion(t *testing.T) { vv, _ := NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledCalled: func() bool { + IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { return false }, }, @@ -77,7 +77,7 @@ func TestGetVersionForNewData(t *testing.T) { getVersionForNewData := GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledCalled: func() bool { + IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { return true }, }, @@ -90,7 +90,7 @@ func TestGetVersionForNewData(t *testing.T) { getVersionForNewData := GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledCalled: func() bool { + IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { return false }, }, From 86d4ed569364b7f0d22045027bc71db56c3d571e Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Wed, 16 Aug 2023 16:53:12 +0300 Subject: [PATCH 2/6] new approach for enable epochs handler --- core/epochFlags.go | 236 +++++++++++++++++++++++++++ core/epochFlags_test.go | 43 +++++ core/errors.go | 5 +- core/export_test.go | 29 ++++ core/interface.go | 4 +- core/loggingFunctions_test.go | 7 +- core/mock/enableEpochsHandlerStub.go | 27 +-- core/stopWatch_test.go | 45 ++--- core/trie.go | 4 +- core/trie_test.go | 51 +++--- 10 files changed, 383 insertions(+), 68 deletions(-) create mode 100644 core/epochFlags.go create mode 100644 core/epochFlags_test.go diff --git a/core/epochFlags.go b/core/epochFlags.go new file mode 100644 index 00000000..52a32ae6 --- /dev/null +++ b/core/epochFlags.go @@ -0,0 +1,236 @@ +package core + +import ( + "runtime/debug" + + "github.com/multiversx/mx-chain-core-go/core/check" +) + +// EnableEpochFlag defines a flag specific to the enableEpochs.toml +type EnableEpochFlag string + +const ( + SCDeployFlag EnableEpochFlag = "SCDeployFlag" + BuiltInFunctionsFlag EnableEpochFlag = "BuiltInFunctionsFlag" + RelayedTransactionsFlag EnableEpochFlag = "RelayedTransactionsFlag" + PenalizedTooMuchGasFlag EnableEpochFlag = "PenalizedTooMuchGasFlag" + SwitchJailWaitingFlag EnableEpochFlag = "SwitchJailWaitingFlag" + BelowSignedThresholdFlag EnableEpochFlag = "BelowSignedThresholdFlag" + SwitchHysteresisForMinNodesFlagInSpecificEpochOnly EnableEpochFlag = "SwitchHysteresisForMinNodesFlagInSpecificEpochOnly" + TransactionSignedWithTxHashFlag EnableEpochFlag = "TransactionSignedWithTxHashFlag" + MetaProtectionFlag EnableEpochFlag = "MetaProtectionFlag" + AheadOfTimeGasUsageFlag EnableEpochFlag = "AheadOfTimeGasUsageFlag" + GasPriceModifierFlag EnableEpochFlag = "GasPriceModifierFlag" + RepairCallbackFlag EnableEpochFlag = "RepairCallbackFlag" + ReturnDataToLastTransferFlagAfterEpoch EnableEpochFlag = "ReturnDataToLastTransferFlagAfterEpoch" + SenderInOutTransferFlag EnableEpochFlag = "SenderInOutTransferFlag" + StakeFlag EnableEpochFlag = "StakeFlag" + StakingV2Flag EnableEpochFlag = "StakingV2Flag" + StakingV2OwnerFlagInSpecificEpochOnly EnableEpochFlag = "StakingV2OwnerFlagInSpecificEpochOnly" + StakingV2FlagAfterEpoch EnableEpochFlag = "StakingV2FlagAfterEpoch" + DoubleKeyProtectionFlag EnableEpochFlag = "DoubleKeyProtectionFlag" + ESDTFlag EnableEpochFlag = "ESDTFlag" + ESDTFlagInSpecificEpochOnly EnableEpochFlag = "ESDTFlagInSpecificEpochOnly" + GovernanceFlag EnableEpochFlag = "GovernanceFlag" + GovernanceFlagInSpecificEpochOnly EnableEpochFlag = "GovernanceFlagInSpecificEpochOnly" + DelegationManagerFlag EnableEpochFlag = "DelegationManagerFlag" + DelegationSmartContractFlag EnableEpochFlag = "DelegationSmartContractFlag" + DelegationSmartContractFlagInSpecificEpochOnly EnableEpochFlag = "DelegationSmartContractFlagInSpecificEpochOnly" + CorrectLastUnJailedFlag EnableEpochFlag = "CorrectLastUnJailedFlag" + CorrectLastUnJailedFlagInSpecificEpochOnly EnableEpochFlag = "CorrectLastUnJailedFlagInSpecificEpochOnly" + RelayedTransactionsV2Flag EnableEpochFlag = "RelayedTransactionsV2Flag" + UnBondTokensV2Flag EnableEpochFlag = "UnBondTokensV2Flag" + SaveJailedAlwaysFlag EnableEpochFlag = "SaveJailedAlwaysFlag" + ReDelegateBelowMinCheckFlag EnableEpochFlag = "ReDelegateBelowMinCheckFlag" + ValidatorToDelegationFlag EnableEpochFlag = "ValidatorToDelegationFlag" + IncrementSCRNonceInMultiTransferFlag EnableEpochFlag = "IncrementSCRNonceInMultiTransferFlag" + ESDTMultiTransferFlag EnableEpochFlag = "ESDTMultiTransferFlag" + GlobalMintBurnFlag EnableEpochFlag = "GlobalMintBurnFlag" + ESDTTransferRoleFlag EnableEpochFlag = "ESDTTransferRoleFlag" + BuiltInFunctionOnMetaFlag EnableEpochFlag = "BuiltInFunctionOnMetaFlag" + ComputeRewardCheckpointFlag EnableEpochFlag = "ComputeRewardCheckpointFlag" + SCRSizeInvariantCheckFlag EnableEpochFlag = "SCRSizeInvariantCheckFlag" + BackwardCompSaveKeyValueFlag EnableEpochFlag = "BackwardCompSaveKeyValueFlag" + ESDTNFTCreateOnMultiShardFlag EnableEpochFlag = "ESDTNFTCreateOnMultiShardFlag" + MetaESDTSetFlag EnableEpochFlag = "MetaESDTSetFlag" + AddTokensToDelegationFlag EnableEpochFlag = "AddTokensToDelegationFlag" + MultiESDTTransferFixOnCallBackFlag EnableEpochFlag = "MultiESDTTransferFixOnCallBackFlag" + OptimizeGasUsedInCrossMiniBlocksFlag EnableEpochFlag = "OptimizeGasUsedInCrossMiniBlocksFlag" + CorrectFirstQueuedFlag EnableEpochFlag = "CorrectFirstQueuedFlag" + DeleteDelegatorAfterClaimRewardsFlag EnableEpochFlag = "DeleteDelegatorAfterClaimRewardsFlag" + RemoveNonUpdatedStorageFlag EnableEpochFlag = "RemoveNonUpdatedStorageFlag" + OptimizeNFTStoreFlag EnableEpochFlag = "OptimizeNFTStoreFlag" + CreateNFTThroughExecByCallerFlag EnableEpochFlag = "CreateNFTThroughExecByCallerFlag" + StopDecreasingValidatorRatingWhenStuckFlag EnableEpochFlag = "StopDecreasingValidatorRatingWhenStuckFlag" + FrontRunningProtectionFlag EnableEpochFlag = "FrontRunningProtectionFlag" + PayableBySCFlag EnableEpochFlag = "PayableBySCFlag" + CleanUpInformativeSCRsFlag EnableEpochFlag = "CleanUpInformativeSCRsFlag" + StorageAPICostOptimizationFlag EnableEpochFlag = "StorageAPICostOptimizationFlag" + ESDTRegisterAndSetAllRolesFlag EnableEpochFlag = "ESDTRegisterAndSetAllRolesFlag" + ScheduledMiniBlocksFlag EnableEpochFlag = "ScheduledMiniBlocksFlag" + CorrectJailedNotUnStakedEmptyQueueFlag EnableEpochFlag = "CorrectJailedNotUnStakedEmptyQueueFlag" + DoNotReturnOldBlockInBlockchainHookFlag EnableEpochFlag = "DoNotReturnOldBlockInBlockchainHookFlag" + AddFailedRelayedTxToInvalidMBsFlag EnableEpochFlag = "AddFailedRelayedTxToInvalidMBsFlag" + SCRSizeInvariantOnBuiltInResultFlag EnableEpochFlag = "SCRSizeInvariantOnBuiltInResultFlag" + CheckCorrectTokenIDForTransferRoleFlag EnableEpochFlag = "CheckCorrectTokenIDForTransferRoleFlag" + FailExecutionOnEveryAPIErrorFlag EnableEpochFlag = "FailExecutionOnEveryAPIErrorFlag" + MiniBlockPartialExecutionFlag EnableEpochFlag = "MiniBlockPartialExecutionFlag" + ManagedCryptoAPIsFlag EnableEpochFlag = "ManagedCryptoAPIsFlag" + ESDTMetadataContinuousCleanupFlag EnableEpochFlag = "ESDTMetadataContinuousCleanupFlag" + DisableExecByCallerFlag EnableEpochFlag = "DisableExecByCallerFlag" + RefactorContextFlag EnableEpochFlag = "RefactorContextFlag" + CheckFunctionArgumentFlag EnableEpochFlag = "CheckFunctionArgumentFlag" + CheckExecuteOnReadOnlyFlag EnableEpochFlag = "CheckExecuteOnReadOnlyFlag" + SetSenderInEeiOutputTransferFlag EnableEpochFlag = "SetSenderInEeiOutputTransferFlag" + FixAsyncCallbackCheckFlag EnableEpochFlag = "FixAsyncCallbackCheckFlag" + SaveToSystemAccountFlag EnableEpochFlag = "SaveToSystemAccountFlag" + CheckFrozenCollectionFlag EnableEpochFlag = "CheckFrozenCollectionFlag" + SendAlwaysFlag EnableEpochFlag = "SendAlwaysFlag" + ValueLengthCheckFlag EnableEpochFlag = "ValueLengthCheckFlag" + CheckTransferFlag EnableEpochFlag = "CheckTransferFlag" + TransferToMetaFlag EnableEpochFlag = "TransferToMetaFlag" + ESDTNFTImprovementV1Flag EnableEpochFlag = "ESDTNFTImprovementV1Flag" + ChangeDelegationOwnerFlag EnableEpochFlag = "ChangeDelegationOwnerFlag" + RefactorPeersMiniBlocksFlag EnableEpochFlag = "RefactorPeersMiniBlocksFlag" + SCProcessorV2Flag EnableEpochFlag = "SCProcessorV2Flag" + FixAsyncCallBackArgsListFlag EnableEpochFlag = "FixAsyncCallBackArgsListFlag" + FixOldTokenLiquidityFlag EnableEpochFlag = "FixOldTokenLiquidityFlag" + RuntimeMemStoreLimitFlag EnableEpochFlag = "RuntimeMemStoreLimitFlag" + RuntimeCodeSizeFixFlag EnableEpochFlag = "RuntimeCodeSizeFixFlag" + MaxBlockchainHookCountersFlag EnableEpochFlag = "MaxBlockchainHookCountersFlag" + WipeSingleNFTLiquidityDecreaseFlag EnableEpochFlag = "WipeSingleNFTLiquidityDecreaseFlag" + AlwaysSaveTokenMetaDataFlag EnableEpochFlag = "AlwaysSaveTokenMetaDataFlag" + SetGuardianFlag EnableEpochFlag = "SetGuardianFlag" + RelayedNonceFixFlag EnableEpochFlag = "RelayedNonceFixFlag" + ConsistentTokensValuesLengthCheckFlag EnableEpochFlag = "ConsistentTokensValuesLengthCheckFlag" + KeepExecOrderOnCreatedSCRsFlag EnableEpochFlag = "KeepExecOrderOnCreatedSCRsFlag" + MultiClaimOnDelegationFlag EnableEpochFlag = "MultiClaimOnDelegationFlag" + ChangeUsernameFlag EnableEpochFlag = "ChangeUsernameFlag" + AutoBalanceDataTriesFlag EnableEpochFlag = "AutoBalanceDataTriesFlag" + FixDelegationChangeOwnerOnAccountFlag EnableEpochFlag = "FixDelegationChangeOwnerOnAccountFlag" + FixOOGReturnCodeFlag EnableEpochFlag = "FixOOGReturnCodeFlag" + DeterministicSortOnValidatorsInfoFixFlag EnableEpochFlag = "DeterministicSortOnValidatorsInfoFixFlag" +) + +// CheckHandlerCompatibility checks if the provided handler is compatible with this mx-chain-core-go version +func CheckHandlerCompatibility(handler EnableEpochsHandler, logger Logger) error { + if check.IfNil(handler) { + return ErrNilEnableEpochsHandler + } + if check.IfNil(logger) { + return ErrNilLogger + } + + // allFlags slice must contain all flags defined above + allFlags := []EnableEpochFlag{ + SCDeployFlag, + BuiltInFunctionsFlag, + RelayedTransactionsFlag, + PenalizedTooMuchGasFlag, + SwitchJailWaitingFlag, + BelowSignedThresholdFlag, + SwitchHysteresisForMinNodesFlagInSpecificEpochOnly, + TransactionSignedWithTxHashFlag, + MetaProtectionFlag, + AheadOfTimeGasUsageFlag, + GasPriceModifierFlag, + RepairCallbackFlag, + ReturnDataToLastTransferFlagAfterEpoch, + SenderInOutTransferFlag, + StakeFlag, + StakingV2Flag, + StakingV2OwnerFlagInSpecificEpochOnly, + StakingV2FlagAfterEpoch, + DoubleKeyProtectionFlag, + ESDTFlag, + ESDTFlagInSpecificEpochOnly, + GovernanceFlag, + GovernanceFlagInSpecificEpochOnly, + DelegationManagerFlag, + DelegationSmartContractFlag, + DelegationSmartContractFlagInSpecificEpochOnly, + CorrectLastUnJailedFlagInSpecificEpochOnly, + CorrectLastUnJailedFlag, + RelayedTransactionsV2Flag, + UnBondTokensV2Flag, + SaveJailedAlwaysFlag, + ReDelegateBelowMinCheckFlag, + ValidatorToDelegationFlag, + IncrementSCRNonceInMultiTransferFlag, + ESDTMultiTransferFlag, + GlobalMintBurnFlag, + ESDTTransferRoleFlag, + BuiltInFunctionOnMetaFlag, + ComputeRewardCheckpointFlag, + SCRSizeInvariantCheckFlag, + BackwardCompSaveKeyValueFlag, + ESDTNFTCreateOnMultiShardFlag, + MetaESDTSetFlag, + AddTokensToDelegationFlag, + MultiESDTTransferFixOnCallBackFlag, + OptimizeGasUsedInCrossMiniBlocksFlag, + CorrectFirstQueuedFlag, + DeleteDelegatorAfterClaimRewardsFlag, + RemoveNonUpdatedStorageFlag, + OptimizeNFTStoreFlag, + CreateNFTThroughExecByCallerFlag, + StopDecreasingValidatorRatingWhenStuckFlag, + FrontRunningProtectionFlag, + PayableBySCFlag, + CleanUpInformativeSCRsFlag, + StorageAPICostOptimizationFlag, + ESDTRegisterAndSetAllRolesFlag, + ScheduledMiniBlocksFlag, + CorrectJailedNotUnStakedEmptyQueueFlag, + DoNotReturnOldBlockInBlockchainHookFlag, + AddFailedRelayedTxToInvalidMBsFlag, + SCRSizeInvariantOnBuiltInResultFlag, + CheckCorrectTokenIDForTransferRoleFlag, + FailExecutionOnEveryAPIErrorFlag, + MiniBlockPartialExecutionFlag, + ManagedCryptoAPIsFlag, + ESDTMetadataContinuousCleanupFlag, + DisableExecByCallerFlag, + RefactorContextFlag, + CheckFunctionArgumentFlag, + CheckExecuteOnReadOnlyFlag, + SetSenderInEeiOutputTransferFlag, + FixAsyncCallbackCheckFlag, + SaveToSystemAccountFlag, + CheckFrozenCollectionFlag, + SendAlwaysFlag, + ValueLengthCheckFlag, + CheckTransferFlag, + TransferToMetaFlag, + ESDTNFTImprovementV1Flag, + ChangeDelegationOwnerFlag, + RefactorPeersMiniBlocksFlag, + SCProcessorV2Flag, + FixAsyncCallBackArgsListFlag, + FixOldTokenLiquidityFlag, + RuntimeMemStoreLimitFlag, + RuntimeCodeSizeFixFlag, + MaxBlockchainHookCountersFlag, + WipeSingleNFTLiquidityDecreaseFlag, + AlwaysSaveTokenMetaDataFlag, + SetGuardianFlag, + RelayedNonceFixFlag, + ConsistentTokensValuesLengthCheckFlag, + KeepExecOrderOnCreatedSCRsFlag, + MultiClaimOnDelegationFlag, + ChangeUsernameFlag, + AutoBalanceDataTriesFlag, + FixDelegationChangeOwnerOnAccountFlag, + FixOOGReturnCodeFlag, + DeterministicSortOnValidatorsInfoFixFlag, + } + + for _, flag := range allFlags { + if !handler.IsFlagDefined(flag) { + logger.Trace("programming error, incompatible handler detected", "stack trace", string(debug.Stack())) + return ErrInvalidEnableEpochsHandler + } + } + + return nil +} diff --git a/core/epochFlags_test.go b/core/epochFlags_test.go new file mode 100644 index 00000000..c25b99b8 --- /dev/null +++ b/core/epochFlags_test.go @@ -0,0 +1,43 @@ +package core_test + +import ( + "testing" + + "github.com/multiversx/mx-chain-core-go/core" + "github.com/multiversx/mx-chain-core-go/core/mock" + "github.com/stretchr/testify/require" +) + +func TestCheckHandlerCompatibility(t *testing.T) { + t.Parallel() + + err := core.CheckHandlerCompatibility(nil, &mock.LoggerMock{}) + require.Equal(t, core.ErrNilEnableEpochsHandler, err) + + err = core.CheckHandlerCompatibility(&mock.EnableEpochsHandlerStub{}, nil) + require.Equal(t, core.ErrNilLogger, err) + + allFlagsDefinedHandler := &mock.EnableEpochsHandlerStub{ + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return true + }, + } + err = core.CheckHandlerCompatibility(allFlagsDefinedHandler, &mock.LoggerMock{}) + require.Nil(t, err) + + allFlagsUndefinedHandler := &mock.EnableEpochsHandlerStub{ + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return false + }, + } + err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler, &mock.LoggerMock{}) + require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) + + oneFlagUndefinedHandler := &mock.EnableEpochsHandlerStub{ + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag != core.SetGuardianFlag + }, + } + err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler, &mock.LoggerMock{}) + require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) +} diff --git a/core/errors.go b/core/errors.go index a6e64c49..5a784900 100644 --- a/core/errors.go +++ b/core/errors.go @@ -19,7 +19,7 @@ var ErrInvalidValue = errors.New("invalid value provided") // ErrNilInputData signals that a nil data has been provided var ErrNilInputData = errors.New("nil input data") -//ErrNilUrl signals that the provided url is empty +// ErrNilUrl signals that the provided url is empty var ErrNilUrl = errors.New("url is empty") // ErrPemFileIsInvalid signals that a pem file is invalid @@ -118,3 +118,6 @@ var ErrDBIsClosed = errors.New("DB is closed") // ErrNilEnableEpochsHandler signals that a nil enable epochs handler has been provided var ErrNilEnableEpochsHandler = errors.New("nil enable epochs handler") + +// ErrInvalidEnableEpochsHandler signals that an invalid enable epochs handler has been provided +var ErrInvalidEnableEpochsHandler = errors.New("invalid enable epochs handler") diff --git a/core/export_test.go b/core/export_test.go index a4589a38..27872f55 100644 --- a/core/export_test.go +++ b/core/export_test.go @@ -2,10 +2,39 @@ package core import "time" +// GetContainingDuration - func (sw *StopWatch) GetContainingDuration() (map[string]time.Duration, []string) { return sw.getContainingDuration() } +// GetIdentifiers - +func (sw *StopWatch) GetIdentifiers() []string { + return sw.identifiers +} + +// SetIdentifiers - +func (sw *StopWatch) SetIdentifiers(identifiers []string) { + sw.identifiers = identifiers +} + +// GetStarted - +func (sw *StopWatch) GetStarted(identifier string) (time.Time, bool) { + s, has := sw.started[identifier] + return s, has +} + +// GetElapsed - +func (sw *StopWatch) GetElapsed(identifier string) (time.Duration, bool) { + e, has := sw.elapsed[identifier] + return e, has +} + +// SetElapsed - +func (sw *StopWatch) SetElapsed(identifier string, duration time.Duration) { + sw.elapsed[identifier] = duration +} + +// SplitExponentFraction - func SplitExponentFraction(val string) (string, string) { return splitExponentFraction(val) } diff --git a/core/interface.go b/core/interface.go index 63c2daa6..1ef81ce3 100644 --- a/core/interface.go +++ b/core/interface.go @@ -144,7 +144,7 @@ type TrieNodeVersionVerifier interface { // EnableEpochsHandler defines the behavior of a component that can return if a feature is enabled or not type EnableEpochsHandler interface { - GetCurrentEpoch() uint32 - IsAutoBalanceDataTriesEnabledInEpoch(epoch uint32) bool + IsFlagDefined(flag EnableEpochFlag) bool + IsFlagEnabledInCurrentEpoch(flag EnableEpochFlag) bool IsInterfaceNil() bool } diff --git a/core/loggingFunctions_test.go b/core/loggingFunctions_test.go index 6aed20a0..30a746cd 100644 --- a/core/loggingFunctions_test.go +++ b/core/loggingFunctions_test.go @@ -1,9 +1,10 @@ -package core +package core_test import ( "fmt" "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/core/mock" "github.com/stretchr/testify/require" ) @@ -18,12 +19,12 @@ func TestDumpGoRoutinesToLogShouldNotPanic(t *testing.T) { } }() - DumpGoRoutinesToLog(0, &mock.LoggerMock{}) + core.DumpGoRoutinesToLog(0, &mock.LoggerMock{}) } func TestGetRunningGoRoutines(t *testing.T) { t.Parallel() - res := GetRunningGoRoutines(&mock.LoggerMock{}) + res := core.GetRunningGoRoutines(&mock.LoggerMock{}) require.NotNil(t, res) } diff --git a/core/mock/enableEpochsHandlerStub.go b/core/mock/enableEpochsHandlerStub.go index 74301e48..7b2232d1 100644 --- a/core/mock/enableEpochsHandlerStub.go +++ b/core/mock/enableEpochsHandlerStub.go @@ -1,29 +1,30 @@ package mock +import "github.com/multiversx/mx-chain-core-go/core" + // EnableEpochsHandlerStub - type EnableEpochsHandlerStub struct { - GetCurrentEpochCalled func() uint32 - IsAutoBalanceDataTriesEnabledInEpochCalled func(epoch uint32) bool + IsFlagDefinedCalled func(flag core.EnableEpochFlag) bool + IsFlagEnabledInCurrentEpochCalled func(flag core.EnableEpochFlag) bool } -// GetCurrentEpoch - -func (stub *EnableEpochsHandlerStub) GetCurrentEpoch() uint32 { - if stub.GetCurrentEpochCalled != nil { - return stub.GetCurrentEpochCalled() +// IsFlagDefined - +func (stub *EnableEpochsHandlerStub) IsFlagDefined(flag core.EnableEpochFlag) bool { + if stub.IsFlagDefinedCalled != nil { + return stub.IsFlagDefinedCalled(flag) } - return 0 + return false } -// IsAutoBalanceDataTriesEnabledInEpoch - -func (stub *EnableEpochsHandlerStub) IsAutoBalanceDataTriesEnabledInEpoch(epoch uint32) bool { - if stub.IsAutoBalanceDataTriesEnabledInEpochCalled != nil { - return stub.IsAutoBalanceDataTriesEnabledInEpochCalled(epoch) +// IsFlagEnabledInCurrentEpoch - +func (stub *EnableEpochsHandlerStub) IsFlagEnabledInCurrentEpoch(flag core.EnableEpochFlag) bool { + if stub.IsFlagEnabledInCurrentEpochCalled != nil { + return stub.IsFlagEnabledInCurrentEpochCalled(flag) } - return false } -// IsInterfaceNil returns true if there is no value under the interface +// IsInterfaceNil - func (stub *EnableEpochsHandlerStub) IsInterfaceNil() bool { return stub == nil } diff --git a/core/stopWatch_test.go b/core/stopWatch_test.go index 135def96..54bd1ad9 100644 --- a/core/stopWatch_test.go +++ b/core/stopWatch_test.go @@ -1,9 +1,10 @@ -package core +package core_test import ( "testing" "time" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/core/mock" "github.com/stretchr/testify/assert" ) @@ -15,20 +16,20 @@ var log = &mock.LoggerMock{} func TestStopWatch_Start(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Start(identifier) - _, has := sw.started[identifier] + _, has := sw.GetStarted(identifier) assert.True(t, has) - assert.Equal(t, identifier, sw.identifiers[0]) + assert.Equal(t, identifier, sw.GetIdentifiers()[0]) } func TestStopWatch_DoubleStartShouldNotReAddInIdentifiers(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() identifier1 := "identifier1" identifier2 := "identifier2" @@ -36,19 +37,19 @@ func TestStopWatch_DoubleStartShouldNotReAddInIdentifiers(t *testing.T) { sw.Start(identifier2) sw.Start(identifier1) - assert.Equal(t, identifier1, sw.identifiers[0]) - assert.Equal(t, identifier2, sw.identifiers[1]) - assert.Equal(t, 2, len(sw.identifiers)) + assert.Equal(t, identifier1, sw.GetIdentifiers()[0]) + assert.Equal(t, identifier2, sw.GetIdentifiers()[1]) + assert.Equal(t, 2, len(sw.GetIdentifiers())) } func TestStopWatch_StopNoStartShouldNotAddDuration(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Stop(identifier) - _, has := sw.elapsed[identifier] + _, has := sw.GetElapsed(identifier) assert.False(t, has) } @@ -56,12 +57,12 @@ func TestStopWatch_StopNoStartShouldNotAddDuration(t *testing.T) { func TestStopWatch_StopWithStartShouldAddDuration(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Start(identifier) sw.Stop(identifier) - _, has := sw.elapsed[identifier] + _, has := sw.GetElapsed(identifier) assert.True(t, has) } @@ -69,7 +70,7 @@ func TestStopWatch_StopWithStartShouldAddDuration(t *testing.T) { func TestStopWatch_GetMeasurementsNotFinishedShouldOmit(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Start(identifier) @@ -82,7 +83,7 @@ func TestStopWatch_GetMeasurementsNotFinishedShouldOmit(t *testing.T) { func TestStopWatch_GetMeasurementsShouldWork(t *testing.T) { t.Parallel() - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Start(identifier) sw.Stop(identifier) @@ -102,12 +103,12 @@ func TestStopWatch_AddShouldWork(t *testing.T) { identifier2 := "identifier2" duration2 := time.Duration(7) - swSrc := NewStopWatch() - swSrc.identifiers = []string{identifier1, identifier2} - swSrc.elapsed[identifier1] = duration1 - swSrc.elapsed[identifier2] = duration2 + swSrc := core.NewStopWatch() + swSrc.SetIdentifiers([]string{identifier1, identifier2}) + swSrc.SetElapsed(identifier1, duration1) + swSrc.SetElapsed(identifier2, duration2) - sw := NewStopWatch() + sw := core.NewStopWatch() sw.Add(swSrc) @@ -126,9 +127,9 @@ func TestStopWatch_GetMeasurement(t *testing.T) { t.Parallel() fooDuration := time.Duration(4243) * time.Millisecond - sw := NewStopWatch() - sw.identifiers = []string{"foo"} - sw.elapsed["foo"] = fooDuration + sw := core.NewStopWatch() + sw.SetIdentifiers([]string{"foo"}) + sw.SetElapsed("foo", fooDuration) assert.Equal(t, fooDuration, sw.GetMeasurement("foo")) assert.Equal(t, time.Duration(0), sw.GetMeasurement("bar")) diff --git a/core/trie.go b/core/trie.go index 2d736a97..5e52d447 100644 --- a/core/trie.go +++ b/core/trie.go @@ -52,7 +52,7 @@ func NewTrieNodeVersionVerifier(enableEpochsHandler EnableEpochsHandler) (*trieN // IsValidVersion returns true if the given trie node version is valid func (vv *trieNodeVersionVerifier) IsValidVersion(version TrieNodeVersion) bool { - if vv.enableEpochsHandler.IsAutoBalanceDataTriesEnabledInEpoch(vv.enableEpochsHandler.GetCurrentEpoch()) { + if vv.enableEpochsHandler.IsFlagEnabledInCurrentEpoch(AutoBalanceDataTriesFlag) { return version <= AutoBalanceEnabled } @@ -66,7 +66,7 @@ func (vv *trieNodeVersionVerifier) IsInterfaceNil() bool { // GetVersionForNewData returns the trie node version that should be used for new data func GetVersionForNewData(handler EnableEpochsHandler) TrieNodeVersion { - if handler.IsAutoBalanceDataTriesEnabledInEpoch(handler.GetCurrentEpoch()) { + if handler.IsFlagEnabledInCurrentEpoch(AutoBalanceDataTriesFlag) { return AutoBalanceEnabled } diff --git a/core/trie_test.go b/core/trie_test.go index 506a87c7..e35948fe 100644 --- a/core/trie_test.go +++ b/core/trie_test.go @@ -1,8 +1,9 @@ -package core +package core_test import ( "testing" + "github.com/multiversx/mx-chain-core-go/core" "github.com/multiversx/mx-chain-core-go/core/check" "github.com/multiversx/mx-chain-core-go/core/mock" "github.com/stretchr/testify/assert" @@ -14,14 +15,14 @@ func TestNewTrieNodeVersionVerifier(t *testing.T) { t.Run("nil enableEpochsHandler", func(t *testing.T) { t.Parallel() - vv, err := NewTrieNodeVersionVerifier(nil) + vv, err := core.NewTrieNodeVersionVerifier(nil) assert.Nil(t, vv) - assert.Equal(t, ErrNilEnableEpochsHandler, err) + assert.Equal(t, core.ErrNilEnableEpochsHandler, err) }) t.Run("new trieNodeVersionVerifier", func(t *testing.T) { t.Parallel() - vv, err := NewTrieNodeVersionVerifier(&mock.EnableEpochsHandlerStub{}) + vv, err := core.NewTrieNodeVersionVerifier(&mock.EnableEpochsHandlerStub{}) assert.Nil(t, err) assert.False(t, check.IfNil(vv)) }) @@ -33,40 +34,40 @@ func TestTrieNodeVersionVerifier_IsValidVersion(t *testing.T) { t.Run("auto balance enabled", func(t *testing.T) { t.Parallel() - vv, _ := NewTrieNodeVersionVerifier( + vv, _ := core.NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { - return true + IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.AutoBalanceDataTriesFlag }, }, ) - assert.True(t, vv.IsValidVersion(NotSpecified)) - assert.True(t, vv.IsValidVersion(AutoBalanceEnabled)) - assert.False(t, vv.IsValidVersion(AutoBalanceEnabled+1)) + assert.True(t, vv.IsValidVersion(core.NotSpecified)) + assert.True(t, vv.IsValidVersion(core.AutoBalanceEnabled)) + assert.False(t, vv.IsValidVersion(core.AutoBalanceEnabled+1)) }) t.Run("auto balance disabled", func(t *testing.T) { t.Parallel() - vv, _ := NewTrieNodeVersionVerifier( + vv, _ := core.NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { + IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { return false }, }, ) - assert.True(t, vv.IsValidVersion(NotSpecified)) - assert.False(t, vv.IsValidVersion(AutoBalanceEnabled)) - assert.False(t, vv.IsValidVersion(AutoBalanceEnabled+1)) + assert.True(t, vv.IsValidVersion(core.NotSpecified)) + assert.False(t, vv.IsValidVersion(core.AutoBalanceEnabled)) + assert.False(t, vv.IsValidVersion(core.AutoBalanceEnabled+1)) }) } func TestTrieNodeVersion_String(t *testing.T) { t.Parallel() - assert.Equal(t, NotSpecifiedString, NotSpecified.String()) - assert.Equal(t, AutoBalanceEnabledString, AutoBalanceEnabled.String()) - assert.Equal(t, "unknown: 100", TrieNodeVersion(100).String()) + assert.Equal(t, core.NotSpecifiedString, core.NotSpecified.String()) + assert.Equal(t, core.AutoBalanceEnabledString, core.AutoBalanceEnabled.String()) + assert.Equal(t, "unknown: 100", core.TrieNodeVersion(100).String()) } func TestGetVersionForNewData(t *testing.T) { @@ -75,26 +76,26 @@ func TestGetVersionForNewData(t *testing.T) { t.Run("auto balance enabled", func(t *testing.T) { t.Parallel() - getVersionForNewData := GetVersionForNewData( + getVersionForNewData := core.GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { - return true + IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.AutoBalanceDataTriesFlag }, }, ) - assert.Equal(t, AutoBalanceEnabled, getVersionForNewData) + assert.Equal(t, core.AutoBalanceEnabled, getVersionForNewData) }) t.Run("auto balance disabled", func(t *testing.T) { t.Parallel() - getVersionForNewData := GetVersionForNewData( + getVersionForNewData := core.GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsAutoBalanceDataTriesEnabledInEpochCalled: func(_ uint32) bool { + IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { return false }, }, ) - assert.Equal(t, NotSpecified, getVersionForNewData) + assert.Equal(t, core.NotSpecified, getVersionForNewData) }) } From 1ef94e09602cac79c6217d3b8a39605440cc8de1 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Wed, 16 Aug 2023 18:14:00 +0300 Subject: [PATCH 3/6] removed logger from CheckHandlerCompatibility --- core/epochFlags.go | 8 +------- core/epochFlags_test.go | 11 ++++------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/core/epochFlags.go b/core/epochFlags.go index 52a32ae6..77b33606 100644 --- a/core/epochFlags.go +++ b/core/epochFlags.go @@ -1,8 +1,6 @@ package core import ( - "runtime/debug" - "github.com/multiversx/mx-chain-core-go/core/check" ) @@ -113,13 +111,10 @@ const ( ) // CheckHandlerCompatibility checks if the provided handler is compatible with this mx-chain-core-go version -func CheckHandlerCompatibility(handler EnableEpochsHandler, logger Logger) error { +func CheckHandlerCompatibility(handler EnableEpochsHandler) error { if check.IfNil(handler) { return ErrNilEnableEpochsHandler } - if check.IfNil(logger) { - return ErrNilLogger - } // allFlags slice must contain all flags defined above allFlags := []EnableEpochFlag{ @@ -227,7 +222,6 @@ func CheckHandlerCompatibility(handler EnableEpochsHandler, logger Logger) error for _, flag := range allFlags { if !handler.IsFlagDefined(flag) { - logger.Trace("programming error, incompatible handler detected", "stack trace", string(debug.Stack())) return ErrInvalidEnableEpochsHandler } } diff --git a/core/epochFlags_test.go b/core/epochFlags_test.go index c25b99b8..bb92894b 100644 --- a/core/epochFlags_test.go +++ b/core/epochFlags_test.go @@ -11,18 +11,15 @@ import ( func TestCheckHandlerCompatibility(t *testing.T) { t.Parallel() - err := core.CheckHandlerCompatibility(nil, &mock.LoggerMock{}) + err := core.CheckHandlerCompatibility(nil) require.Equal(t, core.ErrNilEnableEpochsHandler, err) - err = core.CheckHandlerCompatibility(&mock.EnableEpochsHandlerStub{}, nil) - require.Equal(t, core.ErrNilLogger, err) - allFlagsDefinedHandler := &mock.EnableEpochsHandlerStub{ IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { return true }, } - err = core.CheckHandlerCompatibility(allFlagsDefinedHandler, &mock.LoggerMock{}) + err = core.CheckHandlerCompatibility(allFlagsDefinedHandler) require.Nil(t, err) allFlagsUndefinedHandler := &mock.EnableEpochsHandlerStub{ @@ -30,7 +27,7 @@ func TestCheckHandlerCompatibility(t *testing.T) { return false }, } - err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler, &mock.LoggerMock{}) + err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler) require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) oneFlagUndefinedHandler := &mock.EnableEpochsHandlerStub{ @@ -38,6 +35,6 @@ func TestCheckHandlerCompatibility(t *testing.T) { return flag != core.SetGuardianFlag }, } - err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler, &mock.LoggerMock{}) + err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler) require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) } From 32932af4146d7125500852206652e6a155ecc608 Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Fri, 18 Aug 2023 16:51:12 +0300 Subject: [PATCH 4/6] fixes after review --- core/epochFlags.go | 212 ++++++++++++++------------- core/epochFlags_test.go | 7 +- core/interface.go | 2 + core/mock/enableEpochsHandlerStub.go | 18 +++ 4 files changed, 132 insertions(+), 107 deletions(-) diff --git a/core/epochFlags.go b/core/epochFlags.go index 77b33606..0c5d2d65 100644 --- a/core/epochFlags.go +++ b/core/epochFlags.go @@ -1,6 +1,8 @@ package core import ( + "fmt" + "github.com/multiversx/mx-chain-core-go/core/check" ) @@ -110,119 +112,119 @@ const ( DeterministicSortOnValidatorsInfoFixFlag EnableEpochFlag = "DeterministicSortOnValidatorsInfoFixFlag" ) +// allFlags slice must contain all flags defined above +var allFlags = []EnableEpochFlag{ + SCDeployFlag, + BuiltInFunctionsFlag, + RelayedTransactionsFlag, + PenalizedTooMuchGasFlag, + SwitchJailWaitingFlag, + BelowSignedThresholdFlag, + SwitchHysteresisForMinNodesFlagInSpecificEpochOnly, + TransactionSignedWithTxHashFlag, + MetaProtectionFlag, + AheadOfTimeGasUsageFlag, + GasPriceModifierFlag, + RepairCallbackFlag, + ReturnDataToLastTransferFlagAfterEpoch, + SenderInOutTransferFlag, + StakeFlag, + StakingV2Flag, + StakingV2OwnerFlagInSpecificEpochOnly, + StakingV2FlagAfterEpoch, + DoubleKeyProtectionFlag, + ESDTFlag, + ESDTFlagInSpecificEpochOnly, + GovernanceFlag, + GovernanceFlagInSpecificEpochOnly, + DelegationManagerFlag, + DelegationSmartContractFlag, + DelegationSmartContractFlagInSpecificEpochOnly, + CorrectLastUnJailedFlagInSpecificEpochOnly, + CorrectLastUnJailedFlag, + RelayedTransactionsV2Flag, + UnBondTokensV2Flag, + SaveJailedAlwaysFlag, + ReDelegateBelowMinCheckFlag, + ValidatorToDelegationFlag, + IncrementSCRNonceInMultiTransferFlag, + ESDTMultiTransferFlag, + GlobalMintBurnFlag, + ESDTTransferRoleFlag, + BuiltInFunctionOnMetaFlag, + ComputeRewardCheckpointFlag, + SCRSizeInvariantCheckFlag, + BackwardCompSaveKeyValueFlag, + ESDTNFTCreateOnMultiShardFlag, + MetaESDTSetFlag, + AddTokensToDelegationFlag, + MultiESDTTransferFixOnCallBackFlag, + OptimizeGasUsedInCrossMiniBlocksFlag, + CorrectFirstQueuedFlag, + DeleteDelegatorAfterClaimRewardsFlag, + RemoveNonUpdatedStorageFlag, + OptimizeNFTStoreFlag, + CreateNFTThroughExecByCallerFlag, + StopDecreasingValidatorRatingWhenStuckFlag, + FrontRunningProtectionFlag, + PayableBySCFlag, + CleanUpInformativeSCRsFlag, + StorageAPICostOptimizationFlag, + ESDTRegisterAndSetAllRolesFlag, + ScheduledMiniBlocksFlag, + CorrectJailedNotUnStakedEmptyQueueFlag, + DoNotReturnOldBlockInBlockchainHookFlag, + AddFailedRelayedTxToInvalidMBsFlag, + SCRSizeInvariantOnBuiltInResultFlag, + CheckCorrectTokenIDForTransferRoleFlag, + FailExecutionOnEveryAPIErrorFlag, + MiniBlockPartialExecutionFlag, + ManagedCryptoAPIsFlag, + ESDTMetadataContinuousCleanupFlag, + DisableExecByCallerFlag, + RefactorContextFlag, + CheckFunctionArgumentFlag, + CheckExecuteOnReadOnlyFlag, + SetSenderInEeiOutputTransferFlag, + FixAsyncCallbackCheckFlag, + SaveToSystemAccountFlag, + CheckFrozenCollectionFlag, + SendAlwaysFlag, + ValueLengthCheckFlag, + CheckTransferFlag, + TransferToMetaFlag, + ESDTNFTImprovementV1Flag, + ChangeDelegationOwnerFlag, + RefactorPeersMiniBlocksFlag, + SCProcessorV2Flag, + FixAsyncCallBackArgsListFlag, + FixOldTokenLiquidityFlag, + RuntimeMemStoreLimitFlag, + RuntimeCodeSizeFixFlag, + MaxBlockchainHookCountersFlag, + WipeSingleNFTLiquidityDecreaseFlag, + AlwaysSaveTokenMetaDataFlag, + SetGuardianFlag, + RelayedNonceFixFlag, + ConsistentTokensValuesLengthCheckFlag, + KeepExecOrderOnCreatedSCRsFlag, + MultiClaimOnDelegationFlag, + ChangeUsernameFlag, + AutoBalanceDataTriesFlag, + FixDelegationChangeOwnerOnAccountFlag, + FixOOGReturnCodeFlag, + DeterministicSortOnValidatorsInfoFixFlag, +} + // CheckHandlerCompatibility checks if the provided handler is compatible with this mx-chain-core-go version func CheckHandlerCompatibility(handler EnableEpochsHandler) error { if check.IfNil(handler) { return ErrNilEnableEpochsHandler } - // allFlags slice must contain all flags defined above - allFlags := []EnableEpochFlag{ - SCDeployFlag, - BuiltInFunctionsFlag, - RelayedTransactionsFlag, - PenalizedTooMuchGasFlag, - SwitchJailWaitingFlag, - BelowSignedThresholdFlag, - SwitchHysteresisForMinNodesFlagInSpecificEpochOnly, - TransactionSignedWithTxHashFlag, - MetaProtectionFlag, - AheadOfTimeGasUsageFlag, - GasPriceModifierFlag, - RepairCallbackFlag, - ReturnDataToLastTransferFlagAfterEpoch, - SenderInOutTransferFlag, - StakeFlag, - StakingV2Flag, - StakingV2OwnerFlagInSpecificEpochOnly, - StakingV2FlagAfterEpoch, - DoubleKeyProtectionFlag, - ESDTFlag, - ESDTFlagInSpecificEpochOnly, - GovernanceFlag, - GovernanceFlagInSpecificEpochOnly, - DelegationManagerFlag, - DelegationSmartContractFlag, - DelegationSmartContractFlagInSpecificEpochOnly, - CorrectLastUnJailedFlagInSpecificEpochOnly, - CorrectLastUnJailedFlag, - RelayedTransactionsV2Flag, - UnBondTokensV2Flag, - SaveJailedAlwaysFlag, - ReDelegateBelowMinCheckFlag, - ValidatorToDelegationFlag, - IncrementSCRNonceInMultiTransferFlag, - ESDTMultiTransferFlag, - GlobalMintBurnFlag, - ESDTTransferRoleFlag, - BuiltInFunctionOnMetaFlag, - ComputeRewardCheckpointFlag, - SCRSizeInvariantCheckFlag, - BackwardCompSaveKeyValueFlag, - ESDTNFTCreateOnMultiShardFlag, - MetaESDTSetFlag, - AddTokensToDelegationFlag, - MultiESDTTransferFixOnCallBackFlag, - OptimizeGasUsedInCrossMiniBlocksFlag, - CorrectFirstQueuedFlag, - DeleteDelegatorAfterClaimRewardsFlag, - RemoveNonUpdatedStorageFlag, - OptimizeNFTStoreFlag, - CreateNFTThroughExecByCallerFlag, - StopDecreasingValidatorRatingWhenStuckFlag, - FrontRunningProtectionFlag, - PayableBySCFlag, - CleanUpInformativeSCRsFlag, - StorageAPICostOptimizationFlag, - ESDTRegisterAndSetAllRolesFlag, - ScheduledMiniBlocksFlag, - CorrectJailedNotUnStakedEmptyQueueFlag, - DoNotReturnOldBlockInBlockchainHookFlag, - AddFailedRelayedTxToInvalidMBsFlag, - SCRSizeInvariantOnBuiltInResultFlag, - CheckCorrectTokenIDForTransferRoleFlag, - FailExecutionOnEveryAPIErrorFlag, - MiniBlockPartialExecutionFlag, - ManagedCryptoAPIsFlag, - ESDTMetadataContinuousCleanupFlag, - DisableExecByCallerFlag, - RefactorContextFlag, - CheckFunctionArgumentFlag, - CheckExecuteOnReadOnlyFlag, - SetSenderInEeiOutputTransferFlag, - FixAsyncCallbackCheckFlag, - SaveToSystemAccountFlag, - CheckFrozenCollectionFlag, - SendAlwaysFlag, - ValueLengthCheckFlag, - CheckTransferFlag, - TransferToMetaFlag, - ESDTNFTImprovementV1Flag, - ChangeDelegationOwnerFlag, - RefactorPeersMiniBlocksFlag, - SCProcessorV2Flag, - FixAsyncCallBackArgsListFlag, - FixOldTokenLiquidityFlag, - RuntimeMemStoreLimitFlag, - RuntimeCodeSizeFixFlag, - MaxBlockchainHookCountersFlag, - WipeSingleNFTLiquidityDecreaseFlag, - AlwaysSaveTokenMetaDataFlag, - SetGuardianFlag, - RelayedNonceFixFlag, - ConsistentTokensValuesLengthCheckFlag, - KeepExecOrderOnCreatedSCRsFlag, - MultiClaimOnDelegationFlag, - ChangeUsernameFlag, - AutoBalanceDataTriesFlag, - FixDelegationChangeOwnerOnAccountFlag, - FixOOGReturnCodeFlag, - DeterministicSortOnValidatorsInfoFixFlag, - } - for _, flag := range allFlags { if !handler.IsFlagDefined(flag) { - return ErrInvalidEnableEpochsHandler + return fmt.Errorf("%w for flag %s", ErrInvalidEnableEpochsHandler, flag) } } diff --git a/core/epochFlags_test.go b/core/epochFlags_test.go index bb92894b..8d57ab28 100644 --- a/core/epochFlags_test.go +++ b/core/epochFlags_test.go @@ -1,6 +1,8 @@ package core_test import ( + "errors" + "strings" "testing" "github.com/multiversx/mx-chain-core-go/core" @@ -28,7 +30,7 @@ func TestCheckHandlerCompatibility(t *testing.T) { }, } err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler) - require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) + require.True(t, errors.Is(err, core.ErrInvalidEnableEpochsHandler)) oneFlagUndefinedHandler := &mock.EnableEpochsHandlerStub{ IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { @@ -36,5 +38,6 @@ func TestCheckHandlerCompatibility(t *testing.T) { }, } err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler) - require.Equal(t, core.ErrInvalidEnableEpochsHandler, err) + require.True(t, errors.Is(err, core.ErrInvalidEnableEpochsHandler)) + require.True(t, strings.Contains(err.Error(), string(core.SetGuardianFlag))) } diff --git a/core/interface.go b/core/interface.go index 1ef81ce3..0a734fc5 100644 --- a/core/interface.go +++ b/core/interface.go @@ -146,5 +146,7 @@ type TrieNodeVersionVerifier interface { type EnableEpochsHandler interface { IsFlagDefined(flag EnableEpochFlag) bool IsFlagEnabledInCurrentEpoch(flag EnableEpochFlag) bool + IsFlagEnabledInEpoch(flag EnableEpochFlag, epoch uint32) bool + GetActivationEpoch(flag EnableEpochFlag) uint32 IsInterfaceNil() bool } diff --git a/core/mock/enableEpochsHandlerStub.go b/core/mock/enableEpochsHandlerStub.go index 7b2232d1..177f3311 100644 --- a/core/mock/enableEpochsHandlerStub.go +++ b/core/mock/enableEpochsHandlerStub.go @@ -6,6 +6,8 @@ import "github.com/multiversx/mx-chain-core-go/core" type EnableEpochsHandlerStub struct { IsFlagDefinedCalled func(flag core.EnableEpochFlag) bool IsFlagEnabledInCurrentEpochCalled func(flag core.EnableEpochFlag) bool + IsFlagEnabledInEpochCalled func(flag core.EnableEpochFlag, epoch uint32) bool + GetActivationEpochCalled func(flag core.EnableEpochFlag) uint32 } // IsFlagDefined - @@ -24,6 +26,22 @@ func (stub *EnableEpochsHandlerStub) IsFlagEnabledInCurrentEpoch(flag core.Enabl return false } +// IsFlagEnabledInEpoch - +func (stub *EnableEpochsHandlerStub) IsFlagEnabledInEpoch(flag core.EnableEpochFlag, epoch uint32) bool { + if stub.IsFlagEnabledInEpochCalled != nil { + return stub.IsFlagEnabledInEpochCalled(flag, epoch) + } + return false +} + +// GetActivationEpoch - +func (stub *EnableEpochsHandlerStub) GetActivationEpoch(flag core.EnableEpochFlag) uint32 { + if stub.GetActivationEpochCalled != nil { + return stub.GetActivationEpochCalled(flag) + } + return 0 +} + // IsInterfaceNil - func (stub *EnableEpochsHandlerStub) IsInterfaceNil() bool { return stub == nil From 2cc1b40f815c94239df140700e713260d30af5db Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Aug 2023 11:36:18 +0300 Subject: [PATCH 5/6] fixes after review + removed all constants + fixed linter issue as per go 1.20 --- core/epochFlags.go | 211 +-------------------------- core/epochFlags_test.go | 14 +- core/export_test.go | 3 + core/file.go | 6 +- core/file_test.go | 3 +- core/interface.go | 2 +- core/mock/enableEpochsHandlerStub.go | 16 +- core/trie.go | 11 +- core/trie_test.go | 45 +++++- data/outport/common_test.go | 2 +- data/transaction/transaction_test.go | 2 +- 11 files changed, 75 insertions(+), 240 deletions(-) diff --git a/core/epochFlags.go b/core/epochFlags.go index 0c5d2d65..8a43202e 100644 --- a/core/epochFlags.go +++ b/core/epochFlags.go @@ -9,220 +9,13 @@ import ( // EnableEpochFlag defines a flag specific to the enableEpochs.toml type EnableEpochFlag string -const ( - SCDeployFlag EnableEpochFlag = "SCDeployFlag" - BuiltInFunctionsFlag EnableEpochFlag = "BuiltInFunctionsFlag" - RelayedTransactionsFlag EnableEpochFlag = "RelayedTransactionsFlag" - PenalizedTooMuchGasFlag EnableEpochFlag = "PenalizedTooMuchGasFlag" - SwitchJailWaitingFlag EnableEpochFlag = "SwitchJailWaitingFlag" - BelowSignedThresholdFlag EnableEpochFlag = "BelowSignedThresholdFlag" - SwitchHysteresisForMinNodesFlagInSpecificEpochOnly EnableEpochFlag = "SwitchHysteresisForMinNodesFlagInSpecificEpochOnly" - TransactionSignedWithTxHashFlag EnableEpochFlag = "TransactionSignedWithTxHashFlag" - MetaProtectionFlag EnableEpochFlag = "MetaProtectionFlag" - AheadOfTimeGasUsageFlag EnableEpochFlag = "AheadOfTimeGasUsageFlag" - GasPriceModifierFlag EnableEpochFlag = "GasPriceModifierFlag" - RepairCallbackFlag EnableEpochFlag = "RepairCallbackFlag" - ReturnDataToLastTransferFlagAfterEpoch EnableEpochFlag = "ReturnDataToLastTransferFlagAfterEpoch" - SenderInOutTransferFlag EnableEpochFlag = "SenderInOutTransferFlag" - StakeFlag EnableEpochFlag = "StakeFlag" - StakingV2Flag EnableEpochFlag = "StakingV2Flag" - StakingV2OwnerFlagInSpecificEpochOnly EnableEpochFlag = "StakingV2OwnerFlagInSpecificEpochOnly" - StakingV2FlagAfterEpoch EnableEpochFlag = "StakingV2FlagAfterEpoch" - DoubleKeyProtectionFlag EnableEpochFlag = "DoubleKeyProtectionFlag" - ESDTFlag EnableEpochFlag = "ESDTFlag" - ESDTFlagInSpecificEpochOnly EnableEpochFlag = "ESDTFlagInSpecificEpochOnly" - GovernanceFlag EnableEpochFlag = "GovernanceFlag" - GovernanceFlagInSpecificEpochOnly EnableEpochFlag = "GovernanceFlagInSpecificEpochOnly" - DelegationManagerFlag EnableEpochFlag = "DelegationManagerFlag" - DelegationSmartContractFlag EnableEpochFlag = "DelegationSmartContractFlag" - DelegationSmartContractFlagInSpecificEpochOnly EnableEpochFlag = "DelegationSmartContractFlagInSpecificEpochOnly" - CorrectLastUnJailedFlag EnableEpochFlag = "CorrectLastUnJailedFlag" - CorrectLastUnJailedFlagInSpecificEpochOnly EnableEpochFlag = "CorrectLastUnJailedFlagInSpecificEpochOnly" - RelayedTransactionsV2Flag EnableEpochFlag = "RelayedTransactionsV2Flag" - UnBondTokensV2Flag EnableEpochFlag = "UnBondTokensV2Flag" - SaveJailedAlwaysFlag EnableEpochFlag = "SaveJailedAlwaysFlag" - ReDelegateBelowMinCheckFlag EnableEpochFlag = "ReDelegateBelowMinCheckFlag" - ValidatorToDelegationFlag EnableEpochFlag = "ValidatorToDelegationFlag" - IncrementSCRNonceInMultiTransferFlag EnableEpochFlag = "IncrementSCRNonceInMultiTransferFlag" - ESDTMultiTransferFlag EnableEpochFlag = "ESDTMultiTransferFlag" - GlobalMintBurnFlag EnableEpochFlag = "GlobalMintBurnFlag" - ESDTTransferRoleFlag EnableEpochFlag = "ESDTTransferRoleFlag" - BuiltInFunctionOnMetaFlag EnableEpochFlag = "BuiltInFunctionOnMetaFlag" - ComputeRewardCheckpointFlag EnableEpochFlag = "ComputeRewardCheckpointFlag" - SCRSizeInvariantCheckFlag EnableEpochFlag = "SCRSizeInvariantCheckFlag" - BackwardCompSaveKeyValueFlag EnableEpochFlag = "BackwardCompSaveKeyValueFlag" - ESDTNFTCreateOnMultiShardFlag EnableEpochFlag = "ESDTNFTCreateOnMultiShardFlag" - MetaESDTSetFlag EnableEpochFlag = "MetaESDTSetFlag" - AddTokensToDelegationFlag EnableEpochFlag = "AddTokensToDelegationFlag" - MultiESDTTransferFixOnCallBackFlag EnableEpochFlag = "MultiESDTTransferFixOnCallBackFlag" - OptimizeGasUsedInCrossMiniBlocksFlag EnableEpochFlag = "OptimizeGasUsedInCrossMiniBlocksFlag" - CorrectFirstQueuedFlag EnableEpochFlag = "CorrectFirstQueuedFlag" - DeleteDelegatorAfterClaimRewardsFlag EnableEpochFlag = "DeleteDelegatorAfterClaimRewardsFlag" - RemoveNonUpdatedStorageFlag EnableEpochFlag = "RemoveNonUpdatedStorageFlag" - OptimizeNFTStoreFlag EnableEpochFlag = "OptimizeNFTStoreFlag" - CreateNFTThroughExecByCallerFlag EnableEpochFlag = "CreateNFTThroughExecByCallerFlag" - StopDecreasingValidatorRatingWhenStuckFlag EnableEpochFlag = "StopDecreasingValidatorRatingWhenStuckFlag" - FrontRunningProtectionFlag EnableEpochFlag = "FrontRunningProtectionFlag" - PayableBySCFlag EnableEpochFlag = "PayableBySCFlag" - CleanUpInformativeSCRsFlag EnableEpochFlag = "CleanUpInformativeSCRsFlag" - StorageAPICostOptimizationFlag EnableEpochFlag = "StorageAPICostOptimizationFlag" - ESDTRegisterAndSetAllRolesFlag EnableEpochFlag = "ESDTRegisterAndSetAllRolesFlag" - ScheduledMiniBlocksFlag EnableEpochFlag = "ScheduledMiniBlocksFlag" - CorrectJailedNotUnStakedEmptyQueueFlag EnableEpochFlag = "CorrectJailedNotUnStakedEmptyQueueFlag" - DoNotReturnOldBlockInBlockchainHookFlag EnableEpochFlag = "DoNotReturnOldBlockInBlockchainHookFlag" - AddFailedRelayedTxToInvalidMBsFlag EnableEpochFlag = "AddFailedRelayedTxToInvalidMBsFlag" - SCRSizeInvariantOnBuiltInResultFlag EnableEpochFlag = "SCRSizeInvariantOnBuiltInResultFlag" - CheckCorrectTokenIDForTransferRoleFlag EnableEpochFlag = "CheckCorrectTokenIDForTransferRoleFlag" - FailExecutionOnEveryAPIErrorFlag EnableEpochFlag = "FailExecutionOnEveryAPIErrorFlag" - MiniBlockPartialExecutionFlag EnableEpochFlag = "MiniBlockPartialExecutionFlag" - ManagedCryptoAPIsFlag EnableEpochFlag = "ManagedCryptoAPIsFlag" - ESDTMetadataContinuousCleanupFlag EnableEpochFlag = "ESDTMetadataContinuousCleanupFlag" - DisableExecByCallerFlag EnableEpochFlag = "DisableExecByCallerFlag" - RefactorContextFlag EnableEpochFlag = "RefactorContextFlag" - CheckFunctionArgumentFlag EnableEpochFlag = "CheckFunctionArgumentFlag" - CheckExecuteOnReadOnlyFlag EnableEpochFlag = "CheckExecuteOnReadOnlyFlag" - SetSenderInEeiOutputTransferFlag EnableEpochFlag = "SetSenderInEeiOutputTransferFlag" - FixAsyncCallbackCheckFlag EnableEpochFlag = "FixAsyncCallbackCheckFlag" - SaveToSystemAccountFlag EnableEpochFlag = "SaveToSystemAccountFlag" - CheckFrozenCollectionFlag EnableEpochFlag = "CheckFrozenCollectionFlag" - SendAlwaysFlag EnableEpochFlag = "SendAlwaysFlag" - ValueLengthCheckFlag EnableEpochFlag = "ValueLengthCheckFlag" - CheckTransferFlag EnableEpochFlag = "CheckTransferFlag" - TransferToMetaFlag EnableEpochFlag = "TransferToMetaFlag" - ESDTNFTImprovementV1Flag EnableEpochFlag = "ESDTNFTImprovementV1Flag" - ChangeDelegationOwnerFlag EnableEpochFlag = "ChangeDelegationOwnerFlag" - RefactorPeersMiniBlocksFlag EnableEpochFlag = "RefactorPeersMiniBlocksFlag" - SCProcessorV2Flag EnableEpochFlag = "SCProcessorV2Flag" - FixAsyncCallBackArgsListFlag EnableEpochFlag = "FixAsyncCallBackArgsListFlag" - FixOldTokenLiquidityFlag EnableEpochFlag = "FixOldTokenLiquidityFlag" - RuntimeMemStoreLimitFlag EnableEpochFlag = "RuntimeMemStoreLimitFlag" - RuntimeCodeSizeFixFlag EnableEpochFlag = "RuntimeCodeSizeFixFlag" - MaxBlockchainHookCountersFlag EnableEpochFlag = "MaxBlockchainHookCountersFlag" - WipeSingleNFTLiquidityDecreaseFlag EnableEpochFlag = "WipeSingleNFTLiquidityDecreaseFlag" - AlwaysSaveTokenMetaDataFlag EnableEpochFlag = "AlwaysSaveTokenMetaDataFlag" - SetGuardianFlag EnableEpochFlag = "SetGuardianFlag" - RelayedNonceFixFlag EnableEpochFlag = "RelayedNonceFixFlag" - ConsistentTokensValuesLengthCheckFlag EnableEpochFlag = "ConsistentTokensValuesLengthCheckFlag" - KeepExecOrderOnCreatedSCRsFlag EnableEpochFlag = "KeepExecOrderOnCreatedSCRsFlag" - MultiClaimOnDelegationFlag EnableEpochFlag = "MultiClaimOnDelegationFlag" - ChangeUsernameFlag EnableEpochFlag = "ChangeUsernameFlag" - AutoBalanceDataTriesFlag EnableEpochFlag = "AutoBalanceDataTriesFlag" - FixDelegationChangeOwnerOnAccountFlag EnableEpochFlag = "FixDelegationChangeOwnerOnAccountFlag" - FixOOGReturnCodeFlag EnableEpochFlag = "FixOOGReturnCodeFlag" - DeterministicSortOnValidatorsInfoFixFlag EnableEpochFlag = "DeterministicSortOnValidatorsInfoFixFlag" -) - -// allFlags slice must contain all flags defined above -var allFlags = []EnableEpochFlag{ - SCDeployFlag, - BuiltInFunctionsFlag, - RelayedTransactionsFlag, - PenalizedTooMuchGasFlag, - SwitchJailWaitingFlag, - BelowSignedThresholdFlag, - SwitchHysteresisForMinNodesFlagInSpecificEpochOnly, - TransactionSignedWithTxHashFlag, - MetaProtectionFlag, - AheadOfTimeGasUsageFlag, - GasPriceModifierFlag, - RepairCallbackFlag, - ReturnDataToLastTransferFlagAfterEpoch, - SenderInOutTransferFlag, - StakeFlag, - StakingV2Flag, - StakingV2OwnerFlagInSpecificEpochOnly, - StakingV2FlagAfterEpoch, - DoubleKeyProtectionFlag, - ESDTFlag, - ESDTFlagInSpecificEpochOnly, - GovernanceFlag, - GovernanceFlagInSpecificEpochOnly, - DelegationManagerFlag, - DelegationSmartContractFlag, - DelegationSmartContractFlagInSpecificEpochOnly, - CorrectLastUnJailedFlagInSpecificEpochOnly, - CorrectLastUnJailedFlag, - RelayedTransactionsV2Flag, - UnBondTokensV2Flag, - SaveJailedAlwaysFlag, - ReDelegateBelowMinCheckFlag, - ValidatorToDelegationFlag, - IncrementSCRNonceInMultiTransferFlag, - ESDTMultiTransferFlag, - GlobalMintBurnFlag, - ESDTTransferRoleFlag, - BuiltInFunctionOnMetaFlag, - ComputeRewardCheckpointFlag, - SCRSizeInvariantCheckFlag, - BackwardCompSaveKeyValueFlag, - ESDTNFTCreateOnMultiShardFlag, - MetaESDTSetFlag, - AddTokensToDelegationFlag, - MultiESDTTransferFixOnCallBackFlag, - OptimizeGasUsedInCrossMiniBlocksFlag, - CorrectFirstQueuedFlag, - DeleteDelegatorAfterClaimRewardsFlag, - RemoveNonUpdatedStorageFlag, - OptimizeNFTStoreFlag, - CreateNFTThroughExecByCallerFlag, - StopDecreasingValidatorRatingWhenStuckFlag, - FrontRunningProtectionFlag, - PayableBySCFlag, - CleanUpInformativeSCRsFlag, - StorageAPICostOptimizationFlag, - ESDTRegisterAndSetAllRolesFlag, - ScheduledMiniBlocksFlag, - CorrectJailedNotUnStakedEmptyQueueFlag, - DoNotReturnOldBlockInBlockchainHookFlag, - AddFailedRelayedTxToInvalidMBsFlag, - SCRSizeInvariantOnBuiltInResultFlag, - CheckCorrectTokenIDForTransferRoleFlag, - FailExecutionOnEveryAPIErrorFlag, - MiniBlockPartialExecutionFlag, - ManagedCryptoAPIsFlag, - ESDTMetadataContinuousCleanupFlag, - DisableExecByCallerFlag, - RefactorContextFlag, - CheckFunctionArgumentFlag, - CheckExecuteOnReadOnlyFlag, - SetSenderInEeiOutputTransferFlag, - FixAsyncCallbackCheckFlag, - SaveToSystemAccountFlag, - CheckFrozenCollectionFlag, - SendAlwaysFlag, - ValueLengthCheckFlag, - CheckTransferFlag, - TransferToMetaFlag, - ESDTNFTImprovementV1Flag, - ChangeDelegationOwnerFlag, - RefactorPeersMiniBlocksFlag, - SCProcessorV2Flag, - FixAsyncCallBackArgsListFlag, - FixOldTokenLiquidityFlag, - RuntimeMemStoreLimitFlag, - RuntimeCodeSizeFixFlag, - MaxBlockchainHookCountersFlag, - WipeSingleNFTLiquidityDecreaseFlag, - AlwaysSaveTokenMetaDataFlag, - SetGuardianFlag, - RelayedNonceFixFlag, - ConsistentTokensValuesLengthCheckFlag, - KeepExecOrderOnCreatedSCRsFlag, - MultiClaimOnDelegationFlag, - ChangeUsernameFlag, - AutoBalanceDataTriesFlag, - FixDelegationChangeOwnerOnAccountFlag, - FixOOGReturnCodeFlag, - DeterministicSortOnValidatorsInfoFixFlag, -} - // CheckHandlerCompatibility checks if the provided handler is compatible with this mx-chain-core-go version -func CheckHandlerCompatibility(handler EnableEpochsHandler) error { +func CheckHandlerCompatibility(handler EnableEpochsHandler, requiredFlags []EnableEpochFlag) error { if check.IfNil(handler) { return ErrNilEnableEpochsHandler } - for _, flag := range allFlags { + for _, flag := range requiredFlags { if !handler.IsFlagDefined(flag) { return fmt.Errorf("%w for flag %s", ErrInvalidEnableEpochsHandler, flag) } diff --git a/core/epochFlags_test.go b/core/epochFlags_test.go index 8d57ab28..6a702fc9 100644 --- a/core/epochFlags_test.go +++ b/core/epochFlags_test.go @@ -13,15 +13,16 @@ import ( func TestCheckHandlerCompatibility(t *testing.T) { t.Parallel() - err := core.CheckHandlerCompatibility(nil) + err := core.CheckHandlerCompatibility(nil, []core.EnableEpochFlag{}) require.Equal(t, core.ErrNilEnableEpochsHandler, err) + testFlags := []core.EnableEpochFlag{"f0", "f1", "f2"} allFlagsDefinedHandler := &mock.EnableEpochsHandlerStub{ IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { return true }, } - err = core.CheckHandlerCompatibility(allFlagsDefinedHandler) + err = core.CheckHandlerCompatibility(allFlagsDefinedHandler, testFlags) require.Nil(t, err) allFlagsUndefinedHandler := &mock.EnableEpochsHandlerStub{ @@ -29,15 +30,16 @@ func TestCheckHandlerCompatibility(t *testing.T) { return false }, } - err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler) + err = core.CheckHandlerCompatibility(allFlagsUndefinedHandler, testFlags) require.True(t, errors.Is(err, core.ErrInvalidEnableEpochsHandler)) + missingFlag := testFlags[1] oneFlagUndefinedHandler := &mock.EnableEpochsHandlerStub{ IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { - return flag != core.SetGuardianFlag + return flag != missingFlag }, } - err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler) + err = core.CheckHandlerCompatibility(oneFlagUndefinedHandler, testFlags) require.True(t, errors.Is(err, core.ErrInvalidEnableEpochsHandler)) - require.True(t, strings.Contains(err.Error(), string(core.SetGuardianFlag))) + require.True(t, strings.Contains(err.Error(), string(missingFlag))) } diff --git a/core/export_test.go b/core/export_test.go index 27872f55..98fbbf93 100644 --- a/core/export_test.go +++ b/core/export_test.go @@ -38,3 +38,6 @@ func (sw *StopWatch) SetElapsed(identifier string, duration time.Duration) { func SplitExponentFraction(val string) (string, string) { return splitExponentFraction(val) } + +// TestAutoBalanceDataTriesFlag - +const TestAutoBalanceDataTriesFlag = autoBalanceDataTriesFlag diff --git a/core/file.go b/core/file.go index a7300a53..bb1cb977 100644 --- a/core/file.go +++ b/core/file.go @@ -5,7 +5,7 @@ import ( "encoding/json" "encoding/pem" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -152,7 +152,7 @@ func LoadSkPkFromPemFile(relativePath string, skIndex int) ([]byte, string, erro _ = file.Close() }() - buff, err := ioutil.ReadAll(file) + buff, err := io.ReadAll(file) if err != nil { return nil, "", fmt.Errorf("%w while reading %s file", err, relativePath) } @@ -200,7 +200,7 @@ func LoadAllKeysFromPemFile(relativePath string) ([][]byte, []string, error) { _ = file.Close() }() - buff, err := ioutil.ReadAll(file) + buff, err := io.ReadAll(file) if err != nil { return nil, nil, fmt.Errorf("%w while reading %s file", err, relativePath) } diff --git a/core/file_test.go b/core/file_test.go index edaf0ead..bd2a8406 100644 --- a/core/file_test.go +++ b/core/file_test.go @@ -3,7 +3,6 @@ package core_test import ( "encoding/json" "errors" - "io/ioutil" "os" "path/filepath" "strings" @@ -146,7 +145,7 @@ func TestLoadJSonFile_FileExitsShouldPass(t *testing.T) { data, _ := json.MarshalIndent(TestStruct{A: 0, B: 0}, "", " ") - _ = ioutil.WriteFile(fileName, data, 0644) + _ = os.WriteFile(fileName, data, 0644) err = file.Close() assert.Nil(t, err) diff --git a/core/interface.go b/core/interface.go index 0a734fc5..27888e2b 100644 --- a/core/interface.go +++ b/core/interface.go @@ -145,7 +145,7 @@ type TrieNodeVersionVerifier interface { // EnableEpochsHandler defines the behavior of a component that can return if a feature is enabled or not type EnableEpochsHandler interface { IsFlagDefined(flag EnableEpochFlag) bool - IsFlagEnabledInCurrentEpoch(flag EnableEpochFlag) bool + IsFlagEnabled(flag EnableEpochFlag) bool IsFlagEnabledInEpoch(flag EnableEpochFlag, epoch uint32) bool GetActivationEpoch(flag EnableEpochFlag) uint32 IsInterfaceNil() bool diff --git a/core/mock/enableEpochsHandlerStub.go b/core/mock/enableEpochsHandlerStub.go index 177f3311..fb037b37 100644 --- a/core/mock/enableEpochsHandlerStub.go +++ b/core/mock/enableEpochsHandlerStub.go @@ -4,10 +4,10 @@ import "github.com/multiversx/mx-chain-core-go/core" // EnableEpochsHandlerStub - type EnableEpochsHandlerStub struct { - IsFlagDefinedCalled func(flag core.EnableEpochFlag) bool - IsFlagEnabledInCurrentEpochCalled func(flag core.EnableEpochFlag) bool - IsFlagEnabledInEpochCalled func(flag core.EnableEpochFlag, epoch uint32) bool - GetActivationEpochCalled func(flag core.EnableEpochFlag) uint32 + IsFlagDefinedCalled func(flag core.EnableEpochFlag) bool + IsFlagEnabledCalled func(flag core.EnableEpochFlag) bool + IsFlagEnabledInEpochCalled func(flag core.EnableEpochFlag, epoch uint32) bool + GetActivationEpochCalled func(flag core.EnableEpochFlag) uint32 } // IsFlagDefined - @@ -18,10 +18,10 @@ func (stub *EnableEpochsHandlerStub) IsFlagDefined(flag core.EnableEpochFlag) bo return false } -// IsFlagEnabledInCurrentEpoch - -func (stub *EnableEpochsHandlerStub) IsFlagEnabledInCurrentEpoch(flag core.EnableEpochFlag) bool { - if stub.IsFlagEnabledInCurrentEpochCalled != nil { - return stub.IsFlagEnabledInCurrentEpochCalled(flag) +// IsFlagEnabled - +func (stub *EnableEpochsHandlerStub) IsFlagEnabled(flag core.EnableEpochFlag) bool { + if stub.IsFlagEnabledCalled != nil { + return stub.IsFlagEnabledCalled(flag) } return false } diff --git a/core/trie.go b/core/trie.go index 5e52d447..84331e5c 100644 --- a/core/trie.go +++ b/core/trie.go @@ -23,6 +23,8 @@ const ( // AutoBalanceEnabledString is the string representation of AutoBalanceEnabled trie node version AutoBalanceEnabledString = "auto balanced" + + autoBalanceDataTriesFlag = EnableEpochFlag("AutoBalanceDataTriesFlag") ) func (version TrieNodeVersion) String() string { @@ -40,10 +42,15 @@ type trieNodeVersionVerifier struct { enableEpochsHandler EnableEpochsHandler } +// NewTrieNodeVersionVerifier returns a new instance of trieNodeVersionVerifier func NewTrieNodeVersionVerifier(enableEpochsHandler EnableEpochsHandler) (*trieNodeVersionVerifier, error) { if check.IfNil(enableEpochsHandler) { return nil, ErrNilEnableEpochsHandler } + err := CheckHandlerCompatibility(enableEpochsHandler, []EnableEpochFlag{autoBalanceDataTriesFlag}) + if err != nil { + return nil, err + } return &trieNodeVersionVerifier{ enableEpochsHandler: enableEpochsHandler, @@ -52,7 +59,7 @@ func NewTrieNodeVersionVerifier(enableEpochsHandler EnableEpochsHandler) (*trieN // IsValidVersion returns true if the given trie node version is valid func (vv *trieNodeVersionVerifier) IsValidVersion(version TrieNodeVersion) bool { - if vv.enableEpochsHandler.IsFlagEnabledInCurrentEpoch(AutoBalanceDataTriesFlag) { + if vv.enableEpochsHandler.IsFlagEnabled(autoBalanceDataTriesFlag) { return version <= AutoBalanceEnabled } @@ -66,7 +73,7 @@ func (vv *trieNodeVersionVerifier) IsInterfaceNil() bool { // GetVersionForNewData returns the trie node version that should be used for new data func GetVersionForNewData(handler EnableEpochsHandler) TrieNodeVersion { - if handler.IsFlagEnabledInCurrentEpoch(AutoBalanceDataTriesFlag) { + if handler.IsFlagEnabled(autoBalanceDataTriesFlag) { return AutoBalanceEnabled } diff --git a/core/trie_test.go b/core/trie_test.go index e35948fe..49deec9f 100644 --- a/core/trie_test.go +++ b/core/trie_test.go @@ -1,6 +1,8 @@ package core_test import ( + "errors" + "strings" "testing" "github.com/multiversx/mx-chain-core-go/core" @@ -19,10 +21,27 @@ func TestNewTrieNodeVersionVerifier(t *testing.T) { assert.Nil(t, vv) assert.Equal(t, core.ErrNilEnableEpochsHandler, err) }) + t.Run("incompatible enableEpochsHandler", func(t *testing.T) { + t.Parallel() + + vv, err := core.NewTrieNodeVersionVerifier(&mock.EnableEpochsHandlerStub{ + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + assert.Equal(t, core.TestAutoBalanceDataTriesFlag, flag) + return false + }, + }) + assert.Nil(t, vv) + assert.True(t, errors.Is(err, core.ErrInvalidEnableEpochsHandler)) + assert.True(t, strings.Contains(err.Error(), string(core.TestAutoBalanceDataTriesFlag))) + }) t.Run("new trieNodeVersionVerifier", func(t *testing.T) { t.Parallel() - vv, err := core.NewTrieNodeVersionVerifier(&mock.EnableEpochsHandlerStub{}) + vv, err := core.NewTrieNodeVersionVerifier(&mock.EnableEpochsHandlerStub{ + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag + }, + }) assert.Nil(t, err) assert.False(t, check.IfNil(vv)) }) @@ -36,8 +55,11 @@ func TestTrieNodeVersionVerifier_IsValidVersion(t *testing.T) { vv, _ := core.NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { - return flag == core.AutoBalanceDataTriesFlag + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag + }, + IsFlagEnabledCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag }, }, ) @@ -51,7 +73,10 @@ func TestTrieNodeVersionVerifier_IsValidVersion(t *testing.T) { vv, _ := core.NewTrieNodeVersionVerifier( &mock.EnableEpochsHandlerStub{ - IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag + }, + IsFlagEnabledCalled: func(flag core.EnableEpochFlag) bool { return false }, }, @@ -78,8 +103,11 @@ func TestGetVersionForNewData(t *testing.T) { getVersionForNewData := core.GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { - return flag == core.AutoBalanceDataTriesFlag + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag + }, + IsFlagEnabledCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag }, }, ) @@ -91,7 +119,10 @@ func TestGetVersionForNewData(t *testing.T) { getVersionForNewData := core.GetVersionForNewData( &mock.EnableEpochsHandlerStub{ - IsFlagEnabledInCurrentEpochCalled: func(flag core.EnableEpochFlag) bool { + IsFlagDefinedCalled: func(flag core.EnableEpochFlag) bool { + return flag == core.TestAutoBalanceDataTriesFlag + }, + IsFlagEnabledCalled: func(flag core.EnableEpochFlag) bool { return false }, }, diff --git a/data/outport/common_test.go b/data/outport/common_test.go index 434a64e1..c3cdea60 100644 --- a/data/outport/common_test.go +++ b/data/outport/common_test.go @@ -55,7 +55,7 @@ func TestGetBody(t *testing.T) { require.Nil(t, receivedBody) require.Equal(t, errNilBodyHandler, err) - var body data.BodyHandler + var body data.BodyHandler // nolint body = &block.Body{} receivedBody, err = GetBody(body) require.Nil(t, err) diff --git a/data/transaction/transaction_test.go b/data/transaction/transaction_test.go index 02306653..2a0892ab 100644 --- a/data/transaction/transaction_test.go +++ b/data/transaction/transaction_test.go @@ -351,7 +351,7 @@ func TestTransaction_CheckIntegrityShouldErr(t *testing.T) { func TestTransaction_ImplementsGuardedTransactionHandler(t *testing.T) { t.Parallel() - var tx data.TransactionHandler + var tx data.TransactionHandler // nolint tx = &transaction.Transaction{} _, ok := tx.(data.GuardedTransactionHandler) From 9a2b5556fe40b78cc1ee2c22ef62ad6a8775e60f Mon Sep 17 00:00:00 2001 From: Sorin Stanculeanu Date: Mon, 21 Aug 2023 15:03:49 +0300 Subject: [PATCH 6/6] removed no lint lines --- data/outport/common_test.go | 3 +-- data/transaction/transaction_test.go | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/data/outport/common_test.go b/data/outport/common_test.go index c3cdea60..0fe18b65 100644 --- a/data/outport/common_test.go +++ b/data/outport/common_test.go @@ -55,8 +55,7 @@ func TestGetBody(t *testing.T) { require.Nil(t, receivedBody) require.Equal(t, errNilBodyHandler, err) - var body data.BodyHandler // nolint - body = &block.Body{} + body := &block.Body{} receivedBody, err = GetBody(body) require.Nil(t, err) require.Equal(t, body, receivedBody) diff --git a/data/transaction/transaction_test.go b/data/transaction/transaction_test.go index 2a0892ab..93151a32 100644 --- a/data/transaction/transaction_test.go +++ b/data/transaction/transaction_test.go @@ -351,8 +351,7 @@ func TestTransaction_CheckIntegrityShouldErr(t *testing.T) { func TestTransaction_ImplementsGuardedTransactionHandler(t *testing.T) { t.Parallel() - var tx data.TransactionHandler // nolint - tx = &transaction.Transaction{} + var tx data.TransactionHandler = &transaction.Transaction{} _, ok := tx.(data.GuardedTransactionHandler) assert.True(t, ok)