utils

package
v1.21.41 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: BSD-3-Clause Imports: 57 Imported by: 0

Documentation

Overview

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2020-2022-2025, Lux Industries Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Copyright (C) 2022-2025, Lux Industries, Inc. All rights reserved. See the file LICENSE for licensing terms.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddSingleQuotes

func AddSingleQuotes(s []string) []string

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

func Any

func Any[T any](input []T, f func(T) bool) bool

func AppendSlices

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

AppendSlices appends multiple slices into a single slice.

func ArchSupported

func ArchSupported(arch string) bool

func ByteSliceIsEVMGenesis added in v1.21.40

func ByteSliceIsEVMGenesis(bs []byte) bool

func ByteSliceToEVMGenesis added in v1.21.40

func ByteSliceToEVMGenesis(bs []byte) (core.Genesis, error)

func CleanupString

func CleanupString(s string) string

Cleans up a string by trimming \r and \n characters.

func CleanupStrings

func CleanupStrings(s []string) []string

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

func CombineSCPPath

func CombineSCPPath(host, path string) string

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

func Command

func Command(cmdLine string, params ...string) *exec.Cmd

Command returns an exec.Cmd for the given command line.

func ContainsIgnoreCase

func ContainsIgnoreCase(s, substr string) bool

ContainsIgnoreCase checks if the given string contains the specified substring, ignoring case.

func ConvertInterfaceToMap

func ConvertInterfaceToMap(value interface{}) (map[string]interface{}, error)

ConvertInterfaceToMap converts a given value to a map[string]interface{}.

func E2EConvertIP

func E2EConvertIP(ip string) string

E2EConvertIP maps an IP address to an E2E IP address.

func E2EDocker

func E2EDocker() bool

E2EDocker checks if we're running E2E tests in Docker mode

func E2ESuffix

func E2ESuffix(ip string) string

E2ESuffix extracts the last octet from an IP address

func ErrWrongArgCount

func ErrWrongArgCount(expected, got int) error

func ExpandHome

func ExpandHome(path string) string

ExpandHome expands ~ symbol to home directory

func ExtractPlaceholderValue

func ExtractPlaceholderValue(pattern, text string) (string, error)

ExtractValueFromBytes extracts a value from a byte array using a regular expression.

func FileCopy

func FileCopy(src string, dst string) error

FileCopy copies a file from src to dst.

func FileExists

func FileExists(filename string) bool

FileExists checks if a file exists.

func FileIsEVMGenesis added in v1.21.40

func FileIsEVMGenesis(genesisPath string) (bool, error)

func Filter

func Filter[T any](input []T, f func(T) bool) []T

func Find

func Find[T any](input []T, f func(T) bool) *T

func FindErrorLogs

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

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

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 stirng "54.321")

func GenerateDockerHostIDs

func GenerateDockerHostIDs(nodeCount int) ([]string, error)

GenerateDockerHostIDs generates unique IDs for Docker hosts

func GenerateDockerHostIPs

func GenerateDockerHostIPs(nodeCount int) ([]string, error)

GenerateDockerHostIPs generates IP addresses for Docker hosts

func GetANRContext

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

Context for ANR network operations

func GetAPIContext

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

Context for API requests

func GetAPILargeContext

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

Context for API requests with large timeout

func GetBlockchainTx

func GetBlockchainTx(endpoint string, blockchainID ids.ID) (*txs.CreateChainTx, error)

func GetCLIVersion

func GetCLIVersion() string

func GetChainID

func GetChainID(endpoint string, chainName string) (ids.ID, error)

func GetChainIDs

func GetChainIDs(endpoint string, chainName string) (string, string, error)

func GetCodespaceURL

func GetCodespaceURL(url string) (string, error)

func GetDefaultBlockchainAirdropKeyName

func GetDefaultBlockchainAirdropKeyName(blockchainName string) string

func GetGitCommit

func GetGitCommit(gitRepoURL string) string

GetGitCommit takes a Git repository URL that contains commit ID and returns the commit ID Example: https://github.com/luxfi/hypersdk/pull/772/commits/b88acfb370f5aeb83a000aece2d72f28154410a5 Should return b88acfb370f5aeb83a000aece2d72f28154410a5

func GetIPPort

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

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

func GetIndexInSlice

func GetIndexInSlice[T comparable](list []T, element T) (int, error)

func GetJSONKey

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

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

GetKeyNames returns all key names in the key directory

func GetL1ValidatorUptimeSeconds

func GetL1ValidatorUptimeSeconds(rpcURL string, nodeID ids.NodeID) (uint64, error)

GetL1ValidatorUptimeSeconds returns the uptime of the L1 validator

func GetNetworkBalance

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

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

func GetNodeID

func GetNodeID(endpoint string) (
	string,
	string,
	string,
	error,
)

func GetNodeParams

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

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

func GetProcess

func GetProcess(pid int) (*os.Process, error)

func GetRealFilePath

func GetRealFilePath(path string) string

func GetRemainingValidationTime

func GetRemainingValidationTime(networkEndpoint string, nodeID ids.NodeID, subnetID ids.ID, startTime time.Time) (time.Duration, error)

func GetRemoteComposeFile

func GetRemoteComposeFile() string

RemoteComposeFile returns the path to the remote docker-compose file

func GetRemoteComposeServicePath

func GetRemoteComposeServicePath(serviceName string, dirs ...string) string

GetRemoteComposeServicePath returns the path to the remote service directory

func GetRepoFromCommitURL

func GetRepoFromCommitURL(gitRepoURL string) (string, string)

GetRepoFromCommitURL takes a Git repository URL that contains commit ID and returns the cloneable Git Repo URL (ends in .git) and the repo directory name Example: https://github.com/luxfi/hypersdk/pull/772/commits/b88acfb370f5aeb83a000aece2d72f28154410a5 Should return https://github.com/luxfi/hypersdk

func GetSCPCommandString

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

func GetSCPTargetPath(ip, path string) string

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

func GetSHA256FromDisk

func GetSHA256FromDisk(binPath string) (string, error)

func GetSSHConnectionString

func GetSSHConnectionString(publicIP, certFilePath string) string

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

func GetTimedContext

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

Timed Context

func GetURIHostPortAndPath

func GetURIHostPortAndPath(uri string) (string, uint32, string, error)

Get the host, port and path from a URL.

func GetUserIPAddress

func GetUserIPAddress() (string, error)

GetUserIPAddress retrieves the IP address of the user.

func HandleTracking

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

func HandleUserMetricsPreference

func HandleUserMetricsPreference(app interface{}) error

func InsideCodespace

func InsideCodespace() bool

func IsE2E

func IsE2E() bool

IsE2E checks if we're running in E2E test mode

func IsExecutable

func IsExecutable(filename string) bool

IsExecutable checks if a file is executable.

func IsSSHAgentAvailable

func IsSSHAgentAvailable() bool

IsSSHAgentAvailable checks if the SSH agent is available.

func IsSSHAgentIdentityValid

func IsSSHAgentIdentityValid(identity string) (bool, error)

func IsSSHPubKey

func IsSSHPubKey(pubkey string) bool

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

func IsUnsignedSlice

func IsUnsignedSlice(n []int) bool

IsUnsignedSlice returns true if all elements in the slice are unsigned integers.

func IsValidIP

func IsValidIP(ipStr string) bool

func IsValidIPPort

func IsValidIPPort(ipPortPair string) bool

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

func IsValidSemanticVersion

func IsValidSemanticVersion(version string, component string) bool

func IsValidURL

func IsValidURL(urlString string) bool

IsValidURL checks if a URL is valid.

func ListSSHAgentIdentities

func ListSSHAgentIdentities() ([]string, error)

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

func LogLevelToEmoji

func LogLevelToEmoji(logLevel string) (string, error)

func MapWithError

func MapWithError[T, U any](input []T, f func(T) (U, error)) ([]U, error)

func MkDirWithTimestamp

func MkDirWithTimestamp(dirPrefix string) (string, error)

func NetworkIDFromGenesis

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

NetworkIDFromGenesis returns the network ID in the given genesis

func NewBlsSecretKeyBytes

func NewBlsSecretKeyBytes() ([]byte, error)

func NewLogger

func NewLogger(
	logName string,
	logLevelStr string,
	defaultLogLevelStr string,
	logDir string,
	logToStdout bool,
	print func(string, ...interface{}),
) (luxlog.Logger, error)

func NewMLDSAKeyBytes added in v1.9.11

func NewMLDSAKeyBytes() ([]byte, error)

NewMLDSAKeyBytes generates a new ML-DSA private key and returns it as bytes Uses MLDSA65 (192-bit security, NIST Level 3) as the default

func NewRingtailKeyBytes added in v1.9.11

func NewRingtailKeyBytes() ([]byte, error)

NewRingtailKeyBytes generates a new secp256k1 private key and returns it as bytes Note: "Ringtail" is a placeholder name - we use standard secp256k1 for now

func NonEmptyDirectory

func NonEmptyDirectory(dirName string) (bool, error)

func PointersSlice

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

func PrintMetricsOptOutPrompt

func PrintMetricsOptOutPrompt()

func PrintUnreportedErrors

func PrintUnreportedErrors(
	errors []error,
	returnedError error,
	print func(string, ...interface{}),
)

PrintUnreportedErrors takes a list of errors obtained by a routine, and the main error it is going to report, and prints to the user the unreported errors only, avoiding duplications

func RandomString

func RandomString(length int) string

RandomString generates a random string of the specified length.

func ReadFile

func ReadFile(filePath string) (string, error)

ReadFile reads a file and returns the contents as a string

func ReadGoVersion

func ReadGoVersion(filePath string) (string, error)

ReadGoVersion reads the Go version from the go.mod file

func ReadJSON

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

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

func ReadLongString

func ReadLongString(msg string, args ...interface{}) (string, error)

ReadLongString reads a long string from the user input.

func ReadSSHAgentIdentityPublicKey

func ReadSSHAgentIdentityPublicKey(identityName string) (string, error)

func RemoveFromSlice

func RemoveFromSlice[T comparable](input []T, toRemove T) []T

func RemoveLineCleanChars added in v1.9.5

func RemoveLineCleanChars(s string) string

RemoveLineCleanChars removes ANSI escape codes and other terminal control characters from a string This is useful for cleaning up command output before pattern matching

func ReplaceUserHomeWithTilde

func ReplaceUserHomeWithTilde(path string) string

ReplaceUserHomeWithTilde replaces user home directory with ~

func SaveDockerComposeFile

func SaveDockerComposeFile(content []byte, path string) error

SaveDockerComposeFile saves Docker Compose configuration to a file

func SaveQuantumKeys added in v1.9.11

func SaveQuantumKeys(nodeDir string, keys *QuantumKeys) error

SaveQuantumKeys saves all quantum keys to the specified directory

func ScriptLog

func ScriptLog(nodeID string, msg string, args ...interface{}) string

func SearchSHA256File

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

func SetupExecFile

func SetupExecFile(
	log luxlog.Logger,
	src string,
	dst string,
) error

SetupExecFile copies a file into destination and set it to have exec perms, if destination either does not exists, or is not executable

func SetupRealtimeCLIOutput

func SetupRealtimeCLIOutput(
	cmd *exec.Cmd,
	redirectStdout bool,
	redirectStderr bool,
) (*bytes.Buffer, *bytes.Buffer)

func SizeInKB

func SizeInKB(path string) (int64, error)

SizeInKB returns the size of a file or directory.

func SplitComaSeparatedInt

func SplitComaSeparatedInt(s string) []int

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

func SplitComaSeparatedString

func SplitComaSeparatedString(s string) []string

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

func SplitKeyValueStringToMap

func SplitKeyValueStringToMap(str string, delimiter string) (map[string]string, error)

SplitKeyValueStringToMap splits a string with multiple key-value pairs separated by delimiter. Delimiter must be a single character

func SplitRPCURI added in v1.9.11

func SplitRPCURI(requestURI string) (string, string, error)

SplitRPCURI 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

func SplitSCPPath(path string) (string, string)

SplitSCPPath splits the given path into host and path.

func SplitSliceAt

func SplitSliceAt[T any](slice []T, index int) ([]T, []T)

SplitSliceAt splits a slice at the given index and returns two new slices.func SplitSliceAt[T any](slice []T, index int) ([]T, []T) {

func SplitStringWithQuotes

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

SplitStringWithQuotes split string with a rune comma ignore quoted

func StartDockerCompose

func StartDockerCompose(dockerComposeFile string) error

StartDockerCompose starts Docker Compose with the given configuration file

func StringValue

func StringValue(data map[string]interface{}, key string) (string, error)

StringValue returns the value of a key in a map as a string.

func Sum

func Sum(s []int) int

Sum calculates the sum of all the elements in the given slice of integers.

func SupportedLuxdArch

func SupportedLuxdArch() []string

func TimedFunction

func TimedFunction[T any](
	f func() (T, error),
	name string,
	timeout time.Duration,
) (T, error)

TimedFunction is a function that executes the given function `f` within a specified timeout duration.

func TimedFunctionWithRetry

func TimedFunctionWithRetry[T any](
	f func() (T, error),
	name string,
	timeout time.Duration,
	maxAttempts int,
	retryInterval time.Duration,
) (T, error)

TimedFunctionWithRetry is a function that executes the given function `f` within a specified timeout duration.

func ToBLSPoP

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

func ToMLDSAPublicKey added in v1.9.11

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

ToMLDSAPublicKey converts ML-DSA private key bytes to public key bytes

func ToNodeID

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

func ToRingtailPublicKey added in v1.9.11

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

ToRingtailPublicKey converts secp256k1 private key bytes to public key bytes

func TrackMetrics

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

func TrimHexa

func TrimHexa(s string) string

Removes the leading 0x/0X part of a hexadecimal string representation

func Unique

func Unique(slice []string) []string

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

func UserHomePath

func UserHomePath(filePath ...string) string

UserHomePath returns the absolute path of a file located in the user's home directory.

func VMID

func VMID(vmName string) (ids.ID, error)

func ValidateJSON

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

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

func WriteJSON

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

WriteJSON writes the provided interface to a JSON file

func WriteStringToFile

func WriteStringToFile(filePath string, data string) error

WriteStringToFile writes a string to a file

Types

type QuantumKeys added in v1.9.11

type QuantumKeys struct {
	BLSSecretKey      []byte
	BLSPublicKey      []byte
	BLSPoP            []byte
	RingtailSecretKey []byte
	RingtailPublicKey []byte
	MLDSASecretKey    []byte
	MLDSAPublicKey    []byte
}

QuantumKeys holds all quantum-safe keys for a validator

func GenerateAllQuantumKeys added in v1.9.11

func GenerateAllQuantumKeys() (*QuantumKeys, error)

GenerateAllQuantumKeys generates BLS, Ringtail, and ML-DSA keys for a validator

func GetQuantumNodeParams added in v1.9.11

func GetQuantumNodeParams(nodeDir string) (
	ids.NodeID,
	*QuantumKeys,
	error,
)

GetQuantumNodeParams returns node id and all quantum public keys

func LoadQuantumKeys added in v1.9.11

func LoadQuantumKeys(nodeDir string) (*QuantumKeys, error)

LoadQuantumKeys loads all quantum keys from the specified directory

Jump to

Keyboard shortcuts

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