utils

package
v1.16.44 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: BSD-3-Clause Imports: 45 Imported by: 0

README

Lux Utilities Package

Common utilities extracted from node package for use across all Lux packages.

Documentation

Overview

Package utils provides common utility functions used throughout the SDK.

Index

Constants

View Source
const CGOEnabled = true

CGOEnabled indicates whether CGO is available. This file is only compiled when CGO is enabled.

Variables

This section is empty.

Functions

func AddSingleQuotes added in v0.2.0

func AddSingleQuotes(s []string) []string

AddSingleQuotes adds single quotes to each string in the given slice.

func AppendSlices

func AppendSlices[T any](slices ...[]T) []T

AppendSlices appends multiple slices into a single slice.

func Belongs

func Belongs[T comparable](input []T, elem T) bool

func ByteSliceIsEVMGenesis added in v1.3.8

func ByteSliceIsEVMGenesis(bytes []byte) bool

ByteSliceIsEVMGenesis checks if a byte slice is a EVM genesis

func CleanupString added in v0.2.0

func CleanupString(s string) string

CleanupString cleans up a string by trimming \r and \n characters.

func CleanupStrings added in v0.2.0

func CleanupStrings(s []string) []string

CleanupStrings cleans up a slice of strings by trimming \r and \n characters.

func CombineSCPPath added in v0.2.0

func CombineSCPPath(host, path string) string

CombineSCPPath combines the given host and path into a single item for scp.

func DeleteIndex added in v1.16.41

func DeleteIndex[S ~[]E, E any](s S, i int) S

DeleteIndex moves the last element in the slice to index [i] and shrinks the size of the slice by 1.

This is an O(1) operation that allows the removal of an element from a slice when the order of the slice is not important.

If [i] is out of bounds, this function will panic.

func Detach added in v1.16.41

func Detach(ctx context.Context) context.Context

func DirExists

func DirExists(dirName string) bool

DirExists checks if a directory exists.

func Err added in v1.16.41

func Err(errors ...error) error

func ExpandHome

func ExpandHome(path string) string

ExpandHome expands ~ symbol to home directory

func FileExists

func FileExists(filename string) bool

FileExists checks if a file exists.

func FindErrorLogs added in v0.2.0

func FindErrorLogs(rootDirs ...string)

FindErrorLogs is a utility function, we will NOT do error handling, as this is supposed to be called during error handling itself we don't want to make it even more complex

func FormatAmount added in v0.2.0

func FormatAmount(amount *big.Int, decimals uint8) string

FormatAmount formats an amount of base units as a string representing the amount in the given denomination. (i.e. An amount of 54321 with a decimals value of 3 results in the string "54.321")

func GetAPIContext

func GetAPIContext() (context.Context, context.CancelFunc)

GetAPIContext returns a context for API requests.

func GetAPILargeContext

func GetAPILargeContext() (context.Context, context.CancelFunc)

GetAPILargeContext returns a context for API requests with large timeout.

func GetAddressBalance added in v1.16.39

func GetAddressBalance(address ids.ShortID, endpoint string) (uint64, error)

GetAddressBalance returns the LUX balance of an address using the given endpoint

func GetBlockchainIDFromAlias added in v0.2.1

func GetBlockchainIDFromAlias(endpoint string, alias string) (ids.ID, error)

GetBlockchainIDFromAlias gets a blockchain ID from its alias on the network.

func GetCLIVersion added in v0.2.0

func GetCLIVersion() string

func GetChainID added in v0.2.1

func GetChainID(genesisData []byte) (*big.Int, error)

GetChainID extracts the chain ID from genesis data

func GetDefaultBlockchainAirdropKeyName added in v0.2.1

func GetDefaultBlockchainAirdropKeyName(blockchainName string) string

GetDefaultBlockchainAirdropKeyName returns the default key name for blockchain airdrops

func GetIPPort added in v0.2.0

func GetIPPort(uri string) (netip.AddrPort, error)

GetIPPort parses netip.IPPort from string that also may include http schema

func GetJSONKey added in v0.2.0

func GetJSONKey[T any](m map[string]interface{}, key string) (T, error)

GetJSONKey retrieves a value from a map by key and returns it as the specified type

func GetKeyNames added in v0.2.1

func GetKeyNames(keyDir string, includeEwoq bool) ([]string, error)

GetKeyNames returns a list of key names from the given directory.

func GetNetworkBalance added in v0.2.0

func GetNetworkBalance(address ids.ShortID, network models.Network) (uint64, error)

GetNetworkBalance returns the balance of an address on the P-chain

func GetNodeParams added in v0.2.0

func GetNodeParams(nodeDir string) (
	ids.NodeID,
	[]byte,
	[]byte,
	error,
)

GetNodeParams returns node id, bls public key and bls proof of possession

func GetSCPCommandString added in v0.2.0

func GetSCPCommandString(certFilePath string, sourceIP, sourcePath string, destIP, destPath string, recursive, withCompression bool) (string, error)

GetSCPCommandString returns the SCP command string for the given source and destination paths.

func GetSCPTargetPath added in v0.2.0

func GetSCPTargetPath(ip, path string) string

GetSCPTargetPath returns the target path for the given source path and target directory.

func GetSHA256FromDisk added in v0.2.0

func GetSHA256FromDisk(binPath string) (string, error)

func GetSSHConnectionString added in v0.2.0

func GetSSHConnectionString(publicIP, certFilePath string) string

GetSSHConnectionString returns the SSH connection string for the given public IP and certificate file path.

func GetStacktrace added in v1.16.41

func GetStacktrace(all bool) string

func GetTimedContext

func GetTimedContext(timeout time.Duration) (context.Context, context.CancelFunc)

GetTimedContext returns a context with the given timeout.

func GetUserIPAddress added in v0.2.0

func GetUserIPAddress() (string, error)

GetUserIPAddress retrieves the IP address of the user.

func HandleTracking added in v0.2.0

func HandleTracking(cmd *cobra.Command, app interface{}, flags map[string]string)

func HandleUserMetricsPreference added in v0.2.0

func HandleUserMetricsPreference(app interface{}) error

func IsSSHAgentAvailable added in v0.2.0

func IsSSHAgentAvailable() bool

IsSSHAgentAvailable checks if the SSH agent is available.

func IsSSHAgentIdentityValid added in v0.2.0

func IsSSHAgentIdentityValid(identity string) (bool, error)

func IsSSHPubKey added in v0.2.0

func IsSSHPubKey(pubkey string) bool

IsSSHPubKey checks if the given string is a valid SSH public key.

func IsSortedAndUnique added in v1.16.41

func IsSortedAndUnique[T Sortable[T]](s []T) bool

Returns true iff the elements in [s] are unique and sorted.

func IsSortedAndUniqueByHash added in v1.16.41

func IsSortedAndUniqueByHash[T ~[]byte](s []T) bool

Returns true iff the elements in [s] are unique and sorted based by their hashes.

func IsSortedAndUniqueOrdered added in v1.16.41

func IsSortedAndUniqueOrdered[T cmp.Ordered](s []T) bool

Returns true iff the elements in [s] are unique and sorted.

func IsSortedBytes added in v1.16.41

func IsSortedBytes[T ~[]byte](s []T) bool

Returns true iff the elements in [s] are sorted.

func IsSubPath added in v1.16.38

func IsSubPath(childPath, parentPath string) bool

IsSubPath checks if childPath is inside parentPath. Both paths should be absolute paths. Returns true if childPath is a subdirectory or file inside parentPath.

func IsValidIP added in v0.2.0

func IsValidIP(ipStr string) bool

func IsValidIPPort added in v0.2.0

func IsValidIPPort(ipPortPair string) bool

IsValidIPPort checks if an string IP:port pair is valid.

func IsValidURL added in v0.2.0

func IsValidURL(urlString string) bool

IsValidURL checks if a URL is valid.

func ListSSHAgentIdentities added in v0.2.0

func ListSSHAgentIdentities() ([]string, error)

ListSSHAgentIdentities returns a list of SSH identities from ssh-agent.

func Map

func Map[T, U any](input []T, f func(T) U) []U

func NetworkIDFromGenesis added in v0.2.0

func NetworkIDFromGenesis(genesis []byte) (uint32, error)

NetworkIDFromGenesis returns the network ID in the given genesis

func NewBlsSecretKeyBytes added in v0.2.0

func NewBlsSecretKeyBytes() ([]byte, error)

func PointersSlice added in v0.2.1

func PointersSlice[T any](values []T) []*T

PointersSlice converts a slice of values to a slice of pointers

func PrintMetricsOptOutPrompt added in v0.2.0

func PrintMetricsOptOutPrompt()

func RandomBytes added in v1.16.41

func RandomBytes(n int) []byte

RandomBytes returns a slice of n random bytes Intended for use in testing

func ReadJSON added in v0.2.0

func ReadJSON(path string, v interface{}) error

ReadJSON reads a JSON file and unmarshals it into the provided interface

func ReadSSHAgentIdentityPublicKey added in v0.2.0

func ReadSSHAgentIdentityPublicKey(identityName string) (string, error)

func Retry

func Retry[T any](
	fn func() (T, error),
	maxAttempts int,
	retryInterval time.Duration,
) (T, error)

Retry retries the given function until it succeeds or the maximum number of attempts is reached.

func RetryWithContextGen

func RetryWithContextGen[T any](
	ctxGen func() (context.Context, context.CancelFunc),
	fn func(context.Context) (T, error),
	maxAttempts int,
	retryInterval time.Duration,
) (T, error)

RetryWithContextGen retries the given function until it succeeds or the maximum number of attempts is reached. For each retry, it generates a fresh context to be used on the call.

func SearchSHA256File added in v0.2.0

func SearchSHA256File(file []byte, toSearch string) (string, error)

func Sort added in v1.16.41

func Sort[T Sortable[T]](s []T)

Sorts the elements of [s].

func SortByHash added in v1.16.41

func SortByHash[T ~[]byte](s []T)

Sorts the elements of [s] based on their hashes.

func SplitComaSeparatedInt added in v0.2.0

func SplitComaSeparatedInt(s string) []int

SplitComaSeparatedInt splits a comma-separated string into a slice of integers.

func SplitComaSeparatedString added in v0.2.0

func SplitComaSeparatedString(s string) []string

SplitComaSeparatedString splits and trims a comma-separated string into a slice of strings.

func SplitLuxgoRPCURI added in v0.2.0

func SplitLuxgoRPCURI(requestURI string) (string, string, error)

SplitLuxgoRPCURI splits the RPC URI into `endpoint` and `chain`. Reverse operation of `fmt.Sprintf("%s/ext/bc/%s", endpoint, chain)`. Returns the `uri` and `chain` as strings, or an error if the request URI is invalid.

func SplitSCPPath added in v0.2.0

func SplitSCPPath(path string) (string, string)

SplitSCPPath splits the given path into host and path.

func SplitStringWithQuotes added in v0.2.0

func SplitStringWithQuotes(str string, r rune) []string

SplitStringWithQuotes splits a string by the given rune, ignoring quoted segments.

func ToBLSPoP added in v0.2.0

func ToBLSPoP(keyBytes []byte) (
	[]byte,
	[]byte,
	error,
)

func ToNodeID added in v0.2.0

func ToNodeID(certBytes []byte) (ids.NodeID, error)

func TrackMetrics added in v0.2.0

func TrackMetrics(command *cobra.Command, flags map[string]string)

func TrimHexa added in v0.2.0

func TrimHexa(s string) string

TrimHexa removes the leading 0x/0X part of a hexadecimal string representation.

func Uint32Sort

func Uint32Sort(arr []uint32)

func Unique

func Unique[T comparable](arr []T) []T

Unique returns a new slice containing only the unique elements from the input slice.

func ValidateJSON added in v0.2.0

func ValidateJSON(path string) ([]byte, error)

ValidateJSON takes a json string and returns it's byte representation if it contains valid JSON

func WrapContext

func WrapContext[T any](
	f func() (T, error),
) func(context.Context) (T, error)

WrapContext adds a context based timeout to a given function

func WriteJSON added in v0.2.0

func WriteJSON(path string, v interface{}) error

WriteJSON writes the provided interface to a JSON file

func Zero added in v1.16.41

func Zero[T any]() T

Zero returns the zero value of any type T.

Types

type Account added in v0.2.1

type Account struct {
	Balance interface{}       `json:"balance"`        // Can be string (hex) or number
	Code    interface{}       `json:"code,omitempty"` // Can be string (hex) or []byte
	Storage map[string]string `json:"storage,omitempty"`
	Nonce   interface{}       `json:"nonce,omitempty"` // Can be string (hex) or uint64
}

Account represents an account in the genesis allocation

func (*Account) GetBalance added in v1.3.0

func (a *Account) GetBalance() *big.Int

GetBalance returns the balance as a big.Int

func (*Account) GetCode added in v1.3.0

func (a *Account) GetCode() []byte

GetCode returns the code as a byte slice

func (*Account) UnmarshalJSON added in v1.0.1

func (a *Account) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler for Account to handle hex string balances

type Atomic added in v1.16.41

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

func NewAtomic added in v1.16.41

func NewAtomic[T any](value T) *Atomic[T]

func (*Atomic[T]) Get added in v1.16.41

func (a *Atomic[T]) Get() T

func (*Atomic[T]) MarshalJSON added in v1.16.41

func (a *Atomic[T]) MarshalJSON() ([]byte, error)

func (*Atomic[T]) Set added in v1.16.41

func (a *Atomic[T]) Set(value T)

func (*Atomic[T]) Swap added in v1.16.41

func (a *Atomic[T]) Swap(value T) T

func (*Atomic[T]) UnmarshalJSON added in v1.16.41

func (a *Atomic[T]) UnmarshalJSON(b []byte) error

type BytesPool added in v1.16.41

type BytesPool [intSize]sync.Pool

BytesPool tracks buckets of available buffers to be allocated. Each bucket allocates buffers of the following length:

0 1 3 7 15 31 63 127 ... MaxInt

In order to allocate a buffer of length 19 (for example), we calculate the number of bits required to represent 19 (5). And therefore allocate a slice from bucket 5, which has length 31. This is the bucket which produces the smallest slices that are at least length 19.

When replacing a buffer of length 19, we calculate the number of bits required to represent 20 (5). And therefore place the slice into bucket 4, which has length 15. This is the bucket which produces the largest slices that a length 19 slice can be used for.

func NewBytesPool added in v1.16.41

func NewBytesPool() *BytesPool

func (*BytesPool) Get added in v1.16.41

func (p *BytesPool) Get(length int) *[]byte

Get returns a non-nil pointer to a slice with the requested length.

It is not guaranteed for the returned bytes to have been zeroed.

func (*BytesPool) Put added in v1.16.41

func (p *BytesPool) Put(bytes *[]byte)

Put takes ownership of a non-nil pointer to a slice of bytes.

Note: this function takes ownership of the underlying array. So, the length of the provided slice is ignored and only its capacity is used.

type EVMGenesis added in v1.3.8

type EVMGenesis struct {
	Config     map[string]interface{} `json:"config"`
	Alloc      map[string]Account     `json:"alloc"`
	Timestamp  interface{}            `json:"timestamp,omitempty"` // Can be string (hex) or uint64
	GasLimit   interface{}            `json:"gasLimit"`            // Can be string (hex) or uint64
	Difficulty string                 `json:"difficulty,omitempty"`
	MixHash    string                 `json:"mixHash,omitempty"`
	Coinbase   string                 `json:"coinbase,omitempty"`
	Number     string                 `json:"number,omitempty"`
	GasUsed    string                 `json:"gasUsed,omitempty"`
	ParentHash string                 `json:"parentHash,omitempty"`
	Nonce      string                 `json:"nonce,omitempty"`
	ExtraData  string                 `json:"extraData,omitempty"`
}

EVMGenesis represents a EVM genesis configuration

func ByteSliceToEVMGenesis added in v1.3.8

func ByteSliceToEVMGenesis(bytes []byte) (*EVMGenesis, error)

ByteSliceToEVMGenesis converts a byte slice to a EVM genesis

func (*EVMGenesis) UnmarshalJSON added in v1.3.8

func (g *EVMGenesis) UnmarshalJSON(data []byte) error

UnmarshalJSON custom unmarshaler to handle hex string or numeric values

type Sortable added in v1.16.41

type Sortable[T any] interface {
	Compare(T) int
}

Directories

Path Synopsis
Package filesystem is a generated GoMock package.
Package filesystem is a generated GoMock package.
filesystemmock
Package filesystemmock is a generated GoMock package.
Package filesystemmock is a generated GoMock package.
iteratormock
Package iteratormock is a generated GoMock package.
Package iteratormock is a generated GoMock package.
Package json provides JSON serialization utilities for numeric types.
Package json provides JSON serialization utilities for numeric types.
math
Package profiler provides CPU, memory, and lock profiling utilities.
Package profiler provides CPU, memory, and lock profiling utilities.

Jump to

Keyboard shortcuts

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