utils

package
v2.8.0-beta0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: MIT Imports: 49 Imported by: 10

README

package utils

StartStopOnce

stateDiagram-v2
    [*] --> Unstarted
    Unstarted --> Starting : StartOnce()
    Starting --> StartFailed
    Starting --> Started
    Started --> Stopping : StopOnce()
    Stopping --> Stopped
    Stopping --> StopFailed
    StartFailed --> [*]
    Stopped --> [*]
    StopFailed --> [*]

Documentation

Overview

Package utils is used for common functions and tools used across the codebase.

Index

Constants

View Source
const (
	// FormatBytes encodes the output as bytes
	FormatBytes = "bytes"
	// FormatPreformatted encodes the output, assumed to be hex, as bytes.
	FormatPreformatted = "preformatted"
	// FormatUint256 encodes the output as bytes containing a uint256
	FormatUint256 = "uint256"
	// FormatInt256 encodes the output as bytes containing an int256
	FormatInt256 = "int256"
	// FormatBool encodes the output as bytes containing a bool
	FormatBool = "bool"
)
View Source
const (
	KB = 1000
	MB = 1000 * KB
	GB = 1000 * MB
	TB = 1000 * GB
)

nolint

View Source
const (
	// FastN is a shorter N parameter for testing
	FastN = 2
	// FastP is a shorter P parameter for testing
	FastP = 1
)
View Source
const (
	// DefaultSecretSize is the entropy in bytes to generate a base64 string of 64 characters.
	DefaultSecretSize = 48
	// EVMWordByteLen the length of an EVM Word Byte
	EVMWordByteLen = 32
)
View Source
const EthSignedMessagePrefix = "\x19Ethereum Signed Message:\n"
View Source
const HashLength = 32
View Source
const MinRequiredLen = 16
View Source
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

View Source
var (

	// MaxUint256 represents the largest number represented by an EVM word
	MaxUint256 = &big.Int{}
	// MaxInt256 represents the largest number represented by an EVM word using
	// signed encoding.
	MaxInt256 = &big.Int{}
	// MinInt256 represents the smallest number represented by an EVM word using
	// signed encoding.
	MinInt256 = &big.Int{}
)

"Constants" used by EVM words

View Source
var (
	ErrPasswordWhitespace  = errors.New("leading/trailing whitespace detected in password")
	ErrEmptyPasswordInFile = errors.New("detected empty password in password file")
)
View Source
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")
)
View Source
var (
	ErrAlreadyStopped      = errors.New("already stopped")
	ErrCannotStopUnstarted = errors.New("cannot stop unstarted service")
)

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.

View Source
var EmptyHash = common.Hash{}

EmptyHash is a hash of all zeroes, otherwise in Ethereum as 0x0000000000000000000000000000000000000000000000000000000000000000

View Source
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!

View Source
var LeadingWhitespace = regexp.MustCompile(`^\s+`)
View Source
var TrailingWhitespace = regexp.MustCompile(`\s+$`)
View Source
var ZeroAddress = common.Address{}

ZeroAddress is an address of all zeroes, otherwise in Ethereum as 0x0000000000000000000000000000000000000000

Functions

func ABIDecode

func ABIDecode(abiStr string, data []byte) ([]interface{}, error)

ABIEncode is the equivalent of abi.decode. See a full set of examples https://github.com/ethereum/go-ethereum/blob/420b78659bef661a83c5c442121b13f13288c09f/accounts/abi/packing_test.go#L31

func ABIEncode

func ABIEncode(abiStr string, values ...interface{}) ([]byte, error)

ABIEncode is the equivalent of abi.encode. See a full set of examples https://github.com/ethereum/go-ethereum/blob/420b78659bef661a83c5c442121b13f13288c09f/accounts/abi/packing_test.go#L31

func AddHexPrefix

func AddHexPrefix(str string) string

AddHexPrefix adds the prefix (0x) to a given hex string.

func AllEqual

func AllEqual[T comparable](elems ...T) bool

AllEqual returns true iff all the provided elements are equal to each other.

func BatchSplit

func BatchSplit[T any](list []T, max int) (out [][]T, err error)

BatchSplit splits an slices into an slices of slicess with a maximum length

func BoxOutput

func BoxOutput(errorMsgTemplate string, errorMsgValues ...interface{}) string

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 Bytes32FromString

func Bytes32FromString(s string) [32]byte

Bytes32FromString returns a 32 byte array filled from the given string, which may be of any length.

func Bytes32ToSlice

func Bytes32ToSlice(a [32]byte) (r []byte)

func Bytes4FromString

func Bytes4FromString(s string) [4]byte

Bytes4FromString returns a 4 byte array filled from the given string, which may be of any length.

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash wraps around bcrypt.CompareHashAndPassword for a friendlier API.

func CheckUint256

func CheckUint256(n *big.Int) error

CheckUint256 returns an error if n is out of bounds for a uint256

func ConcatBytes

func ConcatBytes(bufs ...[]byte) []byte

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

func DeleteUnstable[T any](s []T, i int) []T

DeleteUnstable destructively removes slice element at index i It does no bounds checking and may re-order the slice

func DurationFromNow

func DurationFromNow(t time.Time) time.Duration

DurationFromNow returns the amount of time since the Time field was last updated.

func EIP55CapitalizedAddress

func EIP55CapitalizedAddress(possibleAddressString string) bool

EIP55CapitalizedAddress returns true iff possibleAddressString has the correct capitalization for an Ethereum address, per EIP 55

func EVMBytesToUint64

func EVMBytesToUint64(buf []byte) uint64

EVMBytesToUint64 converts a bytebuffer to uint64

func EVMEncodeBytes

func EVMEncodeBytes(input []byte) []byte

EVMEncodeBytes encodes arbitrary bytes as bytes expected by the EVM

func EVMTranscodeBool

func EVMTranscodeBool(value gjson.Result) ([]byte, error)

EVMTranscodeBool converts a json input to an EVM bool

func EVMTranscodeInt256

func EVMTranscodeInt256(value gjson.Result) ([]byte, error)

EVMTranscodeInt256 converts a json input to an EVM int256

func EVMTranscodeUint256

func EVMTranscodeUint256(value gjson.Result) ([]byte, error)

EVMTranscodeUint256 converts a json input to an EVM uint256

func EVMWordBigInt

func EVMWordBigInt(val *big.Int) ([]byte, error)

EVMWordBigInt returns a big.Int as an EVM word byte array, with support for a signed representation. Returns error on overflow.

func EVMWordSignedBigInt

func EVMWordSignedBigInt(val *big.Int) ([]byte, error)

EVMWordSignedBigInt returns a big.Int as an EVM word byte array, with support for a signed representation. Returns error on overflow.

func EVMWordUint128

func EVMWordUint128(val *big.Int) ([]byte, error)

EVMWordUint128 returns a uint128 as an EVM word byte array.

func EVMWordUint32

func EVMWordUint32(val uint32) []byte

EVMWordUint32 returns a uint32 as an EVM word byte array.

func EVMWordUint64

func EVMWordUint64(val uint64) []byte

EVMWordUint64 returns a uint64 as an EVM word byte array.

func EnsureDirAndMaxPerms

func EnsureDirAndMaxPerms(path string, perms os.FileMode) error

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

func EnsureFileMaxPerms(file *os.File, perms os.FileMode) error

EnsureFileMaxPerms ensures that the given file has permissions that are no more permissive than the given ones.

func EnsureFilepathMaxPerms

func EnsureFilepathMaxPerms(filepath string, perms os.FileMode) (err error)

EnsureFilepathMaxPerms ensures that the file at the given filepath has permissions that are no more permissive than the given ones.

func FileExists

func FileExists(name string) (bool, error)

FileExists returns true if a file at the passed string exists.

func FiniteTicker

func FiniteTicker(period time.Duration, onTick func()) func()

FiniteTicker starts a goroutine to execute the given function periodically, until the returned function is called.

func FormatJSON

func FormatJSON(v interface{}) ([]byte, error)

FormatJSON applies indent to format a JSON response.

func GenerateEthPrefixedMsgHash added in v2.5.0

func GenerateEthPrefixedMsgHash(msg []byte) (hash common.Hash)

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 GetSignersEthAddress(msg []byte, sig []byte) (recoveredAddr common.Address, err error)

func HasHexPrefix

func HasHexPrefix(str string) bool

HasHexPrefix returns true if the string starts with 0x.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword wraps around bcrypt.GenerateFromPassword for a friendlier API.

func HexToBig

func HexToBig(s string) *big.Int

HexToBig parses the given hex string or panics if it is invalid.

func HexToUint256

func HexToUint256(s string) (*big.Int, error)

HexToUint256 returns the uint256 represented by s, or an error if it doesn't represent one.

func ISO8601UTC

func ISO8601UTC(t time.Time) string

ISO8601UTC formats given time to ISO8601.

func IsEmpty

func IsEmpty(bytes []byte) bool

IsEmpty returns true if bytes contains only zero values, or has len 0.

func IsEmptyAddress

func IsEmptyAddress(addr common.Address) bool

IsEmptyAddress checks that the address is empty, synonymous with the zero account/address. No logs can come from this address, as there is no contract present there.

See https://stackoverflow.com/questions/48219716/what-is-address0-in-solidity for the more info on the zero address.

func IsFileOwnedByChainlink(fileInfo os.FileInfo) (bool, error)

IsFileOwnedByChainlink attempts to read fileInfo to verify file owner

func IsZero added in v2.1.0

func IsZero[C comparable](val C) bool

func JustError

func JustError(_ interface{}, err error) error

JustError takes a tuple and returns the last entry, the error.

func Keccak256

func Keccak256(in []byte) ([]byte, error)

Keccak256 is a simplified interface for the legacy SHA3 implementation that Ethereum uses.

func Keccak256Fixed

func Keccak256Fixed(in []byte) [32]byte

func LeftPadBitString

func LeftPadBitString(input string, length int) string

func MinKey

func MinKey[U any, T constraints.Ordered](elems []U, key func(U) T) T

MinKey returns the minimum value of the given element array with respect to the given key function. In the event U is not a compound type (e.g a struct) an identity function can be provided.

func MultiErrorList

func MultiErrorList(err error) (int, error)

MultiErrorList returns an error which formats underlying errors as a list, or nil if err is nil.

func MustAbiType

func MustAbiType(ts string, components []abi.ArgumentMarshaling) abi.Type

func MustHash

func MustHash(in string) common.Hash

MustHash returns the keccak256 hash, or panics on failure.

func MustNewPeerID

func MustNewPeerID() string

func MustUnmarshalToMap

func MustUnmarshalToMap(input string) map[string]interface{}

MustUnmarshalToMap performs UnmarshalToMap, panics upon failure

func NewBytes32ID

func NewBytes32ID() string

NewBytes32ID returns a randomly generated UUID that conforms to Ethereum bytes32.

func NewHash

func NewHash() common.Hash

NewHash return random Keccak256

func NewRedialBackoff

func NewRedialBackoff() backoff.Backoff

NewRedialBackoff is a standard backoff to use for redialling or reconnecting to unreachable network endpoints

func NewSecret

func NewSecret(n int) string

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

func NormalizedJSON(val []byte) (string, error)

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 PadByteToHash

func PadByteToHash(b byte) common.Hash

PadByteToHash returns a hash with zeros padded on the left of the given byte.

func ParseEthereumAddress

func ParseEthereumAddress(addressString string) (common.Address, error)

ParseEthereumAddress returns addressString as a go-ethereum Address, or an error if it's invalid, e.g. if EIP 55 capitalization check fails

func PasswordFromFile

func PasswordFromFile(pwdFile string) (string, error)

func RandUint256

func RandUint256() *big.Int

RandUint256 generates a random bigNum up to 2 ** 256 - 1

func RandomAddress

func RandomAddress() common.Address

func RandomBytes32

func RandomBytes32() (r [32]byte)

func RemoveHexPrefix

func RemoveHexPrefix(str string) string

RemoveHexPrefix removes the prefix (0x) of a given hex string.

func RetryWithBackoff

func RetryWithBackoff(ctx context.Context, fn func() (retry bool))

RetryWithBackoff retries the sleeper and backs off if not Done

func Sha256

func Sha256(in string) (string, error)

Sha256 returns a hexadecimal encoded string of a hashed input

func StringToHex

func StringToHex(in string) string

StringToHex converts a standard string to a hex encoded string.

func ToDecimal

func ToDecimal(input interface{}) (decimal.Decimal, error)

ToDecimal converts an input to a decimal

func TooPermissive

func TooPermissive(fileMode, maxAllowedPerms os.FileMode) bool

TooPermissive checks if the file has more than the allowed permissions

func TryParseHex

func TryParseHex(s string) (b []byte, err error)

TryParseHex parses the given hex string to bytes, it can return error if the hex string is invalid. Follows the semantic of ethereum's FromHex.

func Uint256ToBytes

func Uint256ToBytes(x *big.Int) (uint256 []byte, err error)

Uint256ToBytes is x represented as the bytes of a uint256

func Uint256ToBytes32

func Uint256ToBytes32(n *big.Int) []byte

Uint256ToBytes32 returns the bytes32 encoding of the big int provided

func UnmarshalToMap

func UnmarshalToMap(input string) (map[string]interface{}, error)

UnmarshalToMap takes an input json string and returns a map[string]interface i.e. a raw object

func UnwrapError

func UnwrapError(err error) []error

UnwrapError returns a list of underlying errors if passed error implements joinedError or return the err in a single-element list otherwise.

func ValidateCronSchedule

func ValidateCronSchedule(schedule string) error

ValidateCronSchedule returns an error if the given schedule is invalid.

func VerifyPasswordComplexity

func VerifyPasswordComplexity(password string, disallowedStrings ...string) (merr error)

func WaitGroupChan

func WaitGroupChan(wg *sync.WaitGroup) <-chan struct{}

WaitGroupChan creates a channel that closes when the provided sync.WaitGroup is done.

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

func WithJitter(d time.Duration) time.Duration

WithJitter adds +/- 10% to a duration

func WrapIfError

func WrapIfError(err *error, msg string)

WrapIfError decorates an error with the given message. It is intended to be used with `defer` statements, like so:

func SomeFunction() (err error) {
    defer WrapIfError(&err, "error in SomeFunction:")

    ...
}

func WriteFileWithMaxPerms

func WriteFileWithMaxPerms(path string, data []byte, perms os.FileMode) (err error)

WriteFileWithMaxPerms writes `data` to `path` and ensures that the file has permissions that are no more permissive than the given ones.

Types

type BackoffSleeper

type BackoffSleeper struct {
	backoff.Backoff
	// contains filtered or unexported fields
}

BackoffSleeper is a sleeper that backs off on subsequent attempts.

func NewBackoffSleeper

func NewBackoffSleeper() *BackoffSleeper

NewBackoffSleeper returns a BackoffSleeper that is configured to sleep for 0 seconds initially, then backs off from 1 second minimum to 10 seconds maximum.

func (*BackoffSleeper) After

func (bs *BackoffSleeper) After() time.Duration

After returns the duration for the next stop, and increments the backoff.

func (*BackoffSleeper) Duration

func (bs *BackoffSleeper) Duration() time.Duration

Duration returns the current duration value.

func (*BackoffSleeper) Reset

func (bs *BackoffSleeper) Reset()

Reset resets the backoff intervals.

func (*BackoffSleeper) Sleep

func (bs *BackoffSleeper) Sleep()

Sleep waits for the given duration, incrementing the back off.

type BackoffTicker

type BackoffTicker struct {
	C chan time.Time

	sync.Mutex
	// contains filtered or unexported fields
}

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) Bounds

func (t *BackoffTicker) Bounds() (time.Duration, time.Duration)

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 Big

type Big big.Int

Big stores large integers and can deserialize a variety of inputs.

func NewBig

func NewBig(i *big.Int) *Big

NewBig constructs a Big from *big.Int.

func NewBigI

func NewBigI(i int64) *Big

NewBigI constructs a Big from int64.

func (*Big) Add

func (b *Big) Add(c *Big) *Big

Add returns the sum of b and c

func (*Big) Bytes

func (b *Big) Bytes() []byte

Bytes returns the

func (*Big) Cmp

func (b *Big) Cmp(c *Big) int

Cmp compares b and c as big.Ints.

func (*Big) Equal

func (b *Big) Equal(c *Big) bool

Equal returns true if c is equal according to Cmp.

func (*Big) Hex

func (b *Big) Hex() string

Bytes returns the absolute value of b as a big-endian byte slice.

func (*Big) Int64

func (b *Big) Int64() int64

Int64 casts b as an int64 type

func (Big) MarshalJSON

func (b Big) MarshalJSON() ([]byte, error)

MarshalJSON marshals this instance to base 10 number as string.

func (Big) MarshalText

func (b Big) MarshalText() ([]byte, error)

MarshalText marshals this instance to base 10 number as string.

func (*Big) Mod

func (b *Big) Mod(c *Big) *Big

Sub returns b % c

func (*Big) Scan

func (b *Big) Scan(value interface{}) error

Scan reads the database value and returns an instance.

func (*Big) String

func (b *Big) String() string

String returns the base 10 encoding of b.

func (*Big) Sub

func (b *Big) Sub(c *Big) *Big

Sub returns the differencs between b and c

func (*Big) ToInt

func (b *Big) ToInt() *big.Int

ToInt converts b to a big.Int.

func (*Big) UnmarshalJSON

func (b *Big) UnmarshalJSON(input []byte) error

UnmarshalJSON implements encoding.JSONUnmarshaler.

func (*Big) UnmarshalText

func (b *Big) UnmarshalText(input []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (Big) Value

func (b Big) Value() (driver.Value, error)

Value returns this instance serialized for database storage.

type BigFloat

type BigFloat big.Float

BigFloat accepts both string and float JSON values.

func (BigFloat) MarshalJSON

func (b BigFloat) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*BigFloat) UnmarshalJSON

func (b *BigFloat) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements the json.Unmarshal interface.

func (*BigFloat) Value

func (b *BigFloat) Value() *big.Float

Value returns the big.Float value.

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

type Clock interface {
	Now() time.Time
}

func NewFixedClock added in v2.3.0

func NewFixedClock(now time.Time) Clock

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 DependentAwaiter

type DependentAwaiter interface {
	AwaitDependents() <-chan struct{}
	AddDependents(n int)
	DependentReady()
}

DependentAwaiter contains Dependent funcs

func NewDependentAwaiter

func NewDependentAwaiter() DependentAwaiter

NewDependentAwaiter creates a new DependentAwaiter

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

func (s FileSize) MarshalText() ([]byte, error)

MarshalText encodes s as a human readable string.

func (FileSize) String

func (s FileSize) String() string

func (*FileSize) UnmarshalText

func (s *FileSize) UnmarshalText(bs []byte) error

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

func BytesToHash(b []byte) Hash

BytesToHash sets b to hash. If b is larger than len(h), b will be cropped from the left.

func (Hash) Hex added in v2.5.0

func (h Hash) Hex() string

Hex converts a hash to a hex string.

func (*Hash) SetBytes added in v2.8.0

func (h *Hash) SetBytes(b []byte)

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

func (h Hash) String() string

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

func (h *Hash) UnmarshalText(input []byte) error

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 Mailbox

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

Mailbox contains a notify channel, a mutual exclusive lock, a queue of interfaces, and a queue capacity.

func NewHighCapacityMailbox

func NewHighCapacityMailbox[T any]() *Mailbox[T]

NewHighCapacityMailbox create a new mailbox with a capacity that is better able to handle e.g. large log replays.

func NewMailbox

func NewMailbox[T any](capacity uint64) *Mailbox[T]

NewMailbox creates a new mailbox instance. If name is non-empty, it must be unique and calling Start will launch prometheus metric monitor that periodically reports mailbox load until Close() is called.

func NewSingleMailbox

func NewSingleMailbox[T any]() *Mailbox[T]

NewSingleMailbox returns a new Mailbox with capacity one.

func (*Mailbox[T]) Close

func (m *Mailbox[T]) Close() error

func (*Mailbox[T]) Deliver

func (m *Mailbox[T]) Deliver(x T) (wasOverCapacity bool)

Deliver appends to the queue and returns true if the queue was full, causing a message to be dropped.

func (*Mailbox[T]) Notify

func (m *Mailbox[T]) Notify() <-chan struct{}

Notify returns the contents of the notify channel

func (*Mailbox[T]) Retrieve

func (m *Mailbox[T]) Retrieve() (t T, ok bool)

Retrieve fetches one element from the queue.

func (*Mailbox[T]) RetrieveAll

func (m *Mailbox[T]) RetrieveAll() []T

RetrieveAll fetches all elements from the queue.

func (*Mailbox[T]) RetrieveLatestAndClear

func (m *Mailbox[T]) RetrieveLatestAndClear() (t T)

RetrieveLatestAndClear fetch the latest value (or nil), and clears the rest of the queue (if any).

type MailboxMonitor

type MailboxMonitor struct {
	services.StateMachine
	// contains filtered or unexported fields
}

func NewMailboxMonitor

func NewMailboxMonitor(appID string) *MailboxMonitor

func (*MailboxMonitor) Close

func (m *MailboxMonitor) Close() error

func (*MailboxMonitor) HealthReport

func (m *MailboxMonitor) HealthReport() map[string]error

func (*MailboxMonitor) Monitor

func (m *MailboxMonitor) Monitor(mb mailbox, name ...string)

func (*MailboxMonitor) Name

func (m *MailboxMonitor) Name() string

func (*MailboxMonitor) Start

func (m *MailboxMonitor) Start(context.Context) error

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) Pause

func (t *PausableTicker) Pause()

Pause pauses a PausableTicker

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) Stop

func (t *ResettableTimer) Stop()

Stop stops a ResettableTimer

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 Sleeper

type Sleeper interface {
	Reset()
	Sleep()
	After() time.Duration
	Duration() time.Duration
}

Sleeper interface is used for tasks that need to be done on some interval, excluding Cron, like reconnecting.

type SleeperTask

type SleeperTask interface {
	Stop() error
	WakeUp()
	WakeUpIfStarted()
}

SleeperTask represents a task that waits in the background to process some work.

func NewSleeperTask

func NewSleeperTask(worker Worker) SleeperTask

NewSleeperTask takes a worker and returns a SleeperTask.

SleeperTask is guaranteed to call Work on the worker at least once for every WakeUp call. If the Worker is busy when WakeUp is called, the Worker will be called again immediately after it is finished. For this reason you should take care to make sure that Worker is idempotent. WakeUp does not block.

type StartStopOnce

type StartStopOnce = services.StateMachine

StartStopOnce contains a StartStopOnceState integer Deprecated: use services.StateMachine

type StopChan deprecated added in v2.1.0

type StopChan = services.StopChan

Deprecated: use services.StopChan

type StopRChan deprecated added in v2.2.0

type StopRChan = services.StopRChan

Deprecated: use services.StopRChan

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

type TickerBase interface {
	Resume()
	Pause()
	Destroy()
	Ticks() <-chan time.Time
}

TickerBase is an interface for pausable tickers.

type Worker

type Worker interface {
	Work()
	Name() string
}

Worker is a simple interface that represents some work to do repeatedly

func SleeperFuncTask

func SleeperFuncTask(work func(), name string) Worker

SleeperFuncTask returns a Worker to execute the given work function.

Directories

Path Synopsis
Package bigmath compensates for awkward big.Int API.
Package bigmath compensates for awkward big.Int API.

Jump to

Keyboard shortcuts

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