Documentation ¶
Overview ¶
Package utils is used for common functions and tools used across the codebase.
Index ¶
- Constants
- Variables
- func AddHexPrefix(str string) string
- func BatchSplit[T any](list []T, max int) (out [][]T, err error)
- func BoxOutput(errorMsgTemplate string, errorMsgValues ...interface{}) string
- func CheckPasswordHash(password, hash string) bool
- func ConcatBytes(bufs ...[]byte) []byte
- func ContextFromChan(chStop chan struct{}) (context.Context, context.CancelFunc)
- func ContextFromChanWithTimeout(chStop chan struct{}, timeout time.Duration) (context.Context, context.CancelFunc)
- func DeleteUnstable[T any](s []T, i int) []T
- func DurationFromNow(t time.Time) time.Duration
- func EnsureDirAndMaxPerms(path string, perms os.FileMode) error
- func EnsureFileMaxPerms(file *os.File, perms os.FileMode) error
- func EnsureFilepathMaxPerms(filepath string, perms os.FileMode) (err error)
- func FileExists(name string) (bool, error)
- func FiniteTicker(period time.Duration, onTick func()) func()
- func FormatJSON(v interface{}) ([]byte, error)
- func GenerateEthPrefixedMsgHash(msg []byte) (hash common.Hash)
- func GenerateEthSignature(privateKey *ecdsa.PrivateKey, msg []byte) (signature []byte, err error)
- func GetSignersEthAddress(msg []byte, sig []byte) (recoveredAddr common.Address, err error)
- func HashPassword(password string) (string, error)
- func ISO8601UTC(t time.Time) string
- func IsEmpty(bytes []byte) bool
- func IsFileOwnedByChainlink(fileInfo os.FileInfo) (bool, error)
- func IsZero[C comparable](val C) bool
- func LeftPadBitString(input string, length int) string
- func MultiErrorList(err error) (int, error)
- func MustNewPeerID() string
- func MustUnmarshalToMap(input string) map[string]interface{}
- func NewBytes32ID() string
- func NewRedialBackoff() backoff.Backoff
- func NewSecret(n int) string
- func NewThreadControl() *threadControl
- func NormalizedJSON(val []byte) (string, error)
- func PasswordFromFile(pwdFile string) (string, error)
- func Sha256(in string) (string, error)
- func StringToHex(in string) string
- func ToDecimal(input interface{}) (decimal.Decimal, error)
- func TooPermissive(fileMode, maxAllowedPerms os.FileMode) bool
- func UnmarshalToMap(input string) (map[string]interface{}, error)
- func UnwrapError(err error) []error
- func ValidateCronSchedule(schedule string) error
- func VerifyPasswordComplexity(password string, disallowedStrings ...string) (merr error)
- func WithCloseChan(parentCtx context.Context, chStop chan struct{}) (context.Context, context.CancelFunc)
- func WithJitter(d time.Duration) time.Duration
- func WriteFileWithMaxPerms(path string, data []byte, perms os.FileMode) (err error)
- type BackoffTicker
- type BoundedPriorityQueue
- type BoundedQueue
- type Clock
- type CronTicker
- type DeferableWriteCloser
- type ErrorBuffer
- type FileSize
- type Hash
- type KeyedMutex
- type PausableTicker
- type PlainHexBytes
- type ResettableTimer
- type ScryptConfigReader
- type ScryptParams
- type StartStopOnce
- type StopChandeprecated
- type StopRChandeprecated
- type ThreadControl
- type TickerBase
Constants ¶
const ( KB = 1000 MB = 1000 * KB GB = 1000 * MB TB = 1000 * GB )
nolint
const ( // FastN is a shorter N parameter for testing FastN = 2 // FastP is a shorter P parameter for testing FastP = 1 )
const DefaultSecretSize = 48
DefaultSecretSize is the entropy in bytes to generate a base64 string of 64 characters.
const EthSignedMessagePrefix = "\x19Ethereum Signed Message:\n"
const HashLength = 32
const MinRequiredLen = 16
const PasswordComplexityRequirements = `` /* 172-byte string literal not displayed */
PasswordComplexityRequirements defines the complexity requirements message Note that adding an entropy requirement wouldn't add much, since a 16 character password already has an entropy score of 75 even if it's all lowercase characters
Variables ¶
var ( ErrPasswordWhitespace = errors.New("leading/trailing whitespace detected in password") ErrEmptyPasswordInFile = errors.New("detected empty password in password file") )
var ( ErrMsgHeader = fmt.Sprintf(` Expected password complexity: Must be at least %d characters long Must not comprise: Leading or trailing whitespace A user's API email Faults: `, MinRequiredLen) ErrWhitespace = errors.New("password contains a leading or trailing whitespace") )
var ( ErrAlreadyStopped = errors.New("already stopped") ErrCannotStopUnstarted = errors.New("cannot stop unstarted service") )
var DefaultScryptParams = ScryptParams{N: keystore.StandardScryptN, P: keystore.StandardScryptP}
DefaultScryptParams is for use in production. It used geth's standard level of encryption and is relatively expensive to decode. Avoid using this in tests.
var FastScryptParams = ScryptParams{N: FastN, P: FastP}
FastScryptParams is for use in tests, where you don't want to wear out your CPU with expensive key derivations, do not use it in production, or your encrypted keys will be easy to brute-force!
var LeadingWhitespace = regexp.MustCompile(`^\s+`)
var TrailingWhitespace = regexp.MustCompile(`\s+$`)
Functions ¶
func AddHexPrefix ¶
AddHexPrefix adds the prefix (0x) to a given hex string.
func BatchSplit ¶
BatchSplit splits an slices into an slices of slicess with a maximum length
func BoxOutput ¶
BoxOutput formats its arguments as fmt.Printf, and encloses them in a box of arrows pointing at their content, in order to better highlight it. See ExampleBoxOutput
func CheckPasswordHash ¶
CheckPasswordHash wraps around bcrypt.CompareHashAndPassword for a friendlier API.
func ConcatBytes ¶
ConcatBytes appends a bunch of byte arrays into a single byte array
func ContextFromChan ¶
func ContextFromChan(chStop chan struct{}) (context.Context, context.CancelFunc)
ContextFromChan creates a context that finishes when the provided channel receives or is closed. Deprecated: Call services.StopChan.NewCtx directly.
func ContextFromChanWithTimeout ¶ added in v2.1.0
func ContextFromChanWithTimeout(chStop chan struct{}, timeout time.Duration) (context.Context, context.CancelFunc)
ContextFromChanWithTimeout creates a context with a timeout that finishes when the provided channel receives or is closed. Deprecated: Call services.StopChan.CtxCancel directly
func DeleteUnstable ¶
DeleteUnstable destructively removes slice element at index i It does no bounds checking and may re-order the slice
func DurationFromNow ¶
DurationFromNow returns the amount of time since the Time field was last updated.
func EnsureDirAndMaxPerms ¶
EnsureDirAndMaxPerms ensures that the given path exists, that it's a directory, and that it has permissions that are no more permissive than the given ones.
- If the path does not exist, it is created - If the path exists, but is not a directory, an error is returned - If the path exists, and is a directory, but has the wrong perms, it is chmod'ed
func EnsureFileMaxPerms ¶
EnsureFileMaxPerms ensures that the given file has permissions that are no more permissive than the given ones.
func EnsureFilepathMaxPerms ¶
EnsureFilepathMaxPerms ensures that the file at the given filepath has permissions that are no more permissive than the given ones.
func FileExists ¶
FileExists returns true if a file at the passed string exists.
func FiniteTicker ¶
FiniteTicker starts a goroutine to execute the given function periodically, until the returned function is called.
func FormatJSON ¶
FormatJSON applies indent to format a JSON response.
func GenerateEthPrefixedMsgHash ¶ added in v2.5.0
func GenerateEthSignature ¶ added in v2.5.0
func GenerateEthSignature(privateKey *ecdsa.PrivateKey, msg []byte) (signature []byte, err error)
func GetSignersEthAddress ¶ added in v2.5.0
func HashPassword ¶
HashPassword wraps around bcrypt.GenerateFromPassword for a friendlier API.
func IsFileOwnedByChainlink ¶
IsFileOwnedByChainlink attempts to read fileInfo to verify file owner
func IsZero ¶ added in v2.1.0
func IsZero[C comparable](val C) bool
func LeftPadBitString ¶
func MultiErrorList ¶
MultiErrorList returns an error which formats underlying errors as a list, or nil if err is nil.
func MustNewPeerID ¶
func MustNewPeerID() string
func MustUnmarshalToMap ¶
MustUnmarshalToMap performs UnmarshalToMap, panics upon failure
func NewBytes32ID ¶
func NewBytes32ID() string
NewBytes32ID returns a randomly generated UUID that conforms to Ethereum bytes32.
func NewRedialBackoff ¶
NewRedialBackoff is a standard backoff to use for redialling or reconnecting to unreachable network endpoints
func NewSecret ¶
NewSecret returns a new securely random sequence of n bytes of entropy. The result is a base64 encoded string.
Panics on failed attempts to read from system's PRNG.
func NewThreadControl ¶ added in v2.6.0
func NewThreadControl() *threadControl
func NormalizedJSON ¶
NormalizedJSON returns a JSON representation of an object that has been normalized to produce a consistent output for hashing.
NOTE: If this string is unmarshalled again, there is no guarantee that the final representation will be consistent with the string produced by this function due to differences in JSON implementations and information loss. e.g:
JSON does not have a requirement to respect object key ordering.
func PasswordFromFile ¶
func StringToHex ¶
StringToHex converts a standard string to a hex encoded string.
func TooPermissive ¶
TooPermissive checks if the file has more than the allowed permissions
func UnmarshalToMap ¶
UnmarshalToMap takes an input json string and returns a map[string]interface i.e. a raw object
func UnwrapError ¶
UnwrapError returns a list of underlying errors if passed error implements joinedError or return the err in a single-element list otherwise.
func ValidateCronSchedule ¶
ValidateCronSchedule returns an error if the given schedule is invalid.
func WithCloseChan ¶
func WithCloseChan(parentCtx context.Context, chStop chan struct{}) (context.Context, context.CancelFunc)
WithCloseChan wraps a context so that it is canceled if the passed in channel is closed. Deprecated: Call services.StopChan.Ctx directly
func WithJitter ¶
WithJitter adds +/- 10% to a duration
Types ¶
type BackoffTicker ¶
BackoffTicker sends ticks with periods that increase over time, over a configured range.
func NewBackoffTicker ¶
func NewBackoffTicker(min, max time.Duration) BackoffTicker
NewBackoffTicker returns a new BackoffTicker for the given range.
func (*BackoffTicker) Start ¶
func (t *BackoffTicker) Start() bool
Start - Starts the ticker Returns true if the ticker was not running yet
func (*BackoffTicker) Stop ¶
func (t *BackoffTicker) Stop() bool
Stop stops the ticker. A ticker can be restarted by calling Start on a stopped ticker. Returns true if the ticker was actually stopped at this invocation (was previously running)
func (*BackoffTicker) Ticks ¶
func (t *BackoffTicker) Ticks() <-chan time.Time
Ticks returns the underlying channel.
type BoundedPriorityQueue ¶
type BoundedPriorityQueue[T any] struct { // contains filtered or unexported fields }
BoundedPriorityQueue stores a series of BoundedQueues with associated priorities and capacities
func NewBoundedPriorityQueue ¶
func NewBoundedPriorityQueue[T any](capacities map[uint]int) *BoundedPriorityQueue[T]
NewBoundedPriorityQueue creates a new BoundedPriorityQueue
func (*BoundedPriorityQueue[T]) Add ¶
func (q *BoundedPriorityQueue[T]) Add(priority uint, x T)
Add pushes an item into a subque within a BoundedPriorityQueue
func (*BoundedPriorityQueue[T]) Empty ¶
func (q *BoundedPriorityQueue[T]) Empty() bool
Empty checks the BoundedPriorityQueue if all subqueues are empty
func (*BoundedPriorityQueue[T]) Take ¶
func (q *BoundedPriorityQueue[T]) Take() (t T)
Take takes from the BoundedPriorityQueue's subque
type BoundedQueue ¶
type BoundedQueue[T any] struct { // contains filtered or unexported fields }
BoundedQueue is a FIFO queue that discards older items when it reaches its capacity.
func NewBoundedQueue ¶
func NewBoundedQueue[T any](capacity int) *BoundedQueue[T]
NewBoundedQueue creates a new BoundedQueue instance
func (*BoundedQueue[T]) Add ¶
func (q *BoundedQueue[T]) Add(x T)
Add appends items to a BoundedQueue
func (*BoundedQueue[T]) Empty ¶
func (q *BoundedQueue[T]) Empty() bool
Empty check is a BoundedQueue is empty
func (*BoundedQueue[T]) Full ¶
func (q *BoundedQueue[T]) Full() bool
Full checks if a BoundedQueue is over capacity.
func (*BoundedQueue[T]) Take ¶
func (q *BoundedQueue[T]) Take() (t T)
Take pulls the first item from the array and removes it
type Clock ¶ added in v2.3.0
func NewFixedClock ¶ added in v2.3.0
func NewRealClock ¶ added in v2.3.0
func NewRealClock() Clock
type CronTicker ¶
type CronTicker struct { *cron.Cron // contains filtered or unexported fields }
CronTicker is like a time.Ticker but for a cron schedule.
func NewCronTicker ¶
func NewCronTicker(schedule string) (CronTicker, error)
NewCronTicker returns a new CrontTicker for the given schedule.
func (*CronTicker) Start ¶
func (t *CronTicker) Start() bool
Start - returns true if the CronTicker was actually started, false otherwise
func (*CronTicker) Stop ¶
func (t *CronTicker) Stop() bool
Stop - returns true if the CronTicker was actually stopped, false otherwise
func (*CronTicker) Ticks ¶
func (t *CronTicker) Ticks() <-chan time.Time
Ticks returns the underlying chanel.
type DeferableWriteCloser ¶
type DeferableWriteCloser struct { io.WriteCloser // contains filtered or unexported fields }
DeferableWriteCloser is to be used in leiu of defer'ing Close on an io.WriteCloser (// For more background see https://www.joeshaw.org/dont-defer-close-on-writable-files/) Callers should *both* explicitly call Close and check for errors when done with the underlying writerclose *and* defer the Close() to handle returns before the explicit close
For example rather than
import "os" f, err := os.Create("./foo") if err != nil { return err} defer f.Close() return f.Write([]bytes("hi"))
do
import "os" f, err := os.Create("./foo") if err != nil {return nil} wc := NewDeferableWriteCloser(f) defer wc.Close() err = wc.Write([]bytes("hi")) if err != nil {return err} return wc.Close()
func NewDeferableWriteCloser ¶
func NewDeferableWriteCloser(wc io.WriteCloser) *DeferableWriteCloser
NewDeferableWriteCloser creates a deferable writercloser. Callers should explicit call and defer Close. See DeferabelWriterCloser for details.
func (*DeferableWriteCloser) Close ¶
func (wc *DeferableWriteCloser) Close() error
Close closes the WriterCloser. The underlying Closer is Closed exactly once and resulting error is cached. Should be called explicitly AND defered Thread safe
type ErrorBuffer ¶
type ErrorBuffer struct {
// contains filtered or unexported fields
}
ErrorBuffer uses joinedErrors interface to join multiple errors into a single error. This is useful to track the most recent N errors in a service and flush them as a single error.
func (*ErrorBuffer) Append ¶
func (eb *ErrorBuffer) Append(incoming error)
func (*ErrorBuffer) Flush ¶
func (eb *ErrorBuffer) Flush() (err error)
func (*ErrorBuffer) SetCap ¶
func (eb *ErrorBuffer) SetCap(cap int)
type FileSize ¶
type FileSize uint64
FileSize repesents a file size in bytes.
func (FileSize) MarshalText ¶
MarshalText encodes s as a human readable string.
func (*FileSize) UnmarshalText ¶
UnmarshalText parses a file size from bs in to s.
type Hash ¶ added in v2.5.0
type Hash [32]byte
Hash is a simplified version of go-ethereum's common.Hash to avoid go-ethereum dependency It represents a 32 byte fixed size array that marshals/unmarshals assuming a 0x prefix
func BytesToHash ¶ added in v2.8.0
BytesToHash sets b to hash. If b is larger than len(h), b will be cropped from the left.
func (*Hash) SetBytes ¶ added in v2.8.0
SetBytes sets the hash to the value of b. If b is larger than len(h), b will be cropped from the left.
func (Hash) String ¶ added in v2.5.0
String implements the stringer interface and is used also by the logger when doing full logging into a file.
func (*Hash) UnmarshalText ¶ added in v2.5.0
UnmarshalText parses a hash in hex syntax.
type KeyedMutex ¶
type KeyedMutex struct {
// contains filtered or unexported fields
}
KeyedMutex allows to lock based on particular values
func (*KeyedMutex) LockInt64 ¶
func (m *KeyedMutex) LockInt64(key int64) func()
LockInt64 locks the value for read/write
type PausableTicker ¶
type PausableTicker struct {
// contains filtered or unexported fields
}
PausableTicker stores a ticker with a duration
func NewPausableTicker ¶
func NewPausableTicker(duration time.Duration) PausableTicker
NewPausableTicker creates a new PausableTicker
func (*PausableTicker) Destroy ¶
func (t *PausableTicker) Destroy()
Destroy pauses the PausibleTicker
func (*PausableTicker) Resume ¶
func (t *PausableTicker) Resume()
Resume resumes a Ticker using a PausibleTicker's duration
func (*PausableTicker) Ticks ¶
func (t *PausableTicker) Ticks() <-chan time.Time
Ticks retrieves the ticks from a PausableTicker
type PlainHexBytes ¶
type PlainHexBytes []byte
PlainHexBytes marshals/unmarshals as a JSON string without a 0x prefix. The empty slice marshals as "".
func (PlainHexBytes) MarshalText ¶
func (b PlainHexBytes) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler
func (PlainHexBytes) String ¶
func (b PlainHexBytes) String() string
func (*PlainHexBytes) UnmarshalJSON ¶
func (b *PlainHexBytes) UnmarshalJSON(input []byte) (err error)
UnmarshalJSON implements json.Unmarshaler.
func (*PlainHexBytes) UnmarshalText ¶
func (b *PlainHexBytes) UnmarshalText(input []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type ResettableTimer ¶
type ResettableTimer struct {
// contains filtered or unexported fields
}
ResettableTimer stores a timer
func NewResettableTimer ¶
func NewResettableTimer() ResettableTimer
NewResettableTimer creates a new ResettableTimer
func (*ResettableTimer) Reset ¶
func (t *ResettableTimer) Reset(duration time.Duration)
Reset stops a ResettableTimer and resets it with a new duration
func (*ResettableTimer) Ticks ¶
func (t *ResettableTimer) Ticks() <-chan time.Time
Ticks retrieves the ticks from a ResettableTimer
type ScryptConfigReader ¶
type ScryptConfigReader interface {
InsecureFastScrypt() bool
}
ScryptConfigReader can check for an insecure, fast flag
type ScryptParams ¶
type ScryptParams struct{ N, P int }
ScryptParams represents two integers, N and P.
func GetScryptParams ¶
func GetScryptParams(config ScryptConfigReader) ScryptParams
GetScryptParams fetches ScryptParams from a ScryptConfigReader
type StartStopOnce ¶
type StartStopOnce = services.StateMachine
StartStopOnce contains a StartStopOnceState integer Deprecated: use services.StateMachine
type ThreadControl ¶ added in v2.6.0
type ThreadControl interface { // Go starts a goroutine and tracks the lifetime of the goroutine. Go(fn func(context.Context)) // Close cancels the goroutines and waits for all of them to exit. Close() }
ThreadControl is a helper for managing a group of goroutines.
type TickerBase ¶
TickerBase is an interface for pausable tickers.