utils

package
v1.9.2 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2025 License: BSD-3-Clause Imports: 52 Imported by: 0

Documentation

Overview

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

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

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

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

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

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

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

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

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

Copyright (C) 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 ByteSliceIsSubnetEvmGenesis

func ByteSliceIsSubnetEvmGenesis(bs []byte) bool

func ByteSliceToSubnetEvmGenesis

func ByteSliceToSubnetEvmGenesis(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 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 FileIsSubnetEVMGenesis

func FileIsSubnetEVMGenesis(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 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 GetL1ValidatorUptimeSeconds

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

GetL1ValidatorUptimeSeconds returns the uptime of the L1 validator

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 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 NewBlsSecretKeyBytes

func NewBlsSecretKeyBytes() ([]byte, error)

func NewLogger

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

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 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 ReplaceUserHomeWithTilde

func ReplaceUserHomeWithTilde(path string) string

ReplaceUserHomeWithTilde replaces user home directory with ~

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 logging.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 SplitLuxgoRPCURI

func SplitLuxgoRPCURI(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 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 ToNodeID

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

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 WriteStringToFile

func WriteStringToFile(filePath string, data string) error

WriteStringToFile writes a string to a file

Types

This section is empty.

Jump to

Keyboard shortcuts

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