common

package
v2.5.3 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2024 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
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"
)
View Source
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
	SharedStateFlag                 = "shared-state"
	DisableConflictTransactionsFlag = "disable-conflict-transactions" // disable conflict transactions, this will hard the network's data reliability and therefore will harm the service.
	// 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.
	DisableRetryOnNodeErrorsFlag = "disable-retry-on-node-error"
	SetRelayCountOnNodeErrorFlag = "set-retry-count-on-node-error"
	DisableCacheOnNodeErrorFlag  = "disable-cache-on-node-error"
	UseOfflineSpecFlag           = "use-offline-spec" // allows the user to manually load a spec providing a path, this is useful to test spec changes before they hit the blockchain
)
View Source
const (
	CONSISTENCY_SELECT_ALL_PROVIDERS = 1
	NO_STATE                         = 0
)
View Source
const (
	PlainTextConnection                = "allow-plaintext-connection"
	EndpointsConfigName                = "endpoints"
	StaticProvidersConfigName          = "static-providers"
	SaveConfigFlagName                 = "save-conf"
	GeolocationFlag                    = "geolocation"
	TestModeFlagName                   = "test-mode"
	MaximumConcurrentProvidersFlagName = "concurrent-providers"
	StatusCodeMetadataKey              = "status-code"
	VersionMetadataKey                 = "lavap-version"
	TimeOutForFetchingLavaBlocksFlag   = "timeout-for-fetching-lava-blocks"
)
View Source
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"
	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"
	// 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
)
View Source
const (
	TimePerCU                           = uint64(100 * time.Millisecond)
	MinimumTimePerRelayDelay            = time.Second
	DataReliabilityTimeoutIncrease      = 5 * time.Second
	AverageWorldLatency                 = 300 * time.Millisecond
	CommunicateWithLocalLavaNodeTimeout = (3 * time.Second) + AverageWorldLatency
	DefaultTimeout                      = 30 * time.Second
	DefaultTimeoutLongIsh               = 1 * time.Minute
	DefaultTimeoutLong                  = 3 * time.Minute
	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

View Source
var (
	ContextDeadlineExceededError                = sdkerrors.New("ContextDeadlineExceeded Error", 300, "context deadline exceeded")
	StatusCodeError504                          = sdkerrors.New("Disallowed StatusCode Error", 504, "Disallowed status code error")
	StatusCodeError429                          = sdkerrors.New("Disallowed StatusCode Error", 429, "Disallowed status code error")
	StatusCodeErrorStrict                       = sdkerrors.New("Disallowed StatusCode Error", 800, "Disallowed status code error")
	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")
)
View Source
var JsonRpcMethodNotFoundError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    -32601,
		Message: "Method not found",
	},
}
View Source
var JsonRpcSubscriptionNotFoundError = JsonRPCErrorMessage{
	JsonRPC: "2.0",
	Id:      1,
	Error: JsonRPCError{
		Code:    -32603,
		Message: "Internal error",
		Data:    "subscription not found",
	},
}
View Source
var RestAptosMethodNotFoundError = RestAptosError{
	Message:     "not found",
	ErrorCode:   "web_framework_error",
	VmErrorCode: nil,
}
View Source
var RestMethodNotFoundError = RestError{
	Code:    12,
	Message: "Not Implemented",
	Details: []interface{}{},
}

Functions

func AddRollingLogConfig

func AddRollingLogConfig(cmd *cobra.Command)

default rolling logs behavior (if enabled) will store 3 files each 100MB for up to 1 day every time.

func BaseTimePerCU

func BaseTimePerCU(cu uint64) time.Duration

func CapContextTimeout

func CapContextTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

func ContextOutOfTime

func ContextOutOfTime(ctx context.Context) bool

func CreateRestMethodNotFoundError

func CreateRestMethodNotFoundError(fiberCtx *fiber.Ctx, chainId string) error

func FindSequenceNumber

func FindSequenceNumber(sequence string) (int, error)

extract requested sequence number from tx error.

func GetExtensionNames

func GetExtensionNames(extensionCollection []*spectypes.Extension) (extensions []string)

func GetIpFromGrpcContext

func GetIpFromGrpcContext(ctx context.Context) string

func GetRemainingTimeoutFromContext

func GetRemainingTimeoutFromContext(ctx context.Context) (timeRemaining time.Duration)

func GetTimePerCu

func GetTimePerCu(cu uint64) time.Duration

func GetTimeoutForProcessing

func GetTimeoutForProcessing(relayTimeout time.Duration, timeoutInfo TimeoutInfo) time.Duration

func GetTokenFromGrpcContext

func GetTokenFromGrpcContext(ctx context.Context) string

func GetUniqueToken

func GetUniqueToken(consumerAddress string, ip string) string

func IsQuoted added in v2.4.0

func IsQuoted(s string) bool

func IsSquareBracketed added in v2.4.0

func IsSquareBracketed(s string) bool

func IsTestMode

func IsTestMode(ctx context.Context) bool

func IsTimeout

func IsTimeout(errArg error) bool

func LocalNodeTimePerCu

func LocalNodeTimePerCu(cu uint64) time.Duration

func ParseEndpointArgs

func ParseEndpointArgs(endpoint_strings, yaml_config_properties []string, endpointsConfigName string) (viper_endpoints *viper.Viper, err error)

func SetupRollingLogger

func SetupRollingLogger() func()

func UnSquareBracket added in v2.4.0

func UnSquareBracket(s string) string

func ValidateEndpoint

func ValidateEndpoint(endpoint, apiInterface string) error

func VerifyAndHandleUnsupportedFlags

func VerifyAndHandleUnsupportedFlags(currentFlags *pflag.FlagSet) error

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 ChainMessageGetApiInterface

type ChainMessageGetApiInterface interface {
	GetApi() *spectypes.Api
}

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
	DisableConflictTransactions bool          // disable conflict transactions
	DisableRetryOnNodeErrors    bool          // disable retries on node errors
	SetRelayCountOnNodeError    int
	DisableCacheOnNodeError     bool
	OfflineSpecPath             string // path to the spec file, works only when bootstrapping a single chain.
}

helper struct to propagate flags deeper into the code in an organized manner

type JsonRPCError

type JsonRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data"`
}

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) LowerContextTimeout

func (url *NodeUrl) LowerContextTimeout(ctx context.Context, processingTimeout time.Duration) (context.Context, context.CancelFunc)

func (*NodeUrl) LowerContextTimeoutWithDuration

func (url *NodeUrl) LowerContextTimeoutWithDuration(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc)

func (*NodeUrl) SetAuthHeaders

func (url *NodeUrl) SetAuthHeaders(ctx context.Context, headerSetter func(string, string))

func (*NodeUrl) SetIpForwardingIfNecessary

func (url *NodeUrl) SetIpForwardingIfNecessary(ctx context.Context, headerSetter func(string, string))

func (NodeUrl) String

func (nurl NodeUrl) String() string

func (*NodeUrl) UrlStr

func (nurl *NodeUrl) UrlStr() string

type ProviderInfo

type ProviderInfo struct {
	ProviderAddress              string
	ProviderQoSExcellenceSummery sdk.Dec // the number represents the average qos for this provider session
	ProviderStake                sdk.Coin
}

type RelayResult

type RelayResult struct {
	Request         *pairingtypes.RelayRequest
	Reply           *pairingtypes.RelayReply
	ProviderInfo    ProviderInfo
	ReplyServer     pairingtypes.Relayer_RelaySubscribeClient
	Finalized       bool
	ConflictHandler ConflictHandlerInterface
	StatusCode      int
	Quorum          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).
}

func (*RelayResult) GetProvider

func (rr *RelayResult) GetProvider() string

func (*RelayResult) GetReply

func (rr *RelayResult) GetReply() *pairingtypes.RelayReply

func (*RelayResult) GetReplyServer

func (*RelayResult) GetStatusCode

func (rr *RelayResult) GetStatusCode() int

type RestAptosError

type RestAptosError struct {
	Message     string      `json:"message"`
	ErrorCode   string      `json:"error_code"`
	VmErrorCode interface{} `json:"vm_error_code"`
}

type RestError

type RestError struct {
	Code    int           `json:"code"`
	Message string        `json:"message"`
	Details []interface{} `json:"details"`
}

type SafeChannelSender added in v2.4.0

type SafeChannelSender[T any] struct {
	// contains filtered or unexported fields
}

func NewSafeChannelSender added in v2.4.0

func NewSafeChannelSender[T any](ctx context.Context, ch chan<- T) *SafeChannelSender[T]

func (*SafeChannelSender[T]) Close added in v2.4.0

func (scs *SafeChannelSender[T]) Close()

func (*SafeChannelSender[T]) LockAndSendAsynchronously added in v2.4.0

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]) ReplaceChannel added in v2.4.0

func (scs *SafeChannelSender[T]) ReplaceChannel(ch chan<- T)

func (*SafeChannelSender[T]) Send added in v2.4.0

func (scs *SafeChannelSender[T]) Send(msg T)

Used when you need to wait for the other side to receive the message.

type Test_mode_ctx_key

type Test_mode_ctx_key struct{}

type TimeoutInfo

type TimeoutInfo struct {
	CU       uint64
	Hanging  bool
	Stateful uint32
}

type TxResultData

type TxResultData struct {
	RawLog string
	Txhash []byte
	Code   int
}

func ParseTransactionResult

func ParseTransactionResult(parsedValues map[string]any) (retData TxResultData, err error)

Jump to

Keyboard shortcuts

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