Documentation
¶
Index ¶
- Constants
- Variables
- func AddRollingLogConfig(cmd *cobra.Command)
- func BaseTimePerCU(cu uint64) time.Duration
- func CapContextTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)
- func CompressData(data []byte, threshold int) ([]byte, bool, error)
- func ContextOutOfTime(ctx context.Context) bool
- func CreateRestMethodNotFoundError(fiberCtx *fiber.Ctx, chainId string) error
- func DecompressData(compressedData []byte) ([]byte, error)
- func FindSequenceNumber(sequence string) (int, error)
- func GetExtensionNames(extensionCollection []*spectypes.Extension) (extensions []string)
- func GetIpFromGrpcContext(ctx context.Context) string
- func GetRemainingTimeoutFromContext(ctx context.Context) (timeRemaining time.Duration)
- func GetTimePerCu(cu uint64) time.Duration
- func GetTimeoutForProcessing(relayTimeout time.Duration, timeoutInfo TimeoutInfo) time.Duration
- func GetTokenFromGrpcContext(ctx context.Context) string
- func GetUniqueToken(userData UserData) string
- func IsQuoted(s string) bool
- func IsSolanaNonRetryableError(errorMessage string) bool
- func IsSolanaNonRetryableErrorBytes(errorMessage []byte) bool
- func IsSquareBracketed(s string) bool
- func IsTestMode(ctx context.Context) bool
- func IsTimeout(errArg error) bool
- func IsUnsupportedMethodErrorMessageBytes(errorMessage []byte) bool
- func IsUnsupportedMethodMessage(errorMessage string) bool
- func LocalNodeTimePerCu(cu uint64) time.Duration
- func OptimizedHttpClient() *http.Client
- func OptimizedHttpTransport() *http.Transport
- func ParseEndpointArgs(endpoint_strings, yaml_config_properties []string, endpointsConfigName string) (viper_endpoints *viper.Viper, err error)
- func SetupRollingLogger() func()
- func SharedHttpTransport() *http.Transport
- func UnSquareBracket(s string) string
- func ValidateEndpoint(endpoint, apiInterface string) error
- func VerifyAndHandleUnsupportedFlags(currentFlags *pflag.FlagSet) error
- type AuthConfig
- type ChainMessageGetApiInterface
- type ConflictHandlerInterface
- type ConsumerCmdFlags
- type CrossValidationParams
- type EpochTimer
- func (et *EpochTimer) CalculateCurrentEpoch() uint64
- func (et *EpochTimer) GetCurrentEpoch() uint64
- func (et *EpochTimer) GetEpochBoundaryTime(epoch uint64) time.Time
- func (et *EpochTimer) GetEpochDuration() time.Duration
- func (et *EpochTimer) GetTimeUntilNextEpoch() time.Duration
- func (et *EpochTimer) RegisterCallback(callback func(uint64))
- func (et *EpochTimer) Start(ctx context.Context)
- func (et *EpochTimer) Stop()
- type JsonRPCError
- type JsonRPCErrorMessage
- type NodeUrl
- func (url *NodeUrl) GetAuthHeaders() map[string]string
- func (url *NodeUrl) LowerContextTimeout(ctx context.Context, processingTimeout time.Duration) (context.Context, context.CancelFunc)
- func (url *NodeUrl) LowerContextTimeoutWithDuration(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)
- func (url *NodeUrl) SetAuthHeaders(ctx context.Context, headerSetter func(string, string))
- func (url *NodeUrl) SetIpForwardingIfNecessary(ctx context.Context, headerSetter func(string, string))
- func (nurl NodeUrl) String() string
- func (nurl *NodeUrl) UrlStr() string
- type ProviderInfo
- type RelayResult
- type RestAptosError
- type RestError
- type SafeChannelSender
- type SafeSyncMap
- type Test_mode_ctx_key
- type TimeoutInfo
- type TxResultData
- type UserData
Constants ¶
const ( RollingLogLevelFlag = "rolling-log-level" RollingLogMaxSizeFlag = "rolling-log-max-size" RollingLogMaxAgeFlag = "rolling-log-max-age" RollingLogBackupsFlag = "rolling-log-backups" RollingLogFileLocationFlag = "rolling-log-file-location" RollingLogFormat = "rolling-log-format" )
const ( ProcessStartLogText = "Process Started" // cors related flags CorsHeadersFlag = "cors-headers" // comma separated list of headers, or * for all, default simple cors specification headers CorsCredentialsFlag = "cors-credentials" // comma separated list of headers, or * for all, default simple cors specification headers CorsOriginFlag = "cors-origin" // comma separated list of origins, or * for all, default enabled completely CorsMethodsFlag = "cors-methods" // comma separated list of methods, default "GET,POST,PUT,DELETE,OPTIONS" CDNCacheDurationFlag = "cdn-cache-duration" // how long to cache the preflight response default 24 hours (in seconds) "86400" RelaysHealthEnableFlag = "relays-health-enable" // enable relays health check, default true RelayHealthIntervalFlag = "relays-health-interval" // interval between each relay health check, default 5m // Disable relay retries when we get node errors. // This feature is suppose to help with successful relays in some chains that return node errors on rare race conditions on the serviced chains. SetRelayCountOnNodeErrorFlag = "set-retry-count-on-node-error" // BatchNodeErrorOnAny controls batch request error detection for JSON-RPC batch requests BatchNodeErrorOnAnyFlag = "batch-node-error-on-any" // UseStaticSpecFlag allows loading specs from various sources instead of the blockchain. // This flag can be specified multiple times to aggregate specs from multiple sources. // Later sources override earlier ones for the same chain ID (last-wins). // // Supported formats: // - Local file: --use-static-spec ./specs/eth.json // - Local directory: --use-static-spec ./specs/mainnet-1/specs/ // - GitHub URL: --use-static-spec https://github.com/owner/repo/tree/branch/path/to/specs // - GitLab URL: --use-static-spec https://gitlab.com/owner/repo/-/tree/branch/path/to/specs // // Multiple local files can be specified either as separate flags or comma-separated: // --use-static-spec file1.json --use-static-spec file2.json // --use-static-spec file1.json,file2.json // // Example with multiple sources (order matters - later overrides earlier): // --use-static-spec https://github.com/lavanet/lava/tree/main/specs \ // --use-static-spec https://gitlab.com/myorg/specs/-/tree/main \ // --use-static-spec ./local-overrides/ // // For private GitHub/GitLab repositories, use the corresponding token flag. UseStaticSpecFlag = "use-static-spec" // GitHubTokenFlag is a GitHub personal access token for accessing private repositories. // Also provides higher API rate limits (5,000 requests/hour vs 60 for unauthenticated). // Required URL format: https://github.com/{owner}/{repo}/tree/{branch}/{path} // Example: --github-token ghp_xxxxxxxxxxxx GitHubTokenFlag = "github-token" // GitLabTokenFlag is a GitLab personal access token for accessing private repositories. // Supports both gitlab.com and self-hosted GitLab instances. // The token must have at least "Reporter" role with "read_repository" scope. // Required URL format: https://gitlab.com/{owner}/{repo}/-/tree/{branch}/{path} // Example: --gitlab-token glpat-xxxxxxxxxxxx GitLabTokenFlag = "gitlab-token" EpochDurationFlag = "epoch-duration" // duration of each epoch for time-based epoch system (standalone mode) DefaultEpochDuration = 30 * time.Minute // default epoch duration for regular mode (if using time-based epochs) StandaloneEpochDuration = 15 * time.Minute // default epoch duration for standalone/static provider mode // optimizer flags SetProviderOptimizerBestTierPickChance = "set-provider-optimizer-best-tier-pick-chance" SetProviderOptimizerWorstTierPickChance = "set-provider-optimizer-worst-tier-pick-chance" SetProviderOptimizerNumberOfTiersToCreate = "set-provider-optimizer-number-of-tiers-to-create" SetProviderOptimizerNumberOfProvidersPerTier = "set-provider-optimizer-number-of-providers-per-tier" // If we have 4 providers for a specific chain, we will put 1 provider in each tier, so we wont have all 4 in tier 1 (which makes no sense.) SetProviderOptimizerAutoAdjustTiers = "enable-provider-optimizer-auto-adjustment-of-tiers" // will auto adjust the tiers based on the number of providers in pairing SetProviderOptimizerQosSelectionInTierFlag = "set-provider-optimizer-qos-based-selection-within-tier" // enables QoS-based selection within tiers instead of stake-based selection // optimizer qos server flags OptimizerQosServerAddressFlag = "optimizer-qos-server-address" // address of the optimizer qos server to send the qos reports OptimizerQosListenFlag = "optimizer-qos-listen" // enable listening for qos reports on metrics endpoint OptimizerQosServerPushIntervalFlag = "optimizer-qos-push-interval" // interval to push the qos reports to the optimizer qos server OptimizerQosServerSamplingIntervalFlag = "optimizer-qos-sampling-interval" // interval to sample the qos reports // websocket flags RateLimitWebSocketFlag = "rate-limit-websocket-requests-per-connection" BanDurationForWebsocketRateLimitExceededFlag = "ban-duration-for-websocket-rate-limit-exceeded" LimitParallelWebsocketConnectionsPerIpFlag = "limit-parallel-websocket-connections-per-ip" LimitWebsocketIdleTimeFlag = "limit-websocket-connection-idle-time" RateLimitRequestPerSecondFlag = "rate-limit-requests-per-second" SkipPolicyVerificationFlag = "skip-policy-verification" SkipWebsocketVerificationFlag = "skip-websocket-verification" SkipRelaySigningFlag = "skip-relay-signing" // skip signing relay requests/responses (for static providers to save CPU/memory) // specification default flags PeriodicProbeProvidersFlagName = "enable-periodic-probe-providers" PeriodicProbeProvidersIntervalFlagName = "periodic-probe-providers-interval" // batch request size limit MaxBatchRequestSizeFlag = "max-batch-request-size" DefaultMaxBatchRequestSize int = 0 // 0 means unlimited // DisableBatchRequestRetryFlag prevents batch requests from being retried on consumer/smartrouter side DisableBatchRequestRetryFlag = "disable-batch-request-retry" ShowProviderEndpointInMetricsFlagName = "show-provider-address-in-metrics" MemoryGCThresholdGBFlagName = "memory-gc-threshold-gb" // Memory GC threshold in GB (0 = disabled) MaxSessionsPerProviderFlagName = "max-sessions-per-provider" // Max number of sessions allowed per provider DefaultProcessingTimeoutFlagName = "default-processing-timeout" // default timeout for relay processing )
const ( CONSISTENCY_SELECT_ALL_PROVIDERS = 1 NO_STATE = 0 )
const ( // CompressionThreshold - only compress payloads larger than this (1 MB) // Small payloads have compression overhead > bandwidth savings CompressionThreshold = 1024 * 1024 * 1 // 1 MB // CompressionLevel - balance between speed and compression ratio // BestSpeed = 1 (fastest), BestCompression = 9 (smallest) // DefaultCompression = 6 (good balance) CompressionLevel = gzip.BestSpeed // LavaCompressionHeader - custom header to indicate manual compression LavaCompressionHeader = "lava-compression" LavaCompressionGzip = "gzip" // LavaCompressionSupportHeader - custom header consumer sends to indicate it supports compression // This is different from grpc-accept-encoding which is always sent by gRPC LavaCompressionSupportHeader = "lava-compression-support" )
const ( PlainTextConnection = "allow-plaintext-connection" EndpointsConfigName = "endpoints" StaticProvidersConfigName = "static-providers" BackupProvidersConfigName = "backup-providers" SaveConfigFlagName = "save-conf" GeolocationFlag = "geolocation" TestModeFlagName = "test-mode" MaximumConcurrentProvidersFlagName = "concurrent-providers" StatusCodeMetadataKey = "status-code" VersionMetadataKey = "lavap-version" LavaChainIdMetadataKey = "lavap-chain-id" TimeOutForFetchingLavaBlocksFlag = "timeout-for-fetching-lava-blocks" )
const ( URL_QUERY_PARAMETERS_SEPARATOR_FROM_PATH = "?" URL_QUERY_PARAMETERS_SEPARATOR_OTHER_PARAMETERS = "&" IP_FORWARDING_HEADER_NAME = "X-Forwarded-For" PROVIDER_ADDRESS_HEADER_NAME = "Lava-Provider-Address" RETRY_COUNT_HEADER_NAME = "Lava-Retries" PROVIDER_LATEST_BLOCK_HEADER_NAME = "Provider-Latest-Block" GUID_HEADER_NAME = "Lava-Guid" ERRORED_PROVIDERS_HEADER_NAME = "Lava-Errored-Providers" NODE_ERRORS_PROVIDERS_HEADER_NAME = "Lava-Node-Errors-providers" REPORTED_PROVIDERS_HEADER_NAME = "Lava-Reported-Providers" USER_REQUEST_TYPE = "lava-user-request-type" STATEFUL_API_HEADER = "lava-stateful-api" STATEFUL_ALL_PROVIDERS_HEADER_NAME = "lava-fast-tx-participants" REQUESTED_BLOCK_HEADER_NAME = "lava-parsed-requested-block" LAVA_IDENTIFIED_NODE_ERROR_HEADER = "lava-identified-node-error" LAVAP_VERSION_HEADER_NAME = "Lavap-Version" LAVA_CONSUMER_PROCESS_GUID = "lava-consumer-process-guid" // these headers need to be lowercase BLOCK_PROVIDERS_ADDRESSES_HEADER_NAME = "lava-providers-block" RELAY_TIMEOUT_HEADER_NAME = "lava-relay-timeout" EXTENSION_OVERRIDE_HEADER_NAME = "lava-extension" FORCE_CACHE_REFRESH_HEADER_NAME = "lava-force-cache-refresh" LAVA_DEBUG_RELAY = "lava-debug-relay" LAVA_LB_UNIQUE_ID_HEADER = "lava-lb-unique-id" STICKINESS_HEADER_NAME = "lava-stickiness" CROSS_VALIDATION_HEADER_MAX_PARTICIPANTS = "lava-cross-validation-max-participants" CROSS_VALIDATION_HEADER_AGREEMENT_THRESHOLD = "lava-cross-validation-agreement-threshold" CROSS_VALIDATION_ALL_PROVIDERS_HEADER_NAME = "lava-cross-validation-all-providers" CROSS_VALIDATION_STATUS_HEADER_NAME = "lava-cross-validation-status" CROSS_VALIDATION_AGREEING_PROVIDERS_HEADER = "lava-cross-validation-agreeing-providers" // send http request to /lava/health to see if the process is up - (ret code 200) DEFAULT_HEALTH_PATH = "/lava/health" MAXIMUM_ALLOWED_TIMEOUT_EXTEND_MULTIPLIER_BY_THE_CONSUMER = 4 )
const ( // JSON-RPC error patterns JSONRPCMethodNotFound = "method not found" JSONRPCMethodNotSupported = "method not supported" JSONRPCUnknownMethod = "unknown method" JSONRPCMethodDoesNotExist = "method does not exist" JSONRPCInvalidMethod = "invalid method" JSONRPCErrorCode = "-32601" // JSON-RPC 2.0 method not found error code // Generic unsupported patterns (catch-all for "method X not supported" format) GenericNotSupported = "not supported" // REST API error patterns RESTEndpointNotFound = "endpoint not found" RESTRouteNotFound = "route not found" RESTPathNotFound = "path not found" RESTMethodNotAllowed = "method not allowed" // gRPC error patterns GRPCMethodNotImplemented = "method not implemented" GRPCUnimplemented = "unimplemented" GRPCNotImplemented = "not implemented" GRPCServiceNotFound = "service not found" // HTTP status codes for unsupported endpoints HTTPStatusNotFound = 404 HTTPStatusMethodNotAllowed = 405 // JSON-RPC error code for method not found JSONRPCMethodNotFoundCode = -32601 // JSON-RPC error code for invalid params JSONRPCInvalidParamsCode = -32602 // Solana non-retryable error codes // - Error code -32009: Slot was skipped or missing in long-term storage (permanent) // Note: -32007 (ledger jump to snapshot) IS retryable as another provider may have the data SolanaMissingInLongTermStorageCode = -32009 // Solana non-retryable error patterns (message-based) SolanaMissingInLongTermStorage = "missing in long-term storage" )
Error pattern constants for unsupported method detection
const ( // MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts. // For 1000 req/s with ~500ms latency, we need ~500 concurrent connections. // Setting higher to allow headroom for spikes. // Go default: 100 DefaultMaxIdleConns = 1000 // MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host. // This is critical for blockchain node connections where we repeatedly connect to the same node. // For 1000 req/s to a single host with ~500ms latency, need ~500 idle connections. // Go default: 2 (way too low for high-concurrency!) DefaultMaxIdleConnsPerHost = 500 // MaxConnsPerHost limits the total number of connections per host, including those in active use. // This is the CRITICAL limit - if too low, requests will queue and cause cascading latency. // For 1000 req/s with ~1s worst-case latency, need up to 1000 connections. // Go default: 0 (unlimited - can cause node overload) DefaultMaxConnsPerHost = 0 // unlimited - let the upstream node enforce its own limits // IdleConnTimeout is the maximum amount of time an idle connection will remain idle before closing. // Keeps connections alive for reuse but eventually closes them to avoid resource leaks. // Go default: 90s DefaultIdleConnTimeout = 90 * time.Second // TLSHandshakeTimeout is the maximum amount of time waiting to perform a TLS handshake. // Go default: 10s DefaultTLSHandshakeTimeout = 10 * time.Second // ExpectContinueTimeout limits the time the client will wait between sending the request headers // and receiving the go-ahead to send the request body. // Go default: 1s DefaultExpectContinueTimeout = 1 * time.Second // ResponseHeaderTimeout is the amount of time to wait for a server's response headers. // This should be relatively high for blockchain nodes as they may be slow under load. // Go default: 0 (no timeout - can hang forever) DefaultResponseHeaderTimeout = 0 // DialTimeout is the maximum amount of time a dial will wait for a connect to complete. // Go default: 30s DefaultDialTimeout = 10 * time.Second // KeepAlive specifies the interval between keep-alive probes for an active network connection. // Go default: 30s DefaultKeepAlive = 30 * time.Second // DefaultHTTPTimeout is the default timeout for the entire request/response cycle. // Set to 5 minutes to handle slow blockchain node operations like trace_block. // Go default: 0 (no timeout - requests can hang forever) DefaultHTTPTimeout = 5 * time.Minute // DefaultTLSSessionCacheSize is the number of TLS session tickets to cache. // This enables TLS session resumption, which skips the expensive certificate // verification on subsequent connections to the same host. // Each cached session saves ~10-15% CPU on TLS handshakes. DefaultTLSSessionCacheSize = 1024 )
HTTP Connection Pool Configuration These values are optimized for high-throughput scenarios (1000+ req/s) where providers handle many simultaneous requests to blockchain nodes.
const ( TimePerCU = uint64(100 * time.Millisecond) MinimumTimePerRelayDelay = time.Second CacheWriteTimeout = 5 * time.Second AverageWorldLatency = 300 * time.Millisecond CommunicateWithLocalLavaNodeTimeout = (3 * time.Second) + AverageWorldLatency DefaultTimeoutSeconds = 30 // default timeout in seconds, can be overridden by flag CacheTimeout = 50 * time.Millisecond // On subscriptions we must use context.Background(), // we cant have a context.WithTimeout() context, meaning we can hang for ever. // to avoid that we introduced a first reply timeout using a routine. // if the first reply doesn't return after the specified timeout a timeout error will occur SubscriptionFirstReplyTimeout = 10 * time.Second )
Variables ¶
var ( ContextDeadlineExceededError = sdkerrors.New("ContextDeadlineExceeded Error", 300, "context deadline exceeded") StatusCodeError504 = sdkerrors.New("Disallowed StatusCode Error", 504, "Disallowed status code error (504)") StatusCodeError429 = sdkerrors.New("Disallowed StatusCode Error", 429, "Disallowed status code error (429)") StatusCodeErrorStrict = sdkerrors.New("Disallowed StatusCode Error", 800, "Disallowed status code error (800)") APINotSupportedError = sdkerrors.New("APINotSupported Error", 900, "api not supported") SubscriptionNotFoundError = sdkerrors.New("SubscriptionNotFoundError Error", 901, "subscription not found") ProviderFinalizationDataAccountabilityError = sdkerrors.New("ProviderFinalizationDataAccountability Error", 3365, "provider returned invalid finalization data, with accountability") )
var DefaultCrossValidationParams = CrossValidationParams{
MaxParticipants: 1,
AgreementThreshold: 1,
}
DefaultCrossValidationParams are used when cross-validation is not enabled (Selection != CrossValidation)
var DefaultTimeout = time.Duration(DefaultTimeoutSeconds) * time.Second
DefaultTimeout is the configurable default timeout for relay processing. It can be overridden via the --default-timeout flag on consumer and smart router commands.
var JsonRpcBatchSizeExceededError = JsonRPCErrorMessage{ JsonRPC: "2.0", Id: 1, Error: JsonRPCError{ Code: 429, Message: "Batch request size exceeded", }, }
var JsonRpcMethodNotFoundError = JsonRPCErrorMessage{ JsonRPC: "2.0", Id: 1, Error: JsonRPCError{ Code: -32601, Message: "Method not found", }, }
var JsonRpcParseError = JsonRPCErrorMessage{ JsonRPC: "2.0", Id: -1, Error: JsonRPCError{ Code: -32700, Message: "Parse error", Data: "Failed to parse the request body as JSON", }, }
var JsonRpcRateLimitError = JsonRPCErrorMessage{ JsonRPC: "2.0", Id: 1, Error: JsonRPCError{ Code: 429, Message: "Too Many Requests", }, }
var JsonRpcSubscriptionNotFoundError = JsonRPCErrorMessage{ JsonRPC: "2.0", Id: 1, Error: JsonRPCError{ Code: -32603, Message: "Internal error", Data: "subscription not found", }, }
var RestAptosMethodNotFoundError = RestAptosError{ Message: "not found", ErrorCode: "web_framework_error", VmErrorCode: nil, }
var RestMethodNotFoundError = RestError{
Code: 12,
Message: "Not Implemented",
Details: []interface{}{},
}
var SPECIAL_LAVA_DIRECTIVE_HEADERS = map[string]struct{}{ BLOCK_PROVIDERS_ADDRESSES_HEADER_NAME: {}, RELAY_TIMEOUT_HEADER_NAME: {}, EXTENSION_OVERRIDE_HEADER_NAME: {}, FORCE_CACHE_REFRESH_HEADER_NAME: {}, LAVA_DEBUG_RELAY: {}, STICKINESS_HEADER_NAME: {}, CROSS_VALIDATION_HEADER_MAX_PARTICIPANTS: {}, CROSS_VALIDATION_HEADER_AGREEMENT_THRESHOLD: {}, }
Functions ¶
func AddRollingLogConfig ¶
default rolling logs behavior (if enabled) will store 3 files each 100MB for up to 1 day every time.
func BaseTimePerCU ¶
func CapContextTimeout ¶
func CompressData ¶ added in v5.6.0
CompressData compresses data using gzip if it's larger than threshold Returns compressed data, whether it was compressed, and any error
func ContextOutOfTime ¶
func DecompressData ¶ added in v5.6.0
DecompressData decompresses gzip data Returns decompressed data and any error
func FindSequenceNumber ¶
extract requested sequence number from tx error.
func GetExtensionNames ¶
func GetIpFromGrpcContext ¶
func GetTimePerCu ¶
func GetTimeoutForProcessing ¶
func GetTimeoutForProcessing(relayTimeout time.Duration, timeoutInfo TimeoutInfo) time.Duration
func GetTokenFromGrpcContext ¶
func GetUniqueToken ¶
func IsSolanaNonRetryableError ¶ added in v5.8.0
IsSolanaNonRetryableError checks if an error message indicates a Solana error that should not be retried. Currently this covers: - Error code -32009: "missing in long-term storage" (slot permanently unavailable)
Note: Error code -32007 (ledger jump to snapshot) IS retryable as another provider may have the data.
Returns true if the error message contains any known Solana non-retryable pattern.
func IsSolanaNonRetryableErrorBytes ¶ added in v5.8.0
IsSolanaNonRetryableErrorBytes checks if an error message (as bytes) indicates a Solana non-retryable error. This is more efficient than IsSolanaNonRetryableError when working with []byte data as it avoids string conversions and uses pre-computed byte patterns with a single-pass lowercase conversion.
func IsSquareBracketed ¶
func IsTestMode ¶
func IsUnsupportedMethodErrorMessageBytes ¶ added in v5.8.0
IsUnsupportedMethodErrorMessageBytes checks if an error message (as bytes) indicates an unsupported method. This is more efficient than IsUnsupportedMethodErrorMessage when working with []byte data as it avoids string conversions and uses pre-computed byte patterns with a single-pass lowercase conversion.
func IsUnsupportedMethodMessage ¶ added in v5.8.0
IsUnsupportedMethodMessage checks if an error message indicates an unsupported method. This is a convenience wrapper that delegates to IsUnsupportedMethodErrorMessageBytes for efficient pattern matching using pre-computed byte patterns.
For more comprehensive checks including HTTP status codes and gRPC status codes, use chainlib.IsUnsupportedMethodError which wraps this function with additional protocol-specific checks.
Returns true if the error message contains any known unsupported method pattern.
func LocalNodeTimePerCu ¶
func OptimizedHttpClient ¶ added in v5.6.0
OptimizedHttpClient creates an HTTP client with optimized transport settings and a default 5-minute timeout suitable for blockchain node operations. The client uses the shared transport for maximum connection reuse.
Note: Multiple clients can safely share the same transport. The transport handles connection pooling internally.
Returns:
- *http.Client: A client with optimized connection pooling and default timeout
func OptimizedHttpTransport ¶ added in v5.6.0
OptimizedHttpTransport creates an HTTP transport optimized for provider-to-node communication. This transport is configured to: 1. Reuse connections efficiently (high MaxIdleConnsPerHost) 2. Limit total connections per host (prevents overwhelming nodes) 3. Handle high concurrency scenarios (200+ simultaneous requests) 4. Close idle connections appropriately to avoid leaks 5. Cache TLS sessions for faster reconnections
Benefits: - Reduces TCP connection overhead - Prevents connection exhaustion on blockchain nodes - Improves latency through connection reuse - Handles heavy load without creating thousands of connections - TLS session resumption reduces CPU usage by ~10-15% on handshakes
Note: For most use cases, prefer SharedHttpTransport() to maximize connection reuse.
func ParseEndpointArgs ¶
func SetupRollingLogger ¶
func SetupRollingLogger() func()
func SharedHttpTransport ¶ added in v5.7.0
SharedHttpTransport returns a singleton HTTP transport that is shared across all RPC clients in the application. This maximizes connection reuse and TLS session caching benefits.
Why sharing matters: - Each http.Transport maintains its own connection pool - With N separate transports, you get N separate pools with limited reuse - With 1 shared transport, all connections are pooled together - TLS session cache is also shared, benefiting all connections
This is safe for concurrent use as http.Transport is goroutine-safe.
func UnSquareBracket ¶
func ValidateEndpoint ¶
Types ¶
type AuthConfig ¶
type AuthConfig struct {
AuthHeaders map[string]string `yaml:"auth-headers,omitempty" json:"auth-headers,omitempty" mapstructure:"auth-headers"`
AuthQuery string `yaml:"auth-query,omitempty" json:"auth-query,omitempty" mapstructure:"auth-query"`
UseTLS bool `yaml:"use-tls,omitempty" json:"use-tls,omitempty" mapstructure:"use-tls"`
AllowInsecure bool `yaml:"allow-insecure,omitempty" json:"allow-insecure,omitempty" mapstructure:"allow-insecure"`
KeyPem string `yaml:"key-pem,omitempty" json:"key-pem,omitempty" mapstructure:"key-pem"`
CertPem string `yaml:"cert-pem,omitempty" json:"cert-pem,omitempty" mapstructure:"cert-pem"`
CaCert string `yaml:"cacert-pem,omitempty" json:"cacert-pem,omitempty" mapstructure:"cacert-pem"`
}
func (*AuthConfig) AddAuthPath ¶
func (ac *AuthConfig) AddAuthPath(url string) string
func (*AuthConfig) GetCaCertificateParams ¶
func (ac *AuthConfig) GetCaCertificateParams() string
File containing trusted root certificates for verifying the server.
func (*AuthConfig) GetLoadingCertificateParams ¶
func (ac *AuthConfig) GetLoadingCertificateParams() (string, string)
File containing client certificate (public key), to present to the server. + File containing client private key, to present to the server.
func (*AuthConfig) GetUseTls ¶
func (ac *AuthConfig) GetUseTls() bool
type ConflictHandlerInterface ¶
type ConflictHandlerInterface interface {
ConflictAlreadyReported() bool
StoreConflictReported()
}
type ConsumerCmdFlags ¶
type ConsumerCmdFlags struct {
HeadersFlag string // comma separated list of headers, or * for all, default simple cors specification headers
CredentialsFlag string // access-control-allow-credentials, defaults to "true"
OriginFlag string // comma separated list of origins, or * for all, default enabled completely
MethodsFlag string // whether to allow access control headers *, most proxies have their own access control so its not required
CDNCacheDuration string // how long to cache the preflight response defaults 24 hours (in seconds) "86400"
RelaysHealthEnableFlag bool // enables relay health check
RelaysHealthIntervalFlag time.Duration // interval for relay health check
DebugRelays bool // enables debug mode for relays
StaticSpecPaths []string // paths to spec sources (files, directories, or remote URLs). Later entries override earlier for same chain ID.
GitHubToken string // GitHub personal access token for accessing private repositories
GitLabToken string // GitLab personal access token for accessing private repositories
EpochDuration time.Duration // duration of each epoch for time-based epoch system (standalone mode)
}
helper struct to propagate flags deeper into the code in an organized manner
type CrossValidationParams ¶ added in v5.8.0
type CrossValidationParams struct {
MaxParticipants int // Maximum number of providers to query
AgreementThreshold int // Number of matching responses needed for consensus
}
CrossValidationParams holds the cross-validation configuration parameters Note: Whether cross-validation is enabled is determined by the Selection type (CrossValidation), not by these parameters. These parameters only store the values when cross-validation is active.
type EpochTimer ¶ added in v5.6.0
type EpochTimer struct {
// contains filtered or unexported fields
}
EpochTimer manages epochs based on absolute wall clock time All processes using the same epochDuration will calculate the same epoch number and update at the same absolute time boundaries
func NewEpochTimer ¶ added in v5.6.0
func NewEpochTimer(epochDuration time.Duration) *EpochTimer
NewEpochTimer creates a new time-based epoch timer Epoch 0 starts at a fixed point in the past (January 1, 2024 00:00:00 UTC) This ensures epochs remain consistent even after long downtimes
func (*EpochTimer) CalculateCurrentEpoch ¶ added in v5.6.0
func (et *EpochTimer) CalculateCurrentEpoch() uint64
CalculateCurrentEpoch calculates epoch number from absolute time Formula: epoch = floor((currentTime - epochZeroTime) / epochDuration)
func (*EpochTimer) GetCurrentEpoch ¶ added in v5.6.0
func (et *EpochTimer) GetCurrentEpoch() uint64
GetCurrentEpoch returns current epoch (alias for clarity)
func (*EpochTimer) GetEpochBoundaryTime ¶ added in v5.6.0
func (et *EpochTimer) GetEpochBoundaryTime(epoch uint64) time.Time
GetEpochBoundaryTime returns the absolute time when an epoch starts
func (*EpochTimer) GetEpochDuration ¶ added in v5.6.0
func (et *EpochTimer) GetEpochDuration() time.Duration
GetEpochDuration returns the configured epoch duration
func (*EpochTimer) GetTimeUntilNextEpoch ¶ added in v5.6.0
func (et *EpochTimer) GetTimeUntilNextEpoch() time.Duration
GetTimeUntilNextEpoch calculates time until next epoch boundary
func (*EpochTimer) RegisterCallback ¶ added in v5.6.0
func (et *EpochTimer) RegisterCallback(callback func(uint64))
RegisterCallback registers a callback to be called on epoch updates
func (*EpochTimer) Start ¶ added in v5.6.0
func (et *EpochTimer) Start(ctx context.Context)
Start begins the epoch timer with synchronized triggers at absolute boundaries
type JsonRPCError ¶
type JsonRPCErrorMessage ¶
type JsonRPCErrorMessage struct {
JsonRPC string `json:"jsonrpc"`
Id int `json:"id"`
Error JsonRPCError `json:"error"`
}
type NodeUrl ¶
type NodeUrl struct {
Url string `yaml:"url,omitempty" json:"url,omitempty" mapstructure:"url"`
InternalPath string `yaml:"internal-path,omitempty" json:"internal-path,omitempty" mapstructure:"internal-path"`
AuthConfig AuthConfig `yaml:"auth-config,omitempty" json:"auth-config,omitempty" mapstructure:"auth-config"`
IpForwarding bool `yaml:"ip-forwarding,omitempty" json:"ip-forwarding,omitempty" mapstructure:"ip-forwarding"`
Timeout time.Duration `yaml:"timeout,omitempty" json:"timeout,omitempty" mapstructure:"timeout"`
Addons []string `yaml:"addons,omitempty" json:"addons,omitempty" mapstructure:"addons"`
SkipVerifications []string `yaml:"skip-verifications,omitempty" json:"skip-verifications,omitempty" mapstructure:"skip-verifications"`
Methods []string `yaml:"methods,omitempty" json:"methods,omitempty" mapstructure:"methods"`
}
func (*NodeUrl) GetAuthHeaders ¶
func (*NodeUrl) LowerContextTimeout ¶
func (*NodeUrl) LowerContextTimeoutWithDuration ¶
func (*NodeUrl) SetAuthHeaders ¶
func (*NodeUrl) SetIpForwardingIfNecessary ¶
type ProviderInfo ¶
type RelayResult ¶
type RelayResult struct {
Request *pairingtypes.RelayRequest
Reply *pairingtypes.RelayReply
ProviderInfo ProviderInfo
ReplyServer pairingtypes.Relayer_RelaySubscribeClient
Finalized bool
ConflictHandler ConflictHandlerInterface
StatusCode int
CrossValidation int
ProviderTrailer metadata.MD // the provider trailer attached to the request. used to transfer useful information (which is not signed so shouldn't be trusted completely).
IsNodeError bool
ResponseHash [32]byte // cached SHA256 hash of Reply.Data for cross-validation comparison, zero-value if not computed
IsUnsupportedMethod bool // Indicates this node error is an unsupported method
}
func (*RelayResult) GetProvider ¶
func (rr *RelayResult) GetProvider() string
func (*RelayResult) GetReply ¶
func (rr *RelayResult) GetReply() *pairingtypes.RelayReply
func (*RelayResult) GetReplyServer ¶
func (rr *RelayResult) GetReplyServer() pairingtypes.Relayer_RelaySubscribeClient
func (*RelayResult) GetStatusCode ¶
func (rr *RelayResult) GetStatusCode() int
type RestAptosError ¶
type SafeChannelSender ¶
type SafeChannelSender[T any] struct { // contains filtered or unexported fields }
func NewSafeChannelSender ¶
func NewSafeChannelSender[T any](ctx context.Context, ch chan<- T) *SafeChannelSender[T]
func (*SafeChannelSender[T]) Close ¶
func (scs *SafeChannelSender[T]) Close()
func (*SafeChannelSender[T]) LockAndSendAsynchronously ¶
func (scs *SafeChannelSender[T]) LockAndSendAsynchronously(msg T)
Used when there is a need to validate locked, but you don't want to wait for the channel to return.
func (*SafeChannelSender[T]) MarkClosed ¶ added in v5.7.0
func (scs *SafeChannelSender[T]) MarkClosed()
MarkClosed marks the channel as closed without actually closing the underlying channel. This is useful when replacing a channel (e.g., during consumer reconnection) to signal that sends should fail gracefully without panicking on close.
func (*SafeChannelSender[T]) ReplaceChannel ¶
func (scs *SafeChannelSender[T]) ReplaceChannel(ch chan<- T)
func (*SafeChannelSender[T]) Send ¶
func (scs *SafeChannelSender[T]) Send(msg T)
Used when you need to wait for the other side to receive the message.
type SafeSyncMap ¶
type SafeSyncMap[K, V any] struct { // contains filtered or unexported fields }
func (*SafeSyncMap[K, V]) Load ¶
func (ssm *SafeSyncMap[K, V]) Load(key K) (ret V, ok bool, err error)
func (*SafeSyncMap[K, V]) LoadOrStore ¶
func (ssm *SafeSyncMap[K, V]) LoadOrStore(key K, value V) (ret V, loaded bool, err error)
LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored. The function returns the value that was loaded or stored.
func (*SafeSyncMap[K, V]) Range ¶
func (ssm *SafeSyncMap[K, V]) Range(f func(key K, value V) bool)
func (*SafeSyncMap[K, V]) Store ¶
func (ssm *SafeSyncMap[K, V]) Store(key K, toSet V)
type Test_mode_ctx_key ¶
type Test_mode_ctx_key struct{}
type TimeoutInfo ¶
type TxResultData ¶
func ParseTransactionResult ¶
func ParseTransactionResult(parsedValues map[string]any) (retData TxResultData, err error)