diff --git a/load-testing/tests/relays_stress_helpers_test.go b/load-testing/tests/relays_stress_helpers_test.go index 5bd17d127..a78d42ac7 100644 --- a/load-testing/tests/relays_stress_helpers_test.go +++ b/load-testing/tests/relays_stress_helpers_test.go @@ -39,7 +39,7 @@ import ( "github.com/pokt-network/poktroll/testutil/testclient/testeventsquery" apptypes "github.com/pokt-network/poktroll/x/application/types" gatewaytypes "github.com/pokt-network/poktroll/x/gateway/types" - "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" suppliertypes "github.com/pokt-network/poktroll/x/supplier/types" ) @@ -173,9 +173,9 @@ func (s *relaysSuite) mapSessionInfoForLoadTestDurationFn( sessionInfo := &sessionInfoNotif{ blockHeight: blockHeight, - sessionNumber: keeper.GetSessionNumber(blockHeight), - sessionStartBlockHeight: keeper.GetSessionStartBlockHeight(blockHeight), - sessionEndBlockHeight: keeper.GetSessionEndBlockHeight(blockHeight), + sessionNumber: shared.GetSessionNumber(blockHeight), + sessionStartBlockHeight: shared.GetSessionStartBlockHeight(blockHeight), + sessionEndBlockHeight: shared.GetSessionEndBlockHeight(blockHeight), } infoLogger := logger.Info(). @@ -330,15 +330,15 @@ func (plans *actorLoadTestIncrementPlans) validateAppSupplierPermutations(t gocu // Otherwise, the expected baseline for several metrics will be periodically skewed. func (plans *actorLoadTestIncrementPlans) validateIncrementRates(t gocuke.TestingT) { require.Truef(t, - plans.gateways.blocksPerIncrement%keeper.NumBlocksPerSession == 0, + plans.gateways.blocksPerIncrement%shared.NumBlocksPerSession == 0, "gateway increment rate must be a multiple of the session length", ) require.Truef(t, - plans.suppliers.blocksPerIncrement%keeper.NumBlocksPerSession == 0, + plans.suppliers.blocksPerIncrement%shared.NumBlocksPerSession == 0, "supplier increment rate must be a multiple of the session length", ) require.Truef(t, - plans.apps.blocksPerIncrement%keeper.NumBlocksPerSession == 0, + plans.apps.blocksPerIncrement%shared.NumBlocksPerSession == 0, "app increment rate must be a multiple of the session length", ) } @@ -369,12 +369,11 @@ func (plans *actorLoadTestIncrementPlans) totalDurationBlocks() int64 { // last increment duration (i.e. **after** maxActorCount actors are activated). blocksToLastSessionEnd := plans.maxActorBlocksToFinalIncrementEnd() - sessionGracePeriodBlocks := keeper.GetSessionGracePeriodBlockCount() - blocksToLastProofWindowEnd := blocksToLastSessionEnd + sessionGracePeriodBlocks + blocksToLastProofWindowEnd := blocksToLastSessionEnd + shared.SessionGracePeriodBlocks // Add one session length so that the duration is inclusive of the block which // commits the last session's proof. - return blocksToLastProofWindowEnd + keeper.NumBlocksPerSession + return blocksToLastProofWindowEnd + shared.NumBlocksPerSession } // blocksToFinalIncrementStart returns the number of blocks that will have @@ -721,9 +720,9 @@ func (plan *actorLoadTestIncrementPlan) shouldIncrementActorCount( return false } - initialSessionNumber := keeper.GetSessionNumber(startBlockHeight) + initialSessionNumber := shared.GetSessionNumber(startBlockHeight) // TODO_TECHDEBT(#21): replace with gov param query when available. - actorSessionIncRate := plan.blocksPerIncrement / keeper.NumBlocksPerSession + actorSessionIncRate := plan.blocksPerIncrement / shared.NumBlocksPerSession nextSessionNumber := sessionInfo.sessionNumber + 1 - initialSessionNumber isSessionStartHeight := sessionInfo.blockHeight == sessionInfo.sessionStartBlockHeight isActorIncrementHeight := nextSessionNumber%actorSessionIncRate == 0 @@ -747,9 +746,9 @@ func (plan *actorLoadTestIncrementPlan) shouldIncrementSupplierCount( return false } - initialSessionNumber := keeper.GetSessionNumber(startBlockHeight) + initialSessionNumber := shared.GetSessionNumber(startBlockHeight) // TODO_TECHDEBT(#21): replace with gov param query when available. - supplierSessionIncRate := plan.blocksPerIncrement / keeper.NumBlocksPerSession + supplierSessionIncRate := plan.blocksPerIncrement / shared.NumBlocksPerSession nextSessionNumber := sessionInfo.sessionNumber + 1 - initialSessionNumber isSessionEndHeight := sessionInfo.blockHeight == sessionInfo.sessionEndBlockHeight isActorIncrementHeight := nextSessionNumber%supplierSessionIncRate == 0 diff --git a/pkg/client/interface.go b/pkg/client/interface.go index 77484c454..3f801bf6b 100644 --- a/pkg/client/interface.go +++ b/pkg/client/interface.go @@ -7,6 +7,7 @@ //go:generate mockgen -destination=../../testutil/mockclient/application_query_client_mock.go -package=mockclient . ApplicationQueryClient //go:generate mockgen -destination=../../testutil/mockclient/supplier_query_client_mock.go -package=mockclient . SupplierQueryClient //go:generate mockgen -destination=../../testutil/mockclient/session_query_client_mock.go -package=mockclient . SessionQueryClient +//go:generate mockgen -destination=../../testutil/mockclient/shared_query_client_mock.go -package=mockclient . SharedQueryClient //go:generate mockgen -destination=../../testutil/mockclient/cosmos_tx_builder_mock.go -package=mockclient github.com/cosmos/cosmos-sdk/client TxBuilder //go:generate mockgen -destination=../../testutil/mockclient/cosmos_keyring_mock.go -package=mockclient github.com/cosmos/cosmos-sdk/crypto/keyring Keyring //go:generate mockgen -destination=../../testutil/mockclient/cosmos_client_mock.go -package=mockclient github.com/cosmos/cosmos-sdk/client AccountRetriever @@ -275,3 +276,10 @@ type SessionQueryClient interface { blockHeight int64, ) (*sessiontypes.Session, error) } + +// SharedQueryClient defines an interface that enables the querying of the +// on-chain shared module information. +type SharedQueryClient interface { + // GetParams queries the chain for the current shared module parameters. + GetParams(ctx context.Context) (*sharedtypes.Params, error) +} diff --git a/pkg/client/query/errors.go b/pkg/client/query/errors.go index 352e56ce3..487b79734 100644 --- a/pkg/client/query/errors.go +++ b/pkg/client/query/errors.go @@ -8,4 +8,5 @@ var ( ErrQueryUnableToDeserializeAccount = sdkerrors.Register(codespace, 2, "unable to deserialize account") ErrQueryRetrieveSession = sdkerrors.Register(codespace, 3, "error while trying to retrieve a session") ErrQueryPubKeyNotFound = sdkerrors.Register(codespace, 4, "account pub key not found") + ErrQuerySessionParams = sdkerrors.Register(codespace, 5, "unable to query session params") ) diff --git a/pkg/client/query/sessionquerier.go b/pkg/client/query/sessionquerier.go index 6a86205fe..a08d49f16 100644 --- a/pkg/client/query/sessionquerier.go +++ b/pkg/client/query/sessionquerier.go @@ -4,7 +4,7 @@ import ( "context" "cosmossdk.io/depinject" - grpc "github.com/cosmos/gogoproto/grpc" + "github.com/cosmos/gogoproto/grpc" "github.com/pokt-network/poktroll/pkg/client" sessiontypes "github.com/pokt-network/poktroll/x/session/types" diff --git a/pkg/client/query/sharedquerier.go b/pkg/client/query/sharedquerier.go new file mode 100644 index 000000000..2c4ac4abb --- /dev/null +++ b/pkg/client/query/sharedquerier.go @@ -0,0 +1,55 @@ +package query + +import ( + "context" + + "cosmossdk.io/depinject" + "github.com/cosmos/gogoproto/grpc" + + "github.com/pokt-network/poktroll/pkg/client" + sharedtypes "github.com/pokt-network/poktroll/x/shared/types" +) + +var _ client.SharedQueryClient = (*sharedQuerier)(nil) + +// sharedQuerier is a wrapper around the sharedtypes.QueryClient that enables the +// querying of on-chain shared information through a single exposed method +// which returns an sharedtypes.Session struct +type sharedQuerier struct { + clientConn grpc.ClientConn + sharedQuerier sharedtypes.QueryClient +} + +// NewSharedQuerier returns a new instance of a client.SharedQueryClient by +// injecting the dependecies provided by the depinject.Config. +// +// Required dependencies: +// - clientCtx +func NewSharedQuerier(deps depinject.Config) (client.SharedQueryClient, error) { + querier := &sharedQuerier{} + + if err := depinject.Inject( + deps, + &querier.clientConn, + ); err != nil { + return nil, err + } + + querier.sharedQuerier = sharedtypes.NewQueryClient(querier.clientConn) + + return querier, nil +} + +// GetParams queries & returns the shared module on-chain parameters. +// +// TODO_TECHDEBT(#543): We don't really want to have to query the params for every method call. +// Once `ModuleParamsClient` is implemented, use its replay observable's `#Last()` method +// to get the most recently (asynchronously) observed (and cached) value. +func (sq *sharedQuerier) GetParams(ctx context.Context) (*sharedtypes.Params, error) { + req := &sharedtypes.QueryParamsRequest{} + res, err := sq.sharedQuerier.Params(ctx, req) + if err != nil { + return nil, ErrQuerySessionParams.Wrapf("[%v]", err) + } + return &res.Params, nil +} diff --git a/pkg/crypto/rings/client.go b/pkg/crypto/rings/client.go index b7eb1f104..9e8560833 100644 --- a/pkg/crypto/rings/client.go +++ b/pkg/crypto/rings/client.go @@ -9,14 +9,14 @@ import ( ring_secp256k1 "github.com/athanorlabs/go-dleq/secp256k1" ringtypes "github.com/athanorlabs/go-dleq/types" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - ring "github.com/noot/ring-go" + "github.com/noot/ring-go" "github.com/pokt-network/poktroll/pkg/client" "github.com/pokt-network/poktroll/pkg/crypto" "github.com/pokt-network/poktroll/pkg/polylog" apptypes "github.com/pokt-network/poktroll/x/application/types" "github.com/pokt-network/poktroll/x/service/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) var _ crypto.RingClient = (*ringClient)(nil) @@ -265,7 +265,7 @@ func (rc *ringClient) getRingPointsForAddressAtHeight( // gateways that have been undelegated after the target session end height. func GetRingAddressesAtBlock(app *apptypes.Application, blockHeight int64) []string { // Get the target session end height at which we want to get the active delegations. - targetSessionEndHeight := uint64(sessionkeeper.GetSessionEndBlockHeight(blockHeight)) + targetSessionEndHeight := uint64(shared.GetSessionEndBlockHeight(blockHeight)) // Get the current active delegations for the application and use them as a base. activeDelegationsAtHeight := app.DelegateeGatewayAddresses diff --git a/pkg/deps/config/suppliers.go b/pkg/deps/config/suppliers.go index 80fa4a0e9..d96ec6d74 100644 --- a/pkg/deps/config/suppliers.go +++ b/pkg/deps/config/suppliers.go @@ -378,7 +378,7 @@ func NewSupplyPOKTRollSDKFn(signingKeyName string) SupplierFn { } } -// newSupplyBlockQueryClientFn returns a function which constructs a +// NewSupplyBlockQueryClientFn returns a function which constructs a // BlockQueryClient instance and returns a new depinject.Config which // is supplied with the given deps and the new BlockQueryClient. func NewSupplyBlockQueryClientFn(queryNodeRPCUrl *url.URL) SupplierFn { @@ -395,3 +395,21 @@ func NewSupplyBlockQueryClientFn(queryNodeRPCUrl *url.URL) SupplierFn { return depinject.Configs(deps, depinject.Supply(blockQueryClient)), nil } } + +// NewSupplySharedQueryClientFn returns a function which constructs a +// SharedQueryClient instance and returns a new depinject.Config which +// is supplied with the given deps and the new SharedQueryClient. +func NewSupplySharedQueryClientFn() SupplierFn { + return func( + _ context.Context, + deps depinject.Config, + _ *cobra.Command, + ) (depinject.Config, error) { + sharedQuerier, err := query.NewSharedQuerier(deps) + if err != nil { + return nil, err + } + + return depinject.Configs(deps, depinject.Supply(sharedQuerier)), nil + } +} diff --git a/pkg/relayer/cmd/cmd.go b/pkg/relayer/cmd/cmd.go index 60830763e..03a870b78 100644 --- a/pkg/relayer/cmd/cmd.go +++ b/pkg/relayer/cmd/cmd.go @@ -195,6 +195,7 @@ func setupRelayerDependencies( supplyMiner, // leaf config.NewSupplyTxClientContextFn(queryNodeGRPCUrl, txNodeRPCUrl), // leaf config.NewSupplyDelegationClientFn(), // leaf + config.NewSupplySharedQueryClientFn(), // leaf config.NewSupplyAccountQuerierFn(), config.NewSupplyApplicationQuerierFn(), config.NewSupplySupplierQuerierFn(), diff --git a/pkg/relayer/proxy/proxy.go b/pkg/relayer/proxy/proxy.go index 8e8f8b0fa..c3417c3f9 100644 --- a/pkg/relayer/proxy/proxy.go +++ b/pkg/relayer/proxy/proxy.go @@ -38,8 +38,9 @@ type relayerProxy struct { // which contains the supported services, RPC types, and endpoints, etc... supplierQuerier client.SupplierQueryClient - // sessionQuerier is the querier used to get the current session from the blockchain, - // which is needed to check if the relay proxy should be serving an incoming relay request. + // sessionQuerier is the query client used to get the current session & session params + // from the blockchain, which are needed to check if the relay proxy should be serving an + // incoming relay request. sessionQuerier client.SessionQueryClient // servers is a map of listenAddress -> RelayServer provided by the relayer proxy, diff --git a/pkg/relayer/proxy/proxy_test.go b/pkg/relayer/proxy/proxy_test.go index 2ed0f7415..15a5d9866 100644 --- a/pkg/relayer/proxy/proxy_test.go +++ b/pkg/relayer/proxy/proxy_test.go @@ -17,7 +17,7 @@ import ( "github.com/pokt-network/poktroll/pkg/relayer/config" "github.com/pokt-network/poktroll/pkg/relayer/proxy" "github.com/pokt-network/poktroll/testutil/testproxy" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -346,14 +346,14 @@ func TestRelayerProxy_Relays(t *testing.T) { // blockOutsideSessionGracePeriod is the block height that is after the first // session's grace period and within the second session's grace period, // meaning a relay should not be handled at this block height. - blockOutsideSessionGracePeriod := blockHeight + - sessionkeeper.NumBlocksPerSession + - sessionkeeper.GetSessionGracePeriodBlockCount() + blockOutsideSessionGracePeriod := int64(blockHeight + + shared.NumBlocksPerSession + + shared.SessionGracePeriodBlocks) // blockWithinSessionGracePeriod is the block height that is after the first // session but within its session's grace period, meaning a relay should be // handled at this block height. - blockWithinSessionGracePeriod := blockHeight + sessionkeeper.GetSessionGracePeriodBlockCount() + blockWithinSessionGracePeriod := int64(blockHeight + shared.SessionGracePeriodBlocks) tests := []struct { desc string @@ -656,7 +656,7 @@ func sendRequestWithDifferentSession( test *testproxy.TestBehavior, ) (errCode int32, errorMessage string) { // Use a block height that generates a different session ID - blockHeightAfterSessionGracePeriod := blockHeight + sessionkeeper.GetSessionGracePeriodBlockCount() + blockHeightAfterSessionGracePeriod := int64(blockHeight + shared.SessionGracePeriodBlocks) req := testproxy.GenerateRelayRequest( test, appPrivateKey, diff --git a/pkg/relayer/proxy/relay_verifier.go b/pkg/relayer/proxy/relay_verifier.go index 011b1b293..11cba8b7d 100644 --- a/pkg/relayer/proxy/relay_verifier.go +++ b/pkg/relayer/proxy/relay_verifier.go @@ -3,8 +3,8 @@ package proxy import ( "context" - sessiontypes "github.com/pokt-network/poktroll/pkg/relayer/session" "github.com/pokt-network/poktroll/x/service/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -99,7 +99,7 @@ func (rp *relayerProxy) getTargetSessionBlockHeight( if sessionEndblockHeight < currentBlockHeight { // Do not process the `RelayRequest` if the session has expired and the current // block height is outside the session's grace period. - if sessiontypes.IsWithinGracePeriod(sessionEndblockHeight, currentBlockHeight) { + if !shared.IsGracePeriodElapsed(sessionEndblockHeight, currentBlockHeight) { // The RelayRequest's session has expired but is still within the // grace period so process it as if the session is still active. return sessionEndblockHeight, nil diff --git a/pkg/relayer/session/claim.go b/pkg/relayer/session/claim.go index f9be2455d..1f5761a88 100644 --- a/pkg/relayer/session/claim.go +++ b/pkg/relayer/session/claim.go @@ -11,7 +11,7 @@ import ( "github.com/pokt-network/poktroll/pkg/observable/logging" "github.com/pokt-network/poktroll/pkg/relayer" "github.com/pokt-network/poktroll/pkg/relayer/protocol" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) // createClaims maps over the sessionsToClaimObs observable. For each claim batch, it: @@ -42,6 +42,10 @@ func (rs *relayerSessionsManager) createClaims( ) // TODO_TECHDEBT: pass failed create claim sessions to some retry mechanism. + // TODO_IMPROVE: It may be useful for the retry mechanism which consumes the + // observable which corresponds to failSubmitProofsSessionsCh to have a + // reference to the error which caused the proof submission to fail. + // In this case, the error may not be persistent. _ = failedCreateClaimSessionsObs logging.LogErrors(ctx, filter.EitherError(ctx, eitherClaimedSessionsObs)) @@ -82,11 +86,12 @@ func (rs *relayerSessionsManager) waitForEarliestCreateClaimsHeight( // first one from the group to calculate the earliest height for claim creation. sessionEndHeight := sessionTrees[0].GetSessionHeader().GetSessionEndBlockHeight() - // TODO_TECHDEBT(@red-0ne): Centralize the business logic that involves taking + // TODO_TECHDEBT(#516): Centralize the business logic that involves taking // into account the heights, windows and grace periods into helper functions. // An additional block is added to permit to relays arriving at the last block // of the session to be included in the claim before the smt is closed. - createClaimsWindowStartHeight := sessionEndHeight + sessionkeeper.GetSessionGracePeriodBlockCount() + 1 + sessionGracePeriodEndHeight := shared.GetSessionGracePeriodEndHeight(sessionEndHeight) + createClaimsWindowStartHeight := sessionGracePeriodEndHeight + 1 // TODO_BLOCKER: query the on-chain governance parameter once available. // + claimproofparams.GovCreateClaimWindowStartHeightOffset diff --git a/pkg/relayer/session/proof.go b/pkg/relayer/session/proof.go index 52e3e8e69..9acb77803 100644 --- a/pkg/relayer/session/proof.go +++ b/pkg/relayer/session/proof.go @@ -12,7 +12,7 @@ import ( "github.com/pokt-network/poktroll/pkg/relayer" "github.com/pokt-network/poktroll/pkg/relayer/protocol" proofkeeper "github.com/pokt-network/poktroll/x/proof/keeper" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) // submitProofs maps over the given claimedSessions observable. @@ -79,12 +79,16 @@ func (rs *relayerSessionsManager) waitForEarliestSubmitProofsHeightAndGeneratePr // first one from the group to calculate the earliest height for proof submission. sessionEndHeight := sessionTrees[0].GetSessionHeader().GetSessionEndBlockHeight() - sessionGracePeriodEndHeight := sessionkeeper.GetSessionGracePeriodBlockCount() + sessionEndHeight - // TODO_TECHDEBT(#516): Centralize the business logic that involves taking // into account the heights, windows and grace periods into helper functions. - // TODO_BLOCKER(#516): The proof submission window SHOULD NOT overlap with the claim window. - submitProofsWindowStartHeight := sessionGracePeriodEndHeight + 1 + // TODO_BLOCKER(#516): The proof submission window SHOULD NOT overlap with the + // claim window. The proof submission window start SHOULD be relative to the + // claim window end. + sessionGracePeriodEndHeight := shared.GetSessionGracePeriodEndHeight(sessionEndHeight) + // An additional block is added to permit to relays arriving at the last block + // of the session to be included in the claim before the smt is closed. + createClaimsWindowStartHeight := sessionGracePeriodEndHeight + 1 + submitProofsWindowStartHeight := createClaimsWindowStartHeight // TODO_BLOCKER(#516): query the on-chain governance parameter once available. // + claimproofparams.GovSubmitProofWindowStartHeightOffset @@ -95,7 +99,7 @@ func (rs *relayerSessionsManager) waitForEarliestSubmitProofsHeightAndGeneratePr // TODO_BLOCKER(@bryanchriswhite): The block that'll be used as a source of entropy for // which branch(es) to prove should be deterministic and use on-chain governance params. - // submitProofWindowStartBlock is the block that will have its hash used as the + // sessionPathBlock is the block that will have its hash used as the // source of entropy for all the session trees in that batch, waiting for it to // be received before proceeding. sessionPathBlock := rs.waitForBlock(ctx, sessionGracePeriodEndHeight) diff --git a/pkg/relayer/session/session.go b/pkg/relayer/session/session.go index 84d786eed..531c1208e 100644 --- a/pkg/relayer/session/session.go +++ b/pkg/relayer/session/session.go @@ -12,8 +12,8 @@ import ( "github.com/pokt-network/poktroll/pkg/observable/logging" "github.com/pokt-network/poktroll/pkg/polylog" "github.com/pokt-network/poktroll/pkg/relayer" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" ) var _ relayer.RelayerSessionsManager = (*relayerSessionsManager)(nil) @@ -48,6 +48,9 @@ type relayerSessionsManager struct { // storesDirectory points to a path on disk where KVStore data files are created. storesDirectory string + + // sharedQueryClient is used to query shared module parameters. + sharedQueryClient client.SharedQueryClient } // NewRelayerSessions creates a new relayerSessions. @@ -73,6 +76,7 @@ func NewRelayerSessions( deps, &rs.blockClient, &rs.supplierClient, + &rs.sharedQueryClient, ); err != nil { return nil, err } @@ -164,8 +168,9 @@ func (rs *relayerSessionsManager) ensureSessionTree(sessionHeader *sessiontypes. // TODO_IMPROVE: Add the ability for the process to resume where it left off in // case the process is restarted or the connection is dropped and reconnected. func (rs *relayerSessionsManager) mapBlockToSessionsToClaim( - _ context.Context, block client.Block, -) ([]relayer.SessionTree, bool) { + ctx context.Context, + block client.Block, +) (sessionTrees []relayer.SessionTree, skip bool) { rs.sessionsTreesMu.Lock() defer rs.sessionsTreesMu.Unlock() @@ -174,18 +179,31 @@ func (rs *relayerSessionsManager) mapBlockToSessionsToClaim( // They will be emitted last, after all the late sessions have been emitted. var onTimeSessions []relayer.SessionTree + // TODO_TECHDEBT(#543): We don't really want to have to query the params for every method call. + // Once `ModuleParamsClient` is implemented, use its replay observable's `#Last()` method + // to get the most recently (asynchronously) observed (and cached) value. + sharedParams, err := rs.sharedQueryClient.GetParams(ctx) + if err != nil { + rs.logger.Error().Err(err).Msg("unable to query shared module params") + return nil, true + } + + numBlocksPerSession := sharedParams.NumBlocksPerSession + // Check if there are sessions that need to enter the claim/proof phase as their // end block height was the one before the last committed block or earlier. // Iterate over the sessionsTrees map to get the ones that end at a block height // lower than the current block height. - for endBlockHeight, sessionsTreesEndingAtBlockHeight := range rs.sessionsTrees { + for sessionEndHeight, sessionsTreesEndingAtBlockHeight := range rs.sessionsTrees { // Late sessions are the ones that have their session grace period elapsed // and should already have been claimed. // Group them by their end block height and emit each group separately // before emitting the on-time sessions. var lateSessions []relayer.SessionTree - // !IsWithinGracePeriod is checking for sessions to claim with <= operator, + sessionGracePeriodEndHeight := shared.GetSessionGracePeriodEndHeight(sessionEndHeight) + + // Checking for sessions to claim with <= operator, // which means that it would include sessions that were supposed to be // claimed in previous block heights too. // These late sessions might have their create claim window closed and are @@ -194,7 +212,7 @@ func (rs *relayerSessionsManager) mapBlockToSessionsToClaim( // downstream at the waitForEarliestCreateClaimsHeight step. // TODO_BLOCKER: Introduce governance claim and proof window durations, // implement off-chain window closing and on-chain window checks. - if !IsWithinGracePeriod(endBlockHeight, block.Height()) { + if sessionGracePeriodEndHeight <= block.Height() { // Iterate over the sessionsTrees that have grace period ending at this // block height and add them to the list of sessionTrees to be published. for _, sessionTree := range sessionsTreesEndingAtBlockHeight { @@ -211,7 +229,7 @@ func (rs *relayerSessionsManager) mapBlockToSessionsToClaim( // Separate the sessions that are on-time from the ones that are late. // If the session is past its grace period, it is considered late, // otherwise it is on time and will be emitted last. - if IsPastGracePeriod(endBlockHeight, block.Height()) { + if sessionGracePeriodEndHeight+int64(numBlocksPerSession) < block.Height() { lateSessions = append(lateSessions, sessionTree) } else { onTimeSessions = append(onTimeSessions, sessionTree) @@ -318,15 +336,3 @@ func (rs *relayerSessionsManager) mapAddMinedRelayToSessionTree( // Skip because this map function only outputs errors. return nil, true } - -// IsWithinGracePeriod checks if the grace period for the session has ended -// and signals whether it is time to create a claim for it. -func IsWithinGracePeriod(sessionEndBlockHeight, currentBlockHeight int64) bool { - return currentBlockHeight <= sessionEndBlockHeight+sessionkeeper.GetSessionGracePeriodBlockCount() -} - -// IsPastGracePeriod checks if the grace period for the session, given its end -// block height, has ended. -func IsPastGracePeriod(sessionEndBlockHeight, currentBlockHeight int64) bool { - return currentBlockHeight > sessionEndBlockHeight+sessionkeeper.GetSessionGracePeriodBlockCount() -} diff --git a/pkg/relayer/session/session_test.go b/pkg/relayer/session/session_test.go index 0d681076c..5444bee9d 100644 --- a/pkg/relayer/session/session_test.go +++ b/pkg/relayer/session/session_test.go @@ -20,10 +20,11 @@ import ( "github.com/pokt-network/poktroll/pkg/relayer/session" "github.com/pokt-network/poktroll/testutil/mockclient" "github.com/pokt-network/poktroll/testutil/testclient/testblock" + "github.com/pokt-network/poktroll/testutil/testclient/testqueryclients" "github.com/pokt-network/poktroll/testutil/testclient/testsupplier" "github.com/pokt-network/poktroll/testutil/testpolylog" "github.com/pokt-network/poktroll/testutil/testrelayer" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) func TestRelayerSessionsManager_Start(t *testing.T) { @@ -71,7 +72,9 @@ func TestRelayerSessionsManager_Start(t *testing.T) { ). AnyTimes() - deps := depinject.Supply(blockClient, blockQueryClientMock, supplierClient) + sharedQueryClientMock := testqueryclients.NewTestSharedQueryClient(t) + + deps := depinject.Supply(blockClient, blockQueryClientMock, supplierClient, sharedQueryClientMock) storesDirectoryOpt := testrelayer.WithTempStoresDirectory(t) // Create a new relayer sessions manager. @@ -101,7 +104,7 @@ func TestRelayerSessionsManager_Start(t *testing.T) { // Calculate the session grace period end block height to emit that block height // to the blockPublishCh to trigger claim creation for the session. - sessionGracePeriodEndBlockHeight := int64(sessionEndHeight + sessionkeeper.GetSessionGracePeriodBlockCount()) + sessionGracePeriodEndBlockHeight := int64(sessionEndHeight + shared.SessionGracePeriodBlocks) // Publish a block to the blockPublishCh to trigger claim creation for the session. // TODO_TECHDEBT: assumes claiming at sessionGracePeriodEndBlockHeight is valid. diff --git a/testutil/testclient/testqueryclients/sessionquerier.go b/testutil/testclient/testqueryclients/sessionquerier.go index c8c24770a..552e66969 100644 --- a/testutil/testclient/testqueryclients/sessionquerier.go +++ b/testutil/testclient/testqueryclients/sessionquerier.go @@ -11,6 +11,7 @@ import ( "github.com/pokt-network/poktroll/testutil/mockclient" sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -79,11 +80,11 @@ func AddToExistingSessions( Service: &sharedtypes.Service{Id: serviceId}, ApplicationAddress: appAddress, SessionId: sessionId, - SessionStartBlockHeight: sessionkeeper.GetSessionStartBlockHeight(blockHeight), - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(blockHeight), + SessionStartBlockHeight: shared.GetSessionStartBlockHeight(blockHeight), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(blockHeight), }, - NumBlocksPerSession: sessionkeeper.NumBlocksPerSession, - SessionNumber: sessionkeeper.GetSessionNumber(blockHeight), + NumBlocksPerSession: shared.NumBlocksPerSession, + SessionNumber: shared.GetSessionNumber(blockHeight), SessionId: sessionId, Suppliers: []*sharedtypes.Supplier{}, } diff --git a/testutil/testclient/testqueryclients/sharedquerier.go b/testutil/testclient/testqueryclients/sharedquerier.go new file mode 100644 index 000000000..82ffa88f2 --- /dev/null +++ b/testutil/testclient/testqueryclients/sharedquerier.go @@ -0,0 +1,26 @@ +package testqueryclients + +import ( + "testing" + + "github.com/golang/mock/gomock" + + "github.com/pokt-network/poktroll/testutil/mockclient" + sharedtypes "github.com/pokt-network/poktroll/x/shared/types" +) + +// NewTestSharedQueryClient creates a mock of the SharedQueryClient. +func NewTestSharedQueryClient( + t *testing.T, +) *mockclient.MockSharedQueryClient { + ctrl := gomock.NewController(t) + + sharedQuerier := mockclient.NewMockSharedQueryClient(ctrl) + params := sharedtypes.DefaultParams() + + sharedQuerier.EXPECT().GetParams(gomock.Any()). + Return(¶ms, nil). + AnyTimes() + + return sharedQuerier +} diff --git a/testutil/testproxy/relayerproxy.go b/testutil/testproxy/relayerproxy.go index 152d1df56..1e1363063 100644 --- a/testutil/testproxy/relayerproxy.go +++ b/testutil/testproxy/relayerproxy.go @@ -15,7 +15,7 @@ import ( ring_secp256k1 "github.com/athanorlabs/go-dleq/secp256k1" ringtypes "github.com/athanorlabs/go-dleq/types" keyringtypes "github.com/cosmos/cosmos-sdk/crypto/keyring" - secp256k1 "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/bech32" "github.com/noot/ring-go" @@ -28,12 +28,13 @@ import ( "github.com/pokt-network/poktroll/pkg/signer" "github.com/pokt-network/poktroll/testutil/testclient/testblock" "github.com/pokt-network/poktroll/testutil/testclient/testdelegation" - testkeyring "github.com/pokt-network/poktroll/testutil/testclient/testkeyring" + "github.com/pokt-network/poktroll/testutil/testclient/testkeyring" "github.com/pokt-network/poktroll/testutil/testclient/testqueryclients" testrings "github.com/pokt-network/poktroll/testutil/testcrypto/rings" servicetypes "github.com/pokt-network/poktroll/x/service/types" sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -270,7 +271,7 @@ func WithSuccessiveSessions( test.t, appAddress, serviceId, - sessionkeeper.NumBlocksPerSession*int64(i), + shared.NumBlocksPerSession*int64(i), sessionSuppliers, ) } @@ -408,8 +409,8 @@ func GenerateRelayRequest( ApplicationAddress: appAddress, SessionId: string(sessionId[:]), Service: &sharedtypes.Service{Id: serviceId}, - SessionStartBlockHeight: sessionkeeper.GetSessionStartBlockHeight(blockHeight), - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(blockHeight), + SessionStartBlockHeight: shared.GetSessionStartBlockHeight(blockHeight), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(blockHeight), }, // The returned relay is unsigned and must be signed elsewhere for functionality Signature: []byte(""), diff --git a/x/application/keeper/msg_server_undelegate_from_gateway.go b/x/application/keeper/msg_server_undelegate_from_gateway.go index 3a782e36b..f5a0345da 100644 --- a/x/application/keeper/msg_server_undelegate_from_gateway.go +++ b/x/application/keeper/msg_server_undelegate_from_gateway.go @@ -9,7 +9,7 @@ import ( "github.com/pokt-network/poktroll/telemetry" "github.com/pokt-network/poktroll/x/application/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) func (k msgServer) UndelegateFromGateway(ctx context.Context, msg *types.MsgUndelegateFromGateway) (*types.MsgUndelegateFromGatewayResponse, error) { @@ -80,7 +80,7 @@ func (k Keeper) recordPendingUndelegation( gatewayAddress string, currentBlockHeight int64, ) { - sessionEndHeight := uint64(sessionkeeper.GetSessionEndBlockHeight(currentBlockHeight)) + sessionEndHeight := uint64(shared.GetSessionEndBlockHeight(currentBlockHeight)) undelegatingGatewayListAtBlock := app.PendingUndelegations[sessionEndHeight] // Add the gateway address to the undelegated gateways list if it's not already there. diff --git a/x/application/keeper/msg_server_undelegate_from_gateway_test.go b/x/application/keeper/msg_server_undelegate_from_gateway_test.go index 682340ab6..c5d80977d 100644 --- a/x/application/keeper/msg_server_undelegate_from_gateway_test.go +++ b/x/application/keeper/msg_server_undelegate_from_gateway_test.go @@ -14,7 +14,7 @@ import ( "github.com/pokt-network/poktroll/testutil/sample" "github.com/pokt-network/poktroll/x/application/keeper" "github.com/pokt-network/poktroll/x/application/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -316,7 +316,7 @@ func TestMsgServer_UndelegateFromGateway_DelegationIsActiveUntilNextSession(t *t // Verify that the gateway is added to the pending undelegation list with the // right sessionEndHeight as the map key. - sessionEndHeight := uint64(sessionkeeper.GetSessionEndBlockHeight(undelegationHeight)) + sessionEndHeight := uint64(shared.GetSessionEndBlockHeight(undelegationHeight)) require.Contains(t, app.PendingUndelegations[sessionEndHeight].GatewayAddresses, pendingUndelegateFromAddr, @@ -347,8 +347,7 @@ func TestMsgServer_UndelegateFromGateway_DelegationIsActiveUntilNextSession(t *t // Increment the block height past the tested session's grace period and run // the pruning undelegations logic again. - sessionGracePeriodBlockCount := uint64(sessionkeeper.GetSessionGracePeriodBlockCount()) - afterSessionGracePeriodHeight := int64(sessionEndHeight + sessionGracePeriodBlockCount + 1) + afterSessionGracePeriodHeight := int64(sessionEndHeight + shared.SessionGracePeriodBlocks + 1) sdkCtx = sdkCtx.WithBlockHeight(afterSessionGracePeriodHeight) k.EndBlockerPruneAppToGatewayPendingUndelegation(sdkCtx) @@ -385,7 +384,7 @@ func TestMsgServer_UndelegateFromGateway_DelegationIsPrunedAfterRetentionPeriod( // Verify that the the pending undelegation map no longer contains the // sessionEndHeight key. - sessionEndHeight := uint64(sessionkeeper.GetSessionEndBlockHeight(undelegationHeight)) + sessionEndHeight := uint64(shared.GetSessionEndBlockHeight(undelegationHeight)) require.Empty(t, app.PendingUndelegations[sessionEndHeight]) // Verify that the reconstructed delegatee gateway list can no longer include @@ -424,7 +423,7 @@ func TestMsgServer_UndelegateFromGateway_RedelegationAfterUndelegationAtTheSameS // Verify that the gateway is also present in the pending undelegation list with the // right sessionEndHeight as the map key. - sessionEndHeight := uint64(sessionkeeper.GetSessionEndBlockHeight(undelegationHeight)) + sessionEndHeight := uint64(shared.GetSessionEndBlockHeight(undelegationHeight)) require.Contains(t, app.PendingUndelegations[sessionEndHeight].GatewayAddresses, gatewayAddrToRedelegate, @@ -534,7 +533,7 @@ func createAppStakeDelegateAndUndelegate( // getUndelegationPruningBlockHeight returns the block height at which undelegations // should be pruned for a given undlegation block height. func getUndelegationPruningBlockHeight(blockHeight int64) (pruningHeihgt int64) { - nextSessionStartHeight := sessionkeeper.GetSessionEndBlockHeight(blockHeight) + 1 + nextSessionStartHeight := shared.GetSessionEndBlockHeight(blockHeight) + 1 return nextSessionStartHeight + keeper.GetNumBlocksUndelegationRetention() } diff --git a/x/application/keeper/prune_undelegations.go b/x/application/keeper/prune_undelegations.go index 77aae88da..2cf10aa47 100644 --- a/x/application/keeper/prune_undelegations.go +++ b/x/application/keeper/prune_undelegations.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) // NumSessionsAppToGatewayUndelegationRetention is the number of sessions for which @@ -45,6 +45,6 @@ func (k Keeper) EndBlockerPruneAppToGatewayPendingUndelegation(ctx sdk.Context) // GetNumBlocksUndelegationRetention returns the number of blocks for which // undelegations should be kept before being pruned. func GetNumBlocksUndelegationRetention() int64 { - return sessionkeeper.GetSessionGracePeriodBlockCount() + - (sessionkeeper.NumBlocksPerSession * NumSessionsAppToGatewayUndelegationRetention) + return shared.SessionGracePeriodBlocks + + (shared.NumBlocksPerSession * NumSessionsAppToGatewayUndelegationRetention) } diff --git a/x/proof/keeper/msg_server_create_claim_test.go b/x/proof/keeper/msg_server_create_claim_test.go index 371a763d5..5f7da9c31 100644 --- a/x/proof/keeper/msg_server_create_claim_test.go +++ b/x/proof/keeper/msg_server_create_claim_test.go @@ -13,8 +13,8 @@ import ( apptypes "github.com/pokt-network/poktroll/x/application/types" "github.com/pokt-network/poktroll/x/proof/keeper" "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -300,7 +300,7 @@ func newTestClaimMsg( Service: service, SessionId: sessionId, SessionStartBlockHeight: sessionStartHeight, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(sessionStartHeight), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(sessionStartHeight), }, merkleRoot, ) diff --git a/x/proof/keeper/msg_server_submit_proof.go b/x/proof/keeper/msg_server_submit_proof.go index 20c4f96fb..b7d05a439 100644 --- a/x/proof/keeper/msg_server_submit_proof.go +++ b/x/proof/keeper/msg_server_submit_proof.go @@ -19,8 +19,8 @@ import ( "github.com/pokt-network/poktroll/telemetry" "github.com/pokt-network/poktroll/x/proof/types" servicetypes "github.com/pokt-network/poktroll/x/service/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" ) // SMT specification used for the proof verification. @@ -440,13 +440,12 @@ func (k msgServer) validateClosestPath( // into account the heights, windows and grace periods into helper functions. // TODO_BLOCKER@(#516): Update `blockHeight` to be the value of when the `ProofWindow` // opens once the variable is added. - sessionEndBlockHeightWithGracePeriod := sessionHeader.GetSessionEndBlockHeight() + - sessionkeeper.GetSessionGracePeriodBlockCount() - blockHash := k.sessionKeeper.GetBlockHash(ctx, sessionEndBlockHeightWithGracePeriod) + sessionGracePeriodEndHeight := shared.GetSessionGracePeriodEndHeight(sessionHeader.GetSessionEndBlockHeight()) + blockHash := k.sessionKeeper.GetBlockHash(ctx, sessionGracePeriodEndHeight) // TODO: Investigate "proof for the path provided does not match one expected by the on-chain protocol" // error that may occur due to block height differing from the off-chain part. - fmt.Println("E2E_DEBUG: height for block hash when verifying the proof", sessionEndBlockHeightWithGracePeriod, sessionHeader.GetSessionId()) + fmt.Println("E2E_DEBUG: height for block hash when verifying the proof", sessionGracePeriodEndHeight, sessionHeader.GetSessionId()) expectedProofPath := GetPathForProof(blockHash, sessionHeader.GetSessionId()) if !bytes.Equal(proof.Path, expectedProofPath) { diff --git a/x/proof/keeper/msg_server_submit_proof_test.go b/x/proof/keeper/msg_server_submit_proof_test.go index 569c18c6e..dcad1c395 100644 --- a/x/proof/keeper/msg_server_submit_proof_test.go +++ b/x/proof/keeper/msg_server_submit_proof_test.go @@ -33,8 +33,8 @@ import ( "github.com/pokt-network/poktroll/x/proof/keeper" "github.com/pokt-network/poktroll/x/proof/types" servicetypes "github.com/pokt-network/poktroll/x/service/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -1066,7 +1066,7 @@ func createClaimAndStoreBlockHash( // into account the heights, windows and grace periods into helper functions. proofSubmissionHeight := claimMsg.GetSessionHeader().GetSessionEndBlockHeight() + - sessionkeeper.GetSessionGracePeriodBlockCount() + shared.SessionGracePeriodBlocks // Set block height to be after the session grace period. blockHeightCtx := keepertest.SetBlockHeight(ctx, proofSubmissionHeight) diff --git a/x/proof/keeper/proof_test.go b/x/proof/keeper/proof_test.go index fb893c5d3..c72f32bbe 100644 --- a/x/proof/keeper/proof_test.go +++ b/x/proof/keeper/proof_test.go @@ -13,8 +13,8 @@ import ( "github.com/pokt-network/poktroll/testutil/sample" "github.com/pokt-network/poktroll/x/proof/keeper" "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -37,7 +37,7 @@ func createNProofs(keeper keeper.Keeper, ctx context.Context, n int) []types.Pro Service: &sharedtypes.Service{Id: testServiceId}, SessionId: fmt.Sprintf("session-%d", i), SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, ClosestMerkleProof: nil, } diff --git a/x/proof/module/helpers_test.go b/x/proof/module/helpers_test.go index 1d4ed38ed..b8588e554 100644 --- a/x/proof/module/helpers_test.go +++ b/x/proof/module/helpers_test.go @@ -23,8 +23,8 @@ import ( apptypes "github.com/pokt-network/poktroll/x/application/types" proof "github.com/pokt-network/poktroll/x/proof/module" "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" suppliertypes "github.com/pokt-network/poktroll/x/supplier/types" ) @@ -130,7 +130,7 @@ func networkWithClaimObjects( claim := createClaim( t, net, ctx, supplierAcct.Address.String(), - sessionkeeper.GetSessionStartBlockHeight(blockHeight), + shared.GetSessionStartBlockHeight(blockHeight), appAcct.Address.String(), ) claims = append(claims, *claim) @@ -160,7 +160,7 @@ func encodeSessionHeader( Service: &sharedtypes.Service{Id: testServiceId}, SessionId: sessionId, SessionStartBlockHeight: sessionStartHeight, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(sessionStartHeight), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(sessionStartHeight), } cdc := codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) sessionHeaderBz := cdc.MustMarshalJSON(sessionHeader) @@ -210,7 +210,7 @@ func createClaim( Service: &sharedtypes.Service{Id: testServiceId}, SessionId: sessionId, SessionStartBlockHeight: sessionStartHeight, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(sessionStartHeight), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(sessionStartHeight), }, RootHash: rootHash, } diff --git a/x/proof/module/query_claim_test.go b/x/proof/module/query_claim_test.go index f4e2597bd..b941ea8b0 100644 --- a/x/proof/module/query_claim_test.go +++ b/x/proof/module/query_claim_test.go @@ -16,7 +16,7 @@ import ( _ "github.com/pokt-network/poktroll/testutil/testpolylog" proof "github.com/pokt-network/poktroll/x/proof/module" "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" ) func TestClaim_Show(t *testing.T) { @@ -128,12 +128,12 @@ func TestClaim_List(t *testing.T) { // independent constant, which requires us to temporarily align the // with the num blocks per session. See the `forloop` in `networkWithClaimObjects` // that has a TODO_HACK as well. - require.Equal(t, 0, numSuppliers*numApps%sessionkeeper.NumBlocksPerSession) + require.Equal(t, 0, numSuppliers*numApps%shared.NumBlocksPerSession) - numSessions := numSuppliers * numApps / sessionkeeper.NumBlocksPerSession + numSessions := numSuppliers * numApps / shared.NumBlocksPerSession // Submitting one claim per block for simplicity - numClaimsPerSession := sessionkeeper.NumBlocksPerSession + numClaimsPerSession := shared.NumBlocksPerSession totalClaims := numSessions * numClaimsPerSession net, claims := networkWithClaimObjects(t, numSessions, numSuppliers, numApps) diff --git a/x/proof/types/message_submit_proof_test.go b/x/proof/types/message_submit_proof_test.go index 6c5b98abd..d05419e38 100644 --- a/x/proof/types/message_submit_proof_test.go +++ b/x/proof/types/message_submit_proof_test.go @@ -7,8 +7,8 @@ import ( "github.com/stretchr/testify/require" "github.com/pokt-network/poktroll/testutil/sample" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -30,7 +30,7 @@ func TestMsgSubmitProof_ValidateBasic(t *testing.T) { Service: testService, SessionId: "mock_session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, Proof: testClosestMerkleProof, }, @@ -49,7 +49,7 @@ func TestMsgSubmitProof_ValidateBasic(t *testing.T) { Service: testService, SessionId: "mock_session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, Proof: testClosestMerkleProof, }, @@ -68,7 +68,7 @@ func TestMsgSubmitProof_ValidateBasic(t *testing.T) { Service: &sharedtypes.Service{Id: ""}, SessionId: "mock_session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, Proof: testClosestMerkleProof, }, @@ -83,7 +83,7 @@ func TestMsgSubmitProof_ValidateBasic(t *testing.T) { Service: testService, SessionId: "mock_session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, Proof: testClosestMerkleProof, }, diff --git a/x/session/keeper/session_hydrator.go b/x/session/keeper/session_hydrator.go index 67fc6b1a5..cba24a8e0 100644 --- a/x/session/keeper/session_hydrator.go +++ b/x/session/keeper/session_hydrator.go @@ -12,6 +12,7 @@ import ( _ "golang.org/x/crypto/sha3" "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedhelpers "github.com/pokt-network/poktroll/x/shared/helpers" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" ) @@ -20,11 +21,6 @@ var SHA3HashLen = crypto.SHA3_256.Size() // TODO_BLOCKER(#21): Make these configurable governance param const ( - // TODO_BLOCKER: Remove direct usage of these constants in helper functions - // when they will be replaced by governance params - NumBlocksPerSession = 4 - // Duration of the grace period in number of sessions - SessionGracePeriod = 1 NumSupplierPerSession = 15 SessionIDComponentDelimiter = "." ) @@ -103,11 +99,11 @@ func (k Keeper) hydrateSessionMetadata(ctx context.Context, sh *sessionHydrator) ) } - sh.session.NumBlocksPerSession = NumBlocksPerSession - sh.session.SessionNumber = GetSessionNumber(sh.blockHeight) + sh.session.NumBlocksPerSession = shared.NumBlocksPerSession + sh.session.SessionNumber = shared.GetSessionNumber(sh.blockHeight) - sh.sessionHeader.SessionStartBlockHeight = GetSessionStartBlockHeight(sh.blockHeight) - sh.sessionHeader.SessionEndBlockHeight = GetSessionEndBlockHeight(sh.blockHeight) + sh.sessionHeader.SessionStartBlockHeight = shared.GetSessionStartBlockHeight(sh.blockHeight) + sh.sessionHeader.SessionEndBlockHeight = shared.GetSessionEndBlockHeight(sh.blockHeight) return nil } @@ -267,39 +263,6 @@ func sha3Hash(bz []byte) []byte { return hasher.Sum(nil) } -// GetSessionStartBlockHeight returns the block height at which the session starts -// Returns 0 if the block height is not a consensus produced block. -// Example: If NumBlocksPerSession == 4, sessions start at blocks 1, 5, 9, etc. -func GetSessionStartBlockHeight(blockHeight int64) int64 { - if blockHeight <= 0 { - return 0 - } - return blockHeight - ((blockHeight - 1) % NumBlocksPerSession) -} - -// GetSessionEndBlockHeight returns the block height at which the session ends -// Returns 0 if the block height is not a consensus produced block. -// Example: If NumBlocksPerSession == 4, sessions end at blocks 4, 8, 11, etc. -func GetSessionEndBlockHeight(blockHeight int64) int64 { - if blockHeight <= 0 { - return 0 - } - - return GetSessionStartBlockHeight(blockHeight) + NumBlocksPerSession - 1 -} - -// GetSessionNumber returns the session number given the block height. -// Returns session number 0 if the block height is not a consensus produced block. -// Returns session number 1 for block 1 to block NumBlocksPerSession - 1 (inclusive). -// i.e. If NubBlocksPerSession == 4, session == 1 for [1, 4], session == 2 for [5, 8], etc. -func GetSessionNumber(blockHeight int64) int64 { - if blockHeight <= 0 { - return 0 - } - - return ((blockHeight - 1) / NumBlocksPerSession) + 1 -} - // GetSessionId returns the string and bytes representation of the sessionId // given the application public key, service ID, block hash, and block height // that is used to get the session start block height. @@ -325,16 +288,10 @@ func GetSessionId( return sessionId, sessionIdBz } -// GetSessionGracePeriodBlockCount returns the number of blocks in the session -// grace period. -func GetSessionGracePeriodBlockCount() int64 { - return SessionGracePeriod * NumBlocksPerSession -} - // getSessionStartBlockHeightBz returns the bytes representation of the session // start block height given the block height. func getSessionStartBlockHeightBz(blockHeight int64) []byte { - sessionStartBlockHeight := GetSessionStartBlockHeight(blockHeight) + sessionStartBlockHeight := shared.GetSessionStartBlockHeight(blockHeight) sessionStartBlockHeightBz := make([]byte, 8) binary.LittleEndian.PutUint64(sessionStartBlockHeightBz, uint64(sessionStartBlockHeight)) return sessionStartBlockHeightBz diff --git a/x/shared/session.go b/x/shared/session.go new file mode 100644 index 000000000..5240059a5 --- /dev/null +++ b/x/shared/session.go @@ -0,0 +1,65 @@ +package shared + +// NumBlocksPerSession is a place-holder that will be removed once the respective governance +// parameter is implemented. +// +// TODO_BLOCKER(#517): Remove direct usage of these constants in helper functions +// when they will be replaced by governance params +const NumBlocksPerSession = 4 + +// SessionGracePeriodBlocks is the number of blocks after the session ends before the +// "session grace period" is considered to have elapsed. +// +// TODO_BLOCKER: This is a place-holder that will be removed once the respective +// governance parameter is implemented. +const SessionGracePeriodBlocks = 4 + +// GetSessionStartBlockHeight returns the block height at which the session starts +// Returns 0 if the block height is not a consensus produced block. +// Example: If NumBlocksPerSession == 4, sessions start at blocks 1, 5, 9, etc. +func GetSessionStartBlockHeight(blockHeight int64) int64 { + if blockHeight <= 0 { + return 0 + } + + // TODO_BLOCKER(#543): If the num_blocks_per_session param has ever been changed, + // this function may cause unexpected behavior. + return blockHeight - ((blockHeight - 1) % NumBlocksPerSession) +} + +// GetSessionEndBlockHeight returns the block height at which the session ends +// Returns 0 if the block height is not a consensus produced block. +// Example: If NumBlocksPerSession == 4, sessions end at blocks 4, 8, 11, etc. +func GetSessionEndBlockHeight(blockHeight int64) int64 { + if blockHeight <= 0 { + return 0 + } + + return GetSessionStartBlockHeight(blockHeight) + NumBlocksPerSession - 1 +} + +// GetSessionNumber returns the session number given the block height. +// Returns session number 0 if the block height is not a consensus produced block. +// Returns session number 1 for block 1 to block NumBlocksPerSession - 1 (inclusive). +// i.e. If NubBlocksPerSession == 4, session == 1 for [1, 4], session == 2 for [5, 8], etc. +func GetSessionNumber(blockHeight int64) int64 { + if blockHeight <= 0 { + return 0 + } + + // TODO_BLOCKER(#543): If the num_blocks_per_session param has ever been changed, + // this function may cause unexpected behavior. + return ((blockHeight - 1) / NumBlocksPerSession) + 1 +} + +// GetSessionGracePeriodEndHeight returns the block height at which the grace period +// for the session ending with sessionEndHeight elapses. +func GetSessionGracePeriodEndHeight(sessionEndHeight int64) int64 { + return sessionEndHeight + SessionGracePeriodBlocks +} + +// IsGracePeriodElapsed returns true if the grace period for the session ending with +// sessionEndHeight has elapsed, given currentHeight. +func IsGracePeriodElapsed(sessionEndHeight, currentHeight int64) bool { + return currentHeight > GetSessionGracePeriodEndHeight(sessionEndHeight) +} diff --git a/x/shared/types/types.go b/x/shared/types/types.go index ab1254f4c..78d9ec9f9 100644 --- a/x/shared/types/types.go +++ b/x/shared/types/types.go @@ -1 +1,3 @@ package types + +// This file is in place to declare the package for dynamically generated protobufs diff --git a/x/tokenomics/keeper/keeper_test.go b/x/tokenomics/keeper/keeper_test.go index f5d7f527a..3fdd0dd88 100644 --- a/x/tokenomics/keeper/keeper_test.go +++ b/x/tokenomics/keeper/keeper_test.go @@ -18,8 +18,8 @@ import ( "github.com/pokt-network/poktroll/testutil/sample" apptypes "github.com/pokt-network/poktroll/x/application/types" prooftypes "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" tokenomicskeeper "github.com/pokt-network/poktroll/x/tokenomics/keeper" tokenomicstypes "github.com/pokt-network/poktroll/x/tokenomics/types" @@ -60,7 +60,7 @@ func (s *TestSuite) SetupTest() { Service: &sharedtypes.Service{Id: testServiceId}, SessionId: "session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, RootHash: smstRootWithSum(69), } diff --git a/x/tokenomics/keeper/settle_pending_claims.go b/x/tokenomics/keeper/settle_pending_claims.go index a8600264c..59c87aa38 100644 --- a/x/tokenomics/keeper/settle_pending_claims.go +++ b/x/tokenomics/keeper/settle_pending_claims.go @@ -8,7 +8,7 @@ import ( "github.com/pokt-network/poktroll/telemetry" prooftypes "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" + "github.com/pokt-network/poktroll/x/shared" "github.com/pokt-network/poktroll/x/tokenomics/types" ) @@ -129,7 +129,7 @@ func (k Keeper) getExpiringClaims(ctx sdk.Context) (expiringClaims []prooftypes. // TODO_BLOCKER: query the on-chain governance parameter once available. // `* 3` is just a random factor Olshansky added for now to make sure expiration // doesn't happen immediately after a session's grace period is complete. - submitProofWindowEndHeight := sessionkeeper.GetSessionGracePeriodBlockCount() * 3 + submitProofWindowEndHeight := shared.SessionGracePeriodBlocks * int64(3) // TODO_BLOCKER(@Olshansk): Optimize this by indexing claims appropriately // and only retrieving the claims that need to be settled rather than all diff --git a/x/tokenomics/keeper/settle_session_accounting_test.go b/x/tokenomics/keeper/settle_session_accounting_test.go index c96934128..528250aa5 100644 --- a/x/tokenomics/keeper/settle_session_accounting_test.go +++ b/x/tokenomics/keeper/settle_session_accounting_test.go @@ -14,8 +14,8 @@ import ( "github.com/pokt-network/poktroll/testutil/sample" apptypes "github.com/pokt-network/poktroll/x/application/types" prooftypes "github.com/pokt-network/poktroll/x/proof/types" - sessionkeeper "github.com/pokt-network/poktroll/x/session/keeper" sessiontypes "github.com/pokt-network/poktroll/x/session/types" + "github.com/pokt-network/poktroll/x/shared" sharedtypes "github.com/pokt-network/poktroll/x/shared/types" tokenomicstypes "github.com/pokt-network/poktroll/x/tokenomics/types" ) @@ -52,7 +52,7 @@ func TestSettleSessionAccounting_HandleAppGoingIntoDebt(t *testing.T) { }, SessionId: "session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, RootHash: smstRootWithSum(appStake.Amount.Uint64() + 1), // More than the app stake } @@ -93,7 +93,7 @@ func TestSettleSessionAccounting_AppNotFound(t *testing.T) { }, SessionId: "session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, RootHash: smstRootWithSum(42), } @@ -297,7 +297,7 @@ func baseClaim(appAddr, supplierAddr string, sum uint64) prooftypes.Claim { }, SessionId: "session_id", SessionStartBlockHeight: 1, - SessionEndBlockHeight: sessionkeeper.GetSessionEndBlockHeight(1), + SessionEndBlockHeight: shared.GetSessionEndBlockHeight(1), }, RootHash: smstRootWithSum(sum), }