relayer

package
v0.1.34 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// General proxy sync flow
	InstructionInitRequestLogger                      string = "init_request_logger"
	InstructionGetStartBlock                          string = "get_start_block"
	InstructionSetContextValueComponentKind           string = "set_context_value_component_kind"
	InstructionChainHeadProbabilisticDebugInfo        string = "chain_head_probabilistic_debug_info"
	InstructionHandlingRequestProbabilisticDebugInfo  string = "handling_request_probabilistic_debug_info"
	InstructionDebugRelayRequestExtraction            string = "debug_relay_request_extraction"
	InstructionNewRelayRequest                        string = "new_relay_request"
	InstructionRelayRequestBasicValidation            string = "relay_request_basic_validation"
	InstructionLoggerWithRequestDetails               string = "logger_with_request_details"
	InstructionGetAvailableSuppliers                  string = "get_available_suppliers"
	InstructionCheckSupplierAvailable                 string = "check_supplier_available"
	InstructionDetermineRequestTimeoutForServiceID    string = "determine_request_timeout_for_service_id"
	InstructionSetContextDeadline                     string = "set_context_deadline"
	InstructionSetResponseControllerWriteDeadline     string = "set_response_controller_write_deadline"
	InstructionEagerCheckRateLimiting                 string = "eager_check__rate_limiting"
	InstructionGetServiceConfig                       string = "get_service_config"
	InstructionLoggerWithServiceDetails               string = "logger_with_service_details"
	InstructionPreRequestVerification                 string = "pre_request_verification"
	InstructionPostRequestVerification                string = "post_request_verification"
	InstructionBuildServiceBackendRequest             string = "build_service_backend_request"
	InstructionSetRequestTimeoutWithRemainingTime     string = "set_request_timeout_with_remaining_time"
	InstructionHTTPClientDo                           string = "http_client_do"
	InstructionDeferCloseResponseBodyAndCaptureSvcDur string = "defer_close_response_body_and_capture_service_duration"
	InstructionSerializeHTTPResponse                  string = "serialize_http_response"
	InstructionCheckDeadlineBeforeResponse            string = "check_deadline_before_response"
	InstructionRelayResponseGenerated                 string = "relay_response_generated"
	InstructionLoggerWithResponsePreparation          string = "logger_with_response_preparation"
	InstructionResponseSent                           string = "response_sent"
)

Instruction labels for metrics.

Variables

View Source
var (
	// RelaysTotal is a Counter metric for the total requests processed by the relay miner.
	// It increments to track proxy requests and is labeled by 'service_id',
	// essential for monitoring load and traffic on different proxies and services.
	//
	// Usage:
	// - Monitor total request load.
	// - Compare requests across services or proxies.
	RelaysTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      requestsTotal,
		Help:      "Total number of requests processed, labeled by service ID.",
	}, []string{"service_id", "supplier_operator_address"})

	// RelaysErrorsTotal is a Counter for total error events in the relay miner.
	// It increments with each error, labeled by 'service_id',
	// crucial for pinpointing error-prone areas for reliability improvement.
	//
	// Usage:
	// - Track and analyze error types and distribution.
	// - Compare error rates for reliability analysis.
	RelaysErrorsTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      requestsErrorsTotal,
		Help:      "Total number of error events.",
	}, []string{"service_id"})

	// RelaysSuccessTotal is a Counter metric for successful requests in the relay miner.
	// It increments with each successful request, labeled by 'service_id'.
	RelaysSuccessTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      requestsSuccessTotal,
		Help:      "Total number of successful requests processed, labeled by service ID.",
	}, []string{"service_id"})

	// RelaysDurationSeconds observes the end-to-end duration of the request in the relay miner.
	//
	// It includes the duration of the request to the backend service/data node AS WELL AS
	// the duration of the RelayMiner's internal overhead.
	//
	// Usage:
	// - Analyze typical response times and long-tail latency issues.
	// - Compare performance across services or environments.
	RelaysDurationSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      relayDurationSeconds,
		Help:      "Histogram of request durations for performance analysis.",
		Buckets:   defaultBuckets,
	}, []string{"service_id", "status_code"})

	// ServiceDurationSeconds observes the duration of the request to the backend service/data node outside of the RelayMiner.
	//
	// This histogram, labeled by 'service_id' and 'status_code', measures response times,
	// vital for performance analysis under different loads.
	//
	// It is a complementary metric to RelaysDurationSeconds allowing to isolate the
	// performance of the data node and the overhead of the RelayMiner's internal processing.
	//
	// Usage:
	// - Analyze typical response times and long-tail latency issues.
	// - Compare performance across services or environments.
	ServiceDurationSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      serviceDurationSeconds,
		Help:      "Histogram of service call durations for performance analysis.",
		Buckets:   defaultBuckets,
	}, []string{"service_id", "status_code"})

	// TODO_TECHDEBT: Remove those metrics once the session rollover issue is resolved.
	// RelayRequestPreparationDurationSeconds observes the duration of preparing
	// a relay request from an HTTP request.
	//
	// This histogram, labeled by 'service_id', measures the time taken to prepare
	// a relay request, which includes unmarshaling the request body and preparing
	// the RelayRequest structure.
	// Usage:
	// - Analyze the time taken to prepare relay requests.
	// - Identify potential bottlenecks in request preparation.
	RelayRequestPreparationDurationSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      requestPreparationDurationSeconds,
		Help:      "Histogram of relay request preparation durations in seconds.",
		Buckets:   defaultBuckets,
	}, []string{"service_id"})

	// TODO_TECHDEBT: Remove those metrics once the session rollover issue is resolved.
	// RelayResponsePreparationDurationSeconds observes the duration of preparing
	// a relay response from the the service's HTTP response.
	//
	// This histogram, labeled by 'service_id', measures the time taken to prepare
	// a relay response, which includes marshaling the response body and preparing
	// the RelayResponse structure.
	// Usage:
	// - Analyze the time taken to prepare relay responses.
	// - Identify potential bottlenecks in response preparation.
	RelayResponsePreparationDurationSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      responsePreparationDurationSeconds,
		Help:      "Histogram of relay response preparation durations in seconds.",
		Buckets:   defaultBuckets,
	}, []string{"service_id"})

	// FullNodeGRPCCallDurationSeconds is a histogram metric for measuring the duration of gRPC calls.
	//
	// It is labeled by 'component' (e.g., miner, proxy) and 'method', capturing the time taken for each call.
	// This metric is essential for performance monitoring and analysis of gRPC interactions.
	// Usage:
	// - Monitor gRPC call performance.
	// - Identify slow or problematic calls.
	FullNodeGRPCCallDurationSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      fullNodeGRPCCallDurationSeconds,
		Help:      "Histogram of gRPC call durations for performance analysis.",
		Buckets:   defaultBuckets,
	}, []string{"component", "method"})

	// RelayResponseSizeBytes is a histogram metric for observing response size distribution.
	// It counts responses in bytes, with buckets:
	// - 100 bytes to 50,000 bytes, capturing a range from small to large responses.
	// This data helps in accurately representing response size distribution and is vital
	// for performance tuning.
	//
	// TODO_TECHDEBT: Consider configuring bucket sizes externally for flexible adjustments
	// in response to different data patterns or deployment scenarios.
	RelayResponseSizeBytes = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      responseSizeBytes,
		Help:      "Histogram of response sizes in bytes for performance analysis.",
		Buckets:   []float64{100, 500, 1000, 5000, 10000, 50000},
	}, []string{"service_id"})

	// RelayRequestSizeBytes is a histogram metric for observing request size distribution.
	// It counts requests in bytes, with buckets:
	// - 100 bytes to 50,000 bytes, capturing a range from small to large requests.
	// This data helps in accurately representing request size distribution and is vital
	// for performance tuning.
	RelayRequestSizeBytes = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      requestSizeBytes,
		Help:      "Histogram of request sizes in bytes for performance analysis.",
		Buckets:   []float64{100, 500, 1000, 5000, 10000, 50000},
	}, []string{"service_id"})

	// DelayedRelayRequestValidationTotal is a Counter metric for tracking delayed validation occurrences.
	// It increments when relay requests are validated after being served (late validation)
	// rather than being validated upfront. This indicates sessions that weren't known at
	// request time and required deferred validation.
	DelayedRelayRequestValidationTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      delayedRelayRequestValidationTotal,
		Help:      "Total number of delayed validation occurrences, labeled by service ID.",
	}, []string{"service_id", "supplier_operator_address"})

	// DelayedRelayRequestValidationFailuresTotal is a Counter metric for tracking delayed validation failures.
	// It increments when relay requests fail validation during the delayed validation process.
	// This typically occurs when the relay request signature is invalid or session validation
	// fails after the relay has already been served.
	DelayedRelayRequestValidationFailuresTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      delayedRelayRequestValidationFailuresTotal,
		Help:      "Total number of delayed validation failures, labeled by service ID.",
	}, []string{"service_id", "supplier_operator_address"})

	// DelayedRelayRequestRateLimitingCheckTotal is a Counter metric for tracking rate limiting during delayed validation.
	// It increments when, during late (deferred) validation, the application is found to have
	// exceeded its allocated stake and the relay is rate limited.
	//
	// User/payment impact:
	// - The relay becomes reward-ineligible (no on-chain payment to the supplier for this relay).
	// - Signals potential fee leakage and helps rate-limit thresholds.
	DelayedRelayRequestRateLimitingCheckTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      delayedRelayRequestRateLimitingCheckTotal,
		Help:      "Total number of delayed validation rate limiting events, labeled by service ID.",
	}, []string{"service_id", "supplier_operator_address"})

	// BlockHeightCurrent is a Gauge metric for tracking the current block height.
	// It is updated each time a new block is received by the RelayMiner.
	// This metric enables monitoring of block progression over time and detecting
	// when block updates have stalled.
	//
	// Usage:
	// - Monitor block height progression over time in Grafana
	// - Detect block update stalls by checking for flat lines
	// - Alert when block height hasn't updated in expected timeframe
	BlockHeightCurrent = prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{
		Subsystem: relayMinerProcess,
		Name:      blockHeightCurrent,
		Help:      "Current block height observed by the RelayMiner.",
	}, []string{})

	// InstructionTimeSeconds is a Histogram metric for tracking the duration of individual
	// instructions during relay processing. It measures the time between consecutive
	// instruction steps to identify performance bottlenecks and optimize relay handling.
	// The metric is labeled by instruction name to provide granular timing analysis.
	InstructionTimeSeconds = prometheus.NewHistogramFrom(stdprometheus.HistogramOpts{
		Subsystem: relayMinerProcess,
		Name:      instructionTimeSeconds,
		Help:      "Histogram of request instruction times in milliseconds for performance analysis.",
		Buckets:   defaultBuckets,
	}, []string{"instruction"})

	// RelaysDroppedTotal is a Counter metric for relays that were served to the
	// client but DROPPED from the mining pipeline (never added to the session tree).
	//
	// A dropped relay is permanently lost reward: the supplier did the work but will
	// not be compensated on-chain because no evidence enters the SMST.
	// It is labeled by 'service_id', 'supplier_operator_address', and 'reason'
	// (e.g. "mining_channel_full") to quantify and localize reward leakage under load.
	//
	// Usage:
	// - Alert when nonzero: it directly measures unpaid work.
	// - Correlate with throughput to size mining pipeline buffers/workers.
	RelaysDroppedTotal = prometheus.NewCounterFrom(stdprometheus.CounterOpts{
		Subsystem: relayMinerProcess,
		Name:      relaysDroppedTotal,
		Help:      "Total number of served relays dropped from the mining pipeline (lost reward), labeled by service ID, supplier, and reason.",
	}, []string{"service_id", "supplier_operator_address", "reason"})
)

Functions

func BuildServiceBackendRequest added in v0.0.13

func BuildServiceBackendRequest(
	relayRequest *types.RelayRequest,
	serviceConfig *config.RelayMinerSupplierServiceConfig,
) (*http.Request, error)

BuildServiceBackendRequest builds the service backend request from the relay request and the service configuration.

func CaptureBlockHeight added in v0.1.30

func CaptureBlockHeight(height int64)

CaptureBlockHeight updates the block height gauge with the current block height. This metric is used to monitor block progression over time and detect stalled block updates.

func CaptureDelayedRelayRequestRateLimitingCheck added in v0.1.30

func CaptureDelayedRelayRequestRateLimitingCheck(serviceId string, supplierOperatorAddress string)

CaptureDelayedRelayRequestRateLimitingCheck records a rate limiting event during delayed validation. This metric is incremented when relay requests are rate limited during the delayed validation process, typically when the application exceeds its allocated stake during delayed validation checks.

func CaptureDelayedRelayRequestValidation added in v0.1.30

func CaptureDelayedRelayRequestValidation(serviceId string, supplierOperatorAddress string)

CaptureDelayedRelayRequestValidation records a delayed validation occurrence. This metric is incremented when relay requests are validated after being served (late validation) rather than being validated upfront. This indicates sessions that weren't known at request time and required deferred validation.

func CaptureDelayedRelayRequestValidationFailure added in v0.1.30

func CaptureDelayedRelayRequestValidationFailure(serviceId string, supplierOperatorAddress string)

CaptureDelayedRelayRequestValidationFailure records a delayed validation failure event. This metric is incremented when a relay request fails validation during the delayed validation process, typically due to invalid signature or session validation failure after the relay has already been served.

func CaptureDroppedRelay added in v0.1.34

func CaptureDroppedRelay(serviceId, supplierOperatorAddress, reason string)

CaptureDroppedRelay records a relay that was served to the client but dropped from the mining pipeline (i.e. never added to the session tree), making it reward-ineligible. The reason localizes WHERE the drop happened (e.g. "mining_channel_full").

func CaptureGRPCCallDuration added in v0.1.28

func CaptureGRPCCallDuration(component, method string, startTime time.Time)

CaptureGRPCCallDuration records the duration of a gRPC call. It is labeled by component (e.g., miner, proxy) and method, capturing the time taken for the call.

func CaptureRelayDuration added in v0.1.23

func CaptureRelayDuration(serviceId string, startTime time.Time, statusCode int)

CaptureRelayDuration records the internal end-to-end duration of handling a relay which includes the network call to the backend data / service node. It calculates the elapsed time since the RelayMiner started processing the request BEFORE doing all of its internal processing.

func CaptureRequestPreparationDuration added in v0.1.28

func CaptureRequestPreparationDuration(serviceId string, startTime time.Time)

CaptureRequestPreparationDuration records the duration of the request reading and preparation before sending it to the backend service/data node. It is labeled by service ID and captures the time taken to process the request.

func CaptureResponsePreparationDuration added in v0.1.28

func CaptureResponsePreparationDuration(serviceId string, startTime time.Time)

CaptureResponsePreparationDuration records the duration of preparing the response after receiving it from the backend service/data node. It is labeled by service ID and captures the time taken to process the response.

func CaptureServiceDuration added in v0.1.23

func CaptureServiceDuration(serviceId string, startTime time.Time, statusCode int)

CaptureServiceDuration records the duration of a request to the backend data / service node explicitly. It is labeled by service ID and HTTP status code. It calculates the elapsed time since the RelayMiner started the outbound network call AFTER doing all of its internal processing.

func ForwardPocketHeaders added in v0.1.12

func ForwardPocketHeaders(header *http.Header, meta types.RelayRequestMetadata)

ForwardPocketHeaders adds Pocket-specific identity headers from the relay metadata to the HTTP request header. This helps with tracking and authentication at the service backend level.

func NewRelayMiner

func NewRelayMiner(ctx context.Context, deps depinject.Config) (*relayMiner, error)

NewRelayMiner creates a new Relayer instance with the given dependencies. It injects the dependencies into the Relayer instance and returns it.

Required dependencies:

  • RelayerProxy
  • Miner
  • RelayerSessionsManager

func RecordDurations added in v0.1.30

func RecordDurations(instructionTimestamps []*InstructionTimestamp)

RecordDurations calculates and records durations between consecutive instructions. - First instruction establishes baseline (no metric recorded) - Subsequent instructions record delta from previous instruction - Observes durations in InstructionTimeSeconds Prometheus histogram

Types

type InstructionTimer added in v0.1.30

type InstructionTimer struct {
	Timestamps []*InstructionTimestamp
}

InstructionTimer tracks a collection of instruction timing measurements. - Maintains slice of timestamps for relay processing instructions

func (*InstructionTimer) Record added in v0.1.30

func (it *InstructionTimer) Record(instruction string)

Record adds a new instruction timing entry with current timestamp.

type InstructionTimestamp added in v0.1.30

type InstructionTimestamp struct {
	// contains filtered or unexported fields
}

InstructionTimestamp represents a single timing measurement for an instruction. - Captures instruction identifier and timestamp during relay processing

type MinedRelay

type MinedRelay struct {
	types.Relay
	Bytes []byte
	Hash  []byte
}

MinedRelay is a wrapper around a relay that has been serialized and hashed.

type MinedRelaysObservable

type MinedRelaysObservable observable.Observable[*MinedRelay]

MinedRelaysObservable is an observable which is notified with MinedRelay values.

TODO_HACK: The purpose of this type is to work around gomock's lack of support for generic types. For the same reason, this type cannot be an alias (i.e. MinedRelaysObservable = observable.Observable[*MinedRelay]).

type Miner

type Miner interface {
	MinedRelays(
		ctx context.Context,
		servedRelayObs RelaysObservable,
	) (minedRelaysObs MinedRelaysObservable)
}

Miner is responsible for observing servedRelayObs, hashing and checking the difficulty of each, finally publishing those with sufficient difficulty to minedRelayObs as they are applicable for relay volume.

type MinerOption

type MinerOption func(Miner)

type RelayAuthenticator added in v0.0.13

type RelayAuthenticator interface {
	// VerifyRelayRequest verifies the relay request signature and session validity.
	VerifyRelayRequest(
		ctx context.Context,
		relayRequest *servicetypes.RelayRequest,
		serviceId string,
	) error

	// CheckRelayRewardEligibility verifies the Relay Request is still reward eligible.
	// This is done by:
	// - Retrieving the session header of the relay request
	// - Ensuring the current block height hasn't reached the beginning of the claim window
	// Returns an error if the relay is no longer eligible for rewards.
	CheckRelayRewardEligibility(ctx context.Context, relayRequest *servicetypes.RelayRequest) error

	// SignRelayResponse signs the relay response given a supplier operator address.
	SignRelayResponse(relayResponse *servicetypes.RelayResponse, supplierOperatorAddr string) error

	// GetSupplierOperatorAddresses returns the supplier operator addresses that
	// the relay authenticator can use to sign relay responses.
	GetSupplierOperatorAddresses() []string
}

RelayAuthenticator is the interface that authenticates the relay requests and responses (i.e. verifies the relay request signature and session validity, and signs the relay response).

type RelayAuthenticatorOption added in v0.0.13

type RelayAuthenticatorOption func(RelayAuthenticator)

type RelayMeter added in v0.0.11

type RelayMeter interface {
	// Start starts the relay meter.
	Start(ctx context.Context) error

	// IsOverServicing returns whether the relay would result in over-servicing the application.
	IsOverServicing(ctx context.Context, relayRequestMeta servicetypes.RelayRequestMetadata) bool

	// SetNonApplicableRelayReward updates the relay meter for the given relay request as
	// non-applicable between a single Application and a single Supplier for a single session.
	// The volume / reward applicability of the relay is unknown to the relay miner
	// until the relay is served and the relay response signed.
	SetNonApplicableRelayReward(ctx context.Context, relayRequestMeta servicetypes.RelayRequestMetadata)

	// AllowOverServicing returns true if the relay meter is configured to allow over-servicing.
	AllowOverServicing() bool
}

RelayMeter is an interface that keeps track of the amount of stake consumed between a single onchain Application and a single onchain Supplier over the course of a single session. It enables the RelayMiner to rate limit the number of requests handled offchain as a function of the optimistic onchain rate limits.

type RelayServer

type RelayServer interface {
	// Start starts the service server and returns an error if it fails.
	Start(ctx context.Context) error

	// Stop terminates the service server and returns an error if it fails.
	Stop(ctx context.Context) error

	// Ping tests the connection between the relay server and its backend URL.
	Ping(ctx context.Context) error
}

RelayServer is the interface of the advertised relay servers provided by the RelayerProxy.

type RelayServers added in v0.0.14

type RelayServers []RelayServer

RelayServers aggregates a slice of RelayServer interface.

type RelayerProxy

type RelayerProxy interface {
	// Start starts all advertised relay servers and returns an error if any of them fail to start.
	Start(ctx context.Context) error

	// Stop stops all advertised relay servers and returns an error if any of them fail.
	Stop(ctx context.Context) error

	// ServedRelays returns an observable that notifies the miner about the relays that have been served.
	// A served relay is one whose RelayRequest's signature and session have been verified,
	// and its RelayResponse has been signed and successfully sent to the client.
	ServedRelays() RelaysObservable

	// PingAll tests the connectivity between all the managed relay servers and their respective backend URLs.
	PingAll(ctx context.Context) error
}

RelayerProxy is the interface for the proxy that serves relays to the application. It is responsible for starting and stopping all supported RelayServers. While handling requests and responding in a closed loop, it also notifies the miner about the relays that have been served.

type RelayerProxyOption

type RelayerProxyOption func(RelayerProxy)

type RelayerSessionsManager

type RelayerSessionsManager interface {
	// InsertRelays receives an observable of relays that should be included
	// in their respective session's SMST (tree).
	InsertRelays(minedRelaysObs MinedRelaysObservable)

	// Start iterates over the session trees at the end of each, respective, session.
	// The session trees are piped through a series of map operations which progress
	// them through the claim/proof lifecycle, broadcasting transactions to  the
	// network as necessary.
	Start(ctx context.Context) error

	// Stop unsubscribes all observables from the InsertRelays observable which
	// will close downstream observables as they drain.
	//
	// TODO_TECHDEBT: Either add a mechanism to wait for draining to complete
	// and/or ensure that the state at each pipeline stage is persisted to disk
	// and exit as early as possible.
	Stop()

	// SessionTreesSnapshots returns a point-in-time view of all session trees the
	// manager is currently tracking.
	//
	// The snapshots are safe to iterate without holding the internal session tree
	// mutex, making it suitable for tests and diagnostics.
	//
	// DEV_NOTE: This is used for testing purposes only.
	SessionTreesSnapshots() []SessionTreeSnapshot
}

RelayerSessionsManager is responsible for managing the relayer's session lifecycles. It handles the creation and retrieval of SMSTs (trees) for a given session, as well as the respective and subsequent claim creation and proof submission. This is largely accomplished by pipelining observables of relays and sessions through a series of map operations.

type RelayerSessionsManagerOption

type RelayerSessionsManagerOption func(RelayerSessionsManager)

type RelaysObservable

type RelaysObservable observable.Observable[*servicetypes.Relay]

RelaysObservable is an observable which is notified with Relay values.

TODO_HACK: The purpose of this type is to work around gomock's lack of support for generic types. For the same reason, this type cannot be an alias (i.e. RelaysObservable = observable.Observable[*servicetypes.Relay]).

type SessionTree

type SessionTree interface {
	// GetSessionHeader returns the header of the session corresponding to the SMST.
	GetSessionHeader() *sessiontypes.SessionHeader

	// Update is a wrapper for the SMST's Update function. It updates the SMST with
	// the given key, value, and weight.
	// This function should be called when a Relay has been successfully served.
	Update(key, value []byte, weight uint64) error

	// ProveClosest is a wrapper for the SMST's ProveClosest function. It returns the
	// proof for the given path.
	// This function should be called several blocks after a session has been claimed and needs to be proven.
	ProveClosest(path []byte) (proof *smt.SparseCompactMerkleClosestProof, err error)

	// GetSMSTRoot returns the the current root hash of the SMST.
	// It differs from GetClaimRoot in that it always returns the latest root hash
	// of the SMST, while GetClaimRoot returns the root hash after the session tree
	// has been flushed to create the claim.
	GetSMSTRoot() smt.MerkleSumRoot

	// GetClaimRoot returns the root hash of the SMST needed for creating the claim.
	// It returns nil if the session tree has not been flushed yet.
	GetClaimRoot() []byte

	// GetProofBz returns the proof created by ProveClosest needed for submitting
	// a proof in byte format.
	GetProofBz() []byte

	// Flush should be used to safely free up resources used by the SMST without risking rewards.
	// Flush can be seen as a safe version of "Stop" which is explicitly not exposed by this interface.
	//
	// It does the following:
	// 1. Gets the root hash of the SMST needed for submitting the claim.
	// 2. Commits the entire tree to disk (if disk storage is used)
	// 3. Stops the KVStore.
	//
	// It should be called before submitting the claim onchain.
	// This function frees up the in-memory resources used by the SMST that are
	// no longer needed while waiting for the proof submission window to open.
	Flush() (SMSTRoot []byte, err error)

	// Close gracefully releases runtime resources associated with this session tree
	// without deleting any persisted evidence.
	// It ensures any buffered mined relay entries in the write-ahead log (WAL) are
	// flushed to disk and closes the underlying WAL file handle.
	Close() error

	// TODO_DISCUSS: This function should not be part of the interface as it is an optimization
	// aiming to free up KVStore resources after the proof is no longer needed.
	// Delete deletes the SMST from the KVStore.
	// WARNING: This function should be called only after the proof has been successfully
	// submitted onchain and the servicer has confirmed that it has been rewarded.
	Delete() error

	// StartClaiming marks the session tree as being picked up for claiming,
	// so it won't be picked up by the relayer again.
	// It returns an error if it has already been marked as such.
	StartClaiming() error

	// GetSupplierOperatorAddress returns a stringified bech32 address of the supplier
	// operator this sessionTree belongs to.
	GetSupplierOperatorAddress() string

	// GetTrieSpec returns the trie spec of the SMST.
	GetTrieSpec() smt.TrieSpec
}

SessionTree is an interface that wraps an SMST (Sparse Merkle State Trie) and its corresponding session.

type SessionTreeSnapshot added in v0.1.30

type SessionTreeSnapshot struct {
	SupplierOperatorAddress string
	SessionEndHeight        int64
	SessionID               string
	Tree                    SessionTree
}

SessionTreeSnapshot captures the identifying information for a session tree along with the tree itself.

It is intended for diagnostic and testing scenarios where the caller needs a consistent view of the manager's current session state without reaching into its internal maps.

DEV_NOTE: This is used for testing purposes only.

Directories

Path Synopsis
Package cmd provides the command-line interface for the RelayMiner.
Package cmd provides the command-line interface for the RelayMiner.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL