utils

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package utils implements different utilities to be used by production code.

Index

Constants

View Source
const (
	// Base services.
	BaseLoggerName                 = "xmtpd"
	APILoggerName                  = "api"
	DatabaseSubscriptionLoggerName = "database-subscription"
	NodeRegistryWatchdogLoggerName = "node-registry-watchdog"
	PublishWorkerName              = "publish-worker"
	SubscribeWorkerLoggerName      = "subscribe-worker"
	SyncLoggerName                 = "sync"
	SyncWorkerName                 = "sync-worker"
	ContractRatesFetcherLoggerName = "contract-rates-fetcher"
	MetricsLoggerName              = "metrics"
	MisbehaviorLoggerName          = "misbehavior"

	// Gateway services.
	GatewayLoggerName             = "gateway"
	BlockchainPublisherLoggerName = "blockchain-publisher"

	// Indexer.
	IndexerLoggerName                    = "indexer"
	AppChainIndexerLoggerName            = "app-chain"
	GroupMessageBroadcasterLoggerName    = "group-message-broadcaster"
	IdentityUpdateBroadcasterLoggerName  = "identity-update-broadcaster"
	PayerRegistryContractLoggerName      = "payer-registry"
	PayerReportManagerContractLoggerName = "payer-report-manager"
	RPCLogStreamerLoggerName             = "rpc-log-streamer"
	StorerLoggerName                     = "storer"
	ReorgHandlerLoggerName               = "reorg-handler"
	SettlementChainAdminLoggerName       = "settlement-chain-admin"
	SettlementChainIndexerLoggerName     = "settlement-chain"

	// Nonce managers.
	RedisNonceManagerLoggerName = "redis-nonce-manager"
	SQLNonceManagerLoggerName   = "sql-nonce-manager"

	// Migrator.
	MigratorLoggerName            = "migrator"
	MigratorReaderLoggerName      = "reader"
	MigratorTransformerLoggerName = "transformer"
	MigratorWriterLoggerName      = "writer"
	MigratorWriterBatchLoggerName = "writer-batch"

	// On-chain protocol services.
	AppChainAdminLoggerName           = "app-chain-admin"
	FundsAdminLoggerName              = "funds-admin"
	NodeRegistryAdminLoggerName       = "node-registry-admin"
	NodeRegistryCallerLoggerName      = "node-registry-caller"
	ParameterAdminLoggerName          = "parameter-registry-admin"
	RateRegistryAdminLoggerName       = "rate-registry-admin"
	PayerReportManagerAdminLoggerName = "payer-report-manager-admin"

	// Payer report subsystem.
	LedgerLoggerName                       = "ledger"
	PayerReportMainLoggerName              = "payer-report"
	PayerReportStoreLoggerName             = "store"
	PayerReportAttestationWorkerLoggerName = "attestation-worker"
	PayerReportGeneratorWorkerLoggerName   = "generator-worker"
	PayerReportSettlementWorkerLoggerName  = "settlement-worker"
	PayerReportSubmitterWorkerLoggerName   = "submitter-worker"

	// Misc and utilities.
	PrunerLoggerName             = "pruner-worker"
	StressChainWatcherLoggerName = "chain-watcher"
	BlockchainOracleLoggerName   = "blockchain-oracle"
)

Variables

View Source
var ErrIntOverflow = errors.New("overflow in conversion from uint to int")
View Source
var ErrSliceNot32Bytes = errors.New("slice must be 32 bytes long")

Functions

func AddressField added in v1.0.0

func AddressField(address string) zap.Field

func AddressTo32Slice added in v0.5.0

func AddressTo32Slice(addr common.Address) [32]byte

func AmountField added in v1.0.0

func AmountField(amount string) zap.Field

func AppChainChainIDField added in v1.0.0

func AppChainChainIDField(chainID int64) zap.Field

func AssertHexDecode

func AssertHexDecode(s string) []byte

func AuthorizationHeaderFromContext added in v1.0.0

func AuthorizationHeaderFromContext(ctx context.Context) string

func AuthorizationTokenFromHeader added in v1.0.0

func AuthorizationTokenFromHeader(headers http.Header) string

func BalanceField added in v1.0.0

func BalanceField(balance string) zap.Field

func BlockNumberField added in v1.0.0

func BlockNumberField(blockNumber uint64) zap.Field

func BodyField added in v1.0.0

func BodyField(body any) zap.Field

BodyField uses reflection to log the body of the request or response. Do not use in hot paths unless guarded with "if logger.Core().Enabled(zap.DebugLevel) { ... }"

func BuildConnectProtocolDialOptions added in v1.0.0

func BuildConnectProtocolDialOptions(extraDialOpts ...connect.ClientOption) []connect.ClientOption

BuildConnectProtocolDialOptions builds the default dial options for a Connect-Go, gRPC or gRPC-Web connection. Internal node <-> node communication can rely on this protocol.

func BuildGRPCDialOptions added in v1.0.0

func BuildGRPCDialOptions(extraDialOpts ...connect.ClientOption) []connect.ClientOption

BuildGRPCDialOptions instructs the client to use the gRPC transport. Ideal for client <-> node communication, where the client only implements gRPC (i.e., Tonic).

func BuildGRPCWebDialOptions added in v1.0.0

func BuildGRPCWebDialOptions(extraDialOpts ...connect.ClientOption) []connect.ClientOption

BuildGRPCWebDialOptions instructs the client to use the gRPC-Web transport. Ideal for WASM clients that need to use the gRPC-Web protocol.

func BuildHTTP2Client added in v1.0.0

func BuildHTTP2Client(ctx context.Context, isTLS bool) (*http.Client, error)

BuildHTTP2Client creates an HTTP/2 client for Connect-based RPC or other HTTP/2 services.

func BuildLogger

func BuildLogger(options config.LogOptions) (*zap.Logger, *zap.Config, error)

func BuildNamespace added in v0.1.2

func BuildNamespace(privateKey string, nodesAddress string) string

func ChainIDField added in v1.0.0

func ChainIDField(chainID int64) zap.Field

func ClientIPFromContext added in v0.5.0

func ClientIPFromContext(ctx context.Context) string

func ClientIPFromHeaderOrPeer added in v1.0.0

func ClientIPFromHeaderOrPeer(headers http.Header, peer string) string

func ContractAddressField added in v1.0.0

func ContractAddressField(contractAddress string) zap.Field

func CountField added in v1.0.0

func CountField(count int64) zap.Field

func DecodeBytes32ToUint64 added in v0.5.0

func DecodeBytes32ToUint64(b [32]byte) uint64

func DurationMsField added in v1.0.0

func DurationMsField(waitTime time.Duration) zap.Field

func EcdsaPrivateKeyToString

func EcdsaPrivateKeyToString(key *ecdsa.PrivateKey) string

func EcdsaPublicKeyToAddress

func EcdsaPublicKeyToAddress(key *ecdsa.PublicKey) string

func EcdsaPublicKeyToString

func EcdsaPublicKeyToString(key *ecdsa.PublicKey) string

func EncodeUint64ToBytes32 added in v0.5.0

func EncodeUint64ToBytes32(v uint64) [32]byte

func EnvelopeIDField added in v1.0.0

func EnvelopeIDField(envelopeID int64) zap.Field

func EventField added in v1.0.0

func EventField(event string) zap.Field

func EventIDField added in v1.0.0

func EventIDField(eventID string) zap.Field

func FromAddressField added in v1.0.0

func FromAddressField(fromAddress string) zap.Field

func GenerateEcdsaPrivateKey

func GenerateEcdsaPrivateKey() (*ecdsa.PrivateKey, error)

func GetEventSig

func GetEventSig(abi *abi.ABI, eventName string) (string, error)

GetEventSig extracts the event signature from an ABI by event name.

func GetEventTopic

func GetEventTopic(abi *abi.ABI, eventName string) (common.Hash, error)

GetEventTopic extracts the event topic (the hash of the signature) from an ABI by event name.

func GroupIDField added in v1.0.0

func GroupIDField(groupID string) zap.Field

func HTTPAddressToConnectProtocolTarget added in v1.0.0

func HTTPAddressToConnectProtocolTarget(httpAddress string) (target string, isTLS bool, err error)

HTTPAddressToConnectProtocolTarget maps from a URL to a Connect-Go target.

func HTTPAddressToGRPCTarget added in v0.5.1

func HTTPAddressToGRPCTarget(httpAddress string) (target string, isTLS bool, err error)

HTTPAddressToGRPCTarget maps from a URL, as defined in https://pkg.go.dev/net/url#URL, to a gRPC target, as defined in https://github.com/grpc/grpc/blob/master/doc/naming.md Use only with clients with classic gRPC bindings.

func HashField added in v1.0.0

func HashField(hash string) zap.Field

func HashJWTSignatureInput

func HashJWTSignatureInput(textToSign []byte) []byte

func HashOriginatorSignatureInput

func HashOriginatorSignatureInput(unsignedOriginatorEnvelope []byte) []byte

func HashPayerReportInput added in v0.4.0

func HashPayerReportInput(packedBytes []byte, domainSeparator common.Hash) common.Hash

func HashPayerSignatureInput

func HashPayerSignatureInput(originatorID uint32, unsignedClientEnvelope []byte) []byte

func HexDecode

func HexDecode(s string) ([]byte, error)

func HexEncode

func HexEncode(data []byte) string

func IdentifierField added in v1.1.0

func IdentifierField(id string) zap.Field

func InboxIDField added in v1.0.0

func InboxIDField(inboxID string) zap.Field

func Int32SliceToUint32Slice added in v0.5.0

func Int32SliceToUint32Slice(slice []int32) []uint32

func LastProcessedField added in v1.0.0

func LastProcessedField(lastProcessed int64) zap.Field

func LastSequenceIDField added in v1.0.0

func LastSequenceIDField(lastSequenceID int64) zap.Field

func LengthField added in v1.1.0

func LengthField(length int) zap.Field

func LimitField added in v1.0.0

func LimitField(limit uint8) zap.Field

func MethodField added in v1.0.0

func MethodField(method string) zap.Field

func MinInt added in v1.0.0

func MinInt(a, b int) int

func MinutesSinceEpoch added in v0.3.0

func MinutesSinceEpoch(timestamp time.Time) int32

func MinutesSinceEpochNow added in v0.3.0

func MinutesSinceEpochNow() int32

func NewConnectGRPCReplicationAPIClient added in v1.0.0

func NewConnectGRPCReplicationAPIClient(
	ctx context.Context,
	httpAddress string,
	extraDialOpts ...connect.ClientOption,
) (message_apiconnect.ReplicationApiClient, error)

NewConnectGRPCReplicationAPIClient builds a Connect-based client configured to speak classic gRPC. - Uses connect.WithGRPC() (wire-compatible gRPC over an http.Client). - Requires a schemeful base URL: "http(s)://host[:port]" ("host:port" will fail). - The http.Client must speak HTTP/2 (TLS) or h2c (plaintext AllowHTTP+DialTLS) for classic gRPC.

func NewConnectGRPCWebReplicationAPIClient added in v1.0.0

func NewConnectGRPCWebReplicationAPIClient(
	ctx context.Context,
	httpAddress string,
	extraDialOpts ...connect.ClientOption,
) (message_apiconnect.ReplicationApiClient, error)

NewConnectGRPCWebReplicationAPIClient builds a Connect-based gRPC-Web Replication API client. - Use connect.WithGRPCWeb() (not WithGRPC()). - gRPC-Web works over HTTP/1.1 and HTTP/2; a standard http.Client is sufficient. - Base URL must be schemeful: "http(s)://host[:port]" ("host:port" will fail).

func NewConnectGatewayAPIClient added in v1.0.0

func NewConnectGatewayAPIClient(
	ctx context.Context,
	httpAddress string,
	extraDialOpts ...connect.ClientOption,
) (payer_apiconnect.PayerApiClient, error)

NewConnectGatewayAPIClient builds a Connect-based Gateway API client. The consumer is responsible of passing any extra dial options, to make the connection gRPC or gRPC-Web.

func NewConnectMetadataAPIClient added in v1.0.0

func NewConnectMetadataAPIClient(
	ctx context.Context,
	httpAddress string,
	extraDialOpts ...connect.ClientOption,
) (metadata_apiconnect.MetadataApiClient, error)

NewConnectMetadataAPIClient builds a Connect-based Metadata API client. The consumer is responsible of passing any extra dial options, to make the connection gRPC or gRPC-Web.

func NewConnectReplicationAPIClient added in v1.0.0

func NewConnectReplicationAPIClient(
	ctx context.Context,
	httpAddress string,
	extraDialOpts ...connect.ClientOption,
) (message_apiconnect.ReplicationApiClient, error)

NewConnectReplicationAPIClient builds a Connect (default protocol) Replication API client.

  • Uses connect-go default (Connect protocol) over HTTP/1.1 or HTTP/2.
  • Requires a schemeful base URL (http:// or https://).
  • For HTTP/2 (TLS) or h2c (plaintext), pass an http.Client configured appropriately (e.g., via utils.BuildHTTP2Client).

func NewGRPCConn added in v1.0.0

func NewGRPCConn(
	httpAddress string,
	extraDialOpts ...grpc.DialOption,
) (*grpc.ClientConn, error)

NewGRPCConn builds a native grpc-go client for the given HTTP address.

  • Uses the standard grpc-go library (not connect-go).
  • Requires a schemeful base URL (http:// or https://).
  • For Connect-based gRPC clients, use NewConnectGRPCReplicationAPIClient instead.

Developer Note: Upstream caller is responsible for closing the returned connection.

func NewNullBytes added in v0.5.0

func NewNullBytes(b []byte) []byte

func NewNullInt16 added in v0.5.0

func NewNullInt16[T ~int16 | ~uint16](i *T) sql.NullInt16

func NewNullInt16Slice added in v0.5.0

func NewNullInt16Slice[T ~int16 | ~uint16](ints []T) []int16

func NewNullInt32 added in v0.5.0

func NewNullInt32[T ~int32 | ~uint32](i *T) sql.NullInt32

func NewNullInt64 added in v0.5.0

func NewNullInt64[T ~int64 | ~uint64](i *T) sql.NullInt64

NewNullInt64 is a generic version that accepts both int64 and uint64 types.

func NewNullTime added in v0.5.0

func NewNullTime(ts time.Time) sql.NullTime

func NodeHTTPAddressField added in v1.0.0

func NodeHTTPAddressField(nodeHTTPAddress string) zap.Field

func NodeOwnerField added in v1.0.0

func NodeOwnerField(nodeOwner string) zap.Field

func NodeSigningPublicKeyField added in v1.0.0

func NodeSigningPublicKeyField(nodeSigningPublicKey string) zap.Field

func NonceField added in v1.0.0

func NonceField(nonce uint64) zap.Field

func NsToDate added in v0.3.0

func NsToDate(ns int64) time.Time

func NumEnvelopesField added in v1.0.0

func NumEnvelopesField(numEnvelopes int) zap.Field

func NumNoncesField added in v1.0.0

func NumNoncesField(numNonces int32) zap.Field

func NumResponsesField added in v1.0.0

func NumResponsesField(numResponses int) zap.Field

func NumRowsField added in v1.0.0

func NumRowsField(numRows int32) zap.Field

func NumTopicsField added in v1.0.0

func NumTopicsField(numTopics int) zap.Field

func OriginatorIDField added in v1.0.0

func OriginatorIDField(originatorID uint32) zap.Field

func PackSortAndHashNodeIDs added in v1.0.0

func PackSortAndHashNodeIDs(nodeIDs []uint32) (common.Hash, error)

func ParseEcdsaPrivateKey

func ParseEcdsaPrivateKey(key string) (*ecdsa.PrivateKey, error)

func ParseEcdsaPublicKey

func ParseEcdsaPublicKey(key string) (*ecdsa.PublicKey, error)

ParseEcdsaPublicKey takes the stringified form of an ECDSA public key and return the *ecdsa.PublicKey

func ParseGroupID added in v0.5.0

func ParseGroupID(groupID []byte) ([16]byte, error)

func ParseInboxID added in v0.5.0

func ParseInboxID(inboxID []byte) ([32]byte, error)

func PayerAddressField added in v1.0.0

func PayerAddressField(payerAddress string) zap.Field

func PayerIDField added in v1.0.0

func PayerIDField(payerID int32) zap.Field

func PayerInfoField added in v1.0.0

func PayerInfoField(payerInfo *metadata_api.GetPayerInfoResponse_PayerInfo) zap.Field

func PayerReportIDField added in v1.0.0

func PayerReportIDField(reportID string) zap.Field

func PublicKeyField added in v1.0.0

func PublicKeyField(publicKey string) zap.Field

func RandomSleep

func RandomSleep(ctx context.Context, maxDuration time.Duration)

func ReasonField added in v1.0.0

func ReasonField(reason string) zap.Field

func RecipientField added in v1.0.0

func RecipientField(recipient string) zap.Field

func SequenceIDField added in v1.0.0

func SequenceIDField(sequenceID int64) zap.Field

func SettlementChainChainIDField added in v1.0.0

func SettlementChainChainIDField(chainID int64) zap.Field

func SignClientEnvelope added in v0.1.1

func SignClientEnvelope(
	originatorID uint32,
	unsignedClientEnvelope []byte,
	payerPrivateKey *ecdsa.PrivateKey,
) ([]byte, error)

func SliceToArray32 added in v0.4.0

func SliceToArray32(slice []byte) ([32]byte, error)

func StartSequenceIDField added in v1.0.0

func StartSequenceIDField(startSequenceID int64) zap.Field

func StartingNonceField added in v1.0.0

func StartingNonceField(startingNonce uint64) zap.Field

func TimeField added in v1.0.0

func TimeField(time time.Time) zap.Field

func ToAddressField added in v1.0.0

func ToAddressField(toAddress string) zap.Field

func TopicField added in v1.0.0

func TopicField(topic string) zap.Field

func Uint32FromBytes added in v0.5.0

func Uint32FromBytes(b []byte) (uint32, error)

func Uint32SliceToInt32Slice added in v0.5.0

func Uint32SliceToInt32Slice(slice []uint32) ([]int32, error)

func Uint32ToBytes added in v0.5.0

func Uint32ToBytes(u uint32) []byte

func Uint32ToInt32 added in v0.5.0

func Uint32ToInt32(u uint32) (int32, error)

func Uint64ToInt64 added in v0.5.0

func Uint64ToInt64(u uint64) (int64, error)

func Unimplemented

func Unimplemented(message string, unusedVariables ...any)

Unimplemented panics with a message indicating that the function is not implemented.

func UnmarshalClientEnvelope

func UnmarshalClientEnvelope(envelope []byte) (*envelopes.ClientEnvelope, error)

func UnmarshalOriginatorEnvelope

func UnmarshalOriginatorEnvelope(envelope []byte) (*envelopes.OriginatorEnvelope, error)

func UnmarshalUnsignedEnvelope

func UnmarshalUnsignedEnvelope(
	unsignedEnvelopeBytes []byte,
) (*envelopes.UnsignedOriginatorEnvelope, error)

func Unused

func Unused(unusedVariables ...any)

Unused is a no-op function that takes any number of arguments and does nothing with them. Useful for temporarily silencing "unused variable" warnings in development.

func WorkerNodeIDField added in v1.1.0

func WorkerNodeIDField(nodeID uint32) zap.Field

Types

This section is empty.

Directories

Path Synopsis
Package retryerrors implements the retryable error interface.
Package retryerrors implements the retryable error interface.

Jump to

Keyboard shortcuts

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