utils

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2020 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultBootNodeAddrStrings = []string{
	"/ip4/127.0.0.1/tcp/19876/p2p/Qmc1V6W7BwX8Ugb42Ti8RnXF1rY5PF7nnZ6bKBryCgi6cv",
}

DefaultBootNodeAddrStrings is a list of Harmony bootnodes address. Used to find other peers in the network.

View Source
var RootConnLogger = NewConnLogger(log.Root())

RootConnLogger is a LibP2P connection logger that logs to Ethereum root logger. See ConnLogger for usage.

Functions

func AddLogFile

func AddLogFile(filepath string, maxSize int)

AddLogFile creates a StreamHandler that outputs JSON logs into rotating files with specified max file size

func AddLogHandler

func AddLogHandler(handler log.Handler)

AddLogHandler add a log handler

func AllocateShard

func AllocateShard(numOfAddedNodes, numOfShards int) (int, bool)

AllocateShard uses the number of current nodes and number of shards to return the shardNum a new node belongs to, it also tells whether the node is a leader

func AskForPassphrase

func AskForPassphrase(prompt string) string

AskForPassphrase return passphrase using password input

func BToMb

func BToMb(b uint64) uint64

BToMb ...

func ConvertFixedDataIntoByteArray

func ConvertFixedDataIntoByteArray(data interface{}) []byte

ConvertFixedDataIntoByteArray converts an empty interface data to a byte array

func CopyBytes

func CopyBytes(b []byte) (copiedBytes []byte)

CopyBytes returns an exact copy of the provided bytes.

func CountOneBits

func CountOneBits(arr []byte) int64

CountOneBits counts the number of 1 bit in byte array

func EmbedFile

func EmbedFile(filePath string, constName string)

EmbedFile Text file embed script for go:generate. This script embeds a text file located at filePath into a string constant named as constName defined in a golang source file located at the current go:generate path.

func FromHex

func FromHex(s string) []byte

FromHex returns the bytes represented by the hexadecimal string s. s may be prefixed with "0x".

func GenKeyP2P

func GenKeyP2P(ip, port string) (p2p_crypto.PrivKey, p2p_crypto.PubKey, error)

GenKeyP2P generates a pair of RSA keys used in libp2p host

func GenKeyP2PRand

func GenKeyP2PRand() (p2p_crypto.PrivKey, p2p_crypto.PubKey, error)

GenKeyP2PRand generates a pair of RSA keys used in libp2p host, using random seed

func GetAddressFromBlsPubKey

func GetAddressFromBlsPubKey(pubKey *bls.PublicKey) common.Address

GetAddressFromBlsPubKey return the address object from bls pub key.

func GetLogInstance

func GetLogInstance() log.Logger

GetLogInstance returns logging singleton.

func GetLogger

func GetLogger() log.Logger

GetLogger is a shorthand for WithCaller(GetLogInstance()).

func GetPassphraseFromSource

func GetPassphraseFromSource(src string) (pass string, err error)

GetPassphraseFromSource reads a passphrase such as a key-encrypting one non-interactively from the given source.

The source can be "pass:password", "env:var", "file:pathname", "fd:number", or "stdin". See “PASS PHRASE ARGUMENTS” section of openssl(1) for details.

When "stdin" or "fd:" is used, the standard input or the given file descriptor is exhausted. Therefore, this function should be called at most once per program invocation; the second call, if any, may return an empty string if "stdin" or "fd" is used.

func GetPendingCXKey

func GetPendingCXKey(shardID uint32, blockNum uint64) string

GetPendingCXKey creates pending CXReceiptsProof key given shardID and blockNum it is to avoid adding duplicated CXReceiptsProof from the same source shard

func GetPortFromDiff

func GetPortFromDiff(port string, diff int) string

GetPortFromDiff returns the port from base and the diff.

func GetUniqueIDFromIPPort

func GetUniqueIDFromIPPort(ip, port string) uint32

GetUniqueIDFromIPPort --

func HasHexPrefix

func HasHexPrefix(str string) bool

HasHexPrefix validates str begins with '0x' or '0X'.

func Hex2Bytes

func Hex2Bytes(str string) []byte

Hex2Bytes returns the bytes represented by the hexadecimal string str.

func IsHex

func IsHex(str string) bool

IsHex validates whether each byte is valid hexadecimal string.

func IsPrivateIP

func IsPrivateIP(ip net.IP) bool

IsPrivateIP checks if an IP address is private or not

func LeftPadBytes

func LeftPadBytes(slice []byte, l int) []byte

LeftPadBytes zero-pads slice to the left up to length l.

func Load

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

Load loads the file at path into v.

func LoadKeyFromFile

func LoadKeyFromFile(keyfile string) (key p2p_crypto.PrivKey, pk p2p_crypto.PubKey, err error)

LoadKeyFromFile load private key from keyfile If the private key is not loadable or no file, it will generate a new random private key

func LoadPrivateKey

func LoadPrivateKey(key string) (p2p_crypto.PrivKey, p2p_crypto.PubKey, error)

LoadPrivateKey parses the key string in base64 format and return PrivKey

func Logger

func Logger() *zerolog.Logger

Logger returns a zerolog.Logger singleton

func Marshal

func Marshal(v interface{}) (io.Reader, error)

Marshal is a function that marshals the object into an io.Reader.

func RightPadBytes

func RightPadBytes(slice []byte, l int) []byte

RightPadBytes zero-pads slice to the right up to length l.

func Save

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

Save saves a representation of v to the file at path.

func SaveKeyToFile

func SaveKeyToFile(keyfile string, key p2p_crypto.PrivKey) (err error)

SaveKeyToFile save private key to keyfile

func SavePrivateKey

func SavePrivateKey(key p2p_crypto.PrivKey) (string, error)

SavePrivateKey convert the PrivKey to base64 format and return string

func SetLogContext

func SetLogContext(_port, _ip string)

SetLogContext used to print out loggings of node with port and ip. Every instance (node, etc..) needs to set this for logging.

func SetLogVerbosity

func SetLogVerbosity(verbosity log.Lvl)

SetLogVerbosity specifies the verbosity of global logger

func StringsToAddrs

func StringsToAddrs(addrStrings []string) (maddrs []ma.Multiaddr, err error)

StringsToAddrs convert a list of strings to a list of multiaddresses

func StringsToPeers

func StringsToPeers(input string) []p2p.Peer

StringsToPeers converts a string to a list of Peers addr is a string of format "ip:port,ip:port"

func Unmarshal

func Unmarshal(r io.Reader, v interface{}) error

Unmarshal is a function that unmarshals the data from the reader into the specified value.

func WithCaller

func WithCaller(logger log.Logger) log.Logger

WithCaller logs the caller info in three context items "funcFile", "funcLine", and "funcName".

func WithCallerSkip

func WithCallerSkip(logger log.Logger, skip int) log.Logger

WithCallerSkip logs the caller info in three context items "funcFile", "funcLine", and "funcName". skip is the number of frames to skip. 0 adds the info of the caller of this WithCallerSkip.

Types

type AddrList

type AddrList []ma.Multiaddr

AddrList is a list of multiaddress

var BootNodes AddrList

BootNodes is a list of boot nodes. It is populated either from default or from user CLI input.

func (*AddrList) Set

func (al *AddrList) Set(value string) error

Set is a function to set the value of AddrList based on a string

func (*AddrList) String

func (al *AddrList) String() string

String is a function to print a string representation of the AddrList

type ConnLogger

type ConnLogger struct {
	// contains filtered or unexported fields
}

ConnLogger is a LibP2P connection logger that logs to an Ethereum logger. It logs all listener/connection/stream open/close activities at debug level. To use one, add it on a LibP2P host swarm as a notifier, ex:

connLogger := utils.NewConnLogger(
host.Network().Notify(connLogger)

func NewConnLogger

func NewConnLogger(l log.Logger) *ConnLogger

NewConnLogger returns a new connection logger that uses the given Ethereum logger. See ConnLogger for usage.

func (ConnLogger) ClosedStream

func (cl ConnLogger) ClosedStream(n net.Network, s net.Stream)

ClosedStream logs a stream getting closed.

func (ConnLogger) Connected

func (cl ConnLogger) Connected(n net.Network, c net.Conn)

Connected logs a connection getting opened.

func (ConnLogger) Disconnected

func (cl ConnLogger) Disconnected(n net.Network, c net.Conn)

Disconnected logs a connection getting closed.

func (ConnLogger) Listen

func (cl ConnLogger) Listen(n net.Network, ma ma.Multiaddr)

Listen logs a listener starting listening on an address.

func (ConnLogger) ListenClose

func (cl ConnLogger) ListenClose(n net.Network, ma ma.Multiaddr)

ListenClose logs a listener stopping listening on an address.

func (ConnLogger) OpenedStream

func (cl ConnLogger) OpenedStream(n net.Network, s net.Stream)

OpenedStream logs a new stream getting opened.

type PrivKeyStore

type PrivKeyStore struct {
	Key string `json:"key"`
}

PrivKeyStore is used to persist private key to/from file

type TestLogRedirector

type TestLogRedirector struct {
	// contains filtered or unexported fields
}

TestLogRedirector is a log15-compatible log handler that logs to the testing object. It is useful when debugging, because it surfaces application log messages – such as ones emitted by the SUT – which are otherwise discarded and not displayed during testing.

Typical usage:

func TestMyFunc(t *testing.T) {
	l := utils.GetLogInstance()
	lrd := NewTestLogRedirector(l, t)
	defer lrd.Close()

	// Everything sent to the logger l will be printed onto the test log,
	// until lrd.Close() is called at the end of the function.
	// Contexts are formatted using the "%#v" format specifier.
	l.Debug("hello", "audience", "world")
	// The above prints: hello, audience="world"
}

func NewTestLogRedirector

func NewTestLogRedirector(l log.Logger, t TestLogger) *TestLogRedirector

NewTestLogRedirector returns a new testing log redirector. The given logger's handler is saved and replaced by the receiver. Caller shall ensure Close() is called when the redirector is no longer needed.

func (*TestLogRedirector) Close

func (redirector *TestLogRedirector) Close() error

Close restores the log handler back to the original one.

func (*TestLogRedirector) Log

func (redirector *TestLogRedirector) Log(r *log.Record) error

Log logs the given log15 record into the testing object.

type TestLogger

type TestLogger interface {
	Log(args ...interface{})
}

TestLogger is the logging interface implemented by testing.T.

type Timeout

type Timeout struct {
	// contains filtered or unexported fields
}

Timeout is the implementation of timeout

func NewTimeout

func NewTimeout(d time.Duration) *Timeout

NewTimeout creates a new timeout class

func (*Timeout) CheckExpire

func (timeout *Timeout) CheckExpire() bool

CheckExpire checks whether the timeout is reached/expired

func (*Timeout) Duration

func (timeout *Timeout) Duration() time.Duration

Duration returns the duration period of timeout

func (*Timeout) IsActive

func (timeout *Timeout) IsActive() bool

IsActive checks whether timeout clock is active; A timeout is active means it's not stopped caused by stop and also not expired with time elapses longer than duration from start

func (*Timeout) SetDuration

func (timeout *Timeout) SetDuration(nd time.Duration)

SetDuration set new duration for the timer

func (*Timeout) Start

func (timeout *Timeout) Start()

Start starts the timeout clock

func (*Timeout) Stop

func (timeout *Timeout) Stop()

Stop stops the timeout clock

type TimeoutState

type TimeoutState int

TimeoutState indicates the state of Timeout class

const (
	Active TimeoutState = iota
	Inactive
	Expired
)

Enum for different TimeoutState

type UniqueValidatorID

type UniqueValidatorID struct {
	// contains filtered or unexported fields
}

UniqueValidatorID defines the structure of unique validator ID

func GetUniqueValidatorIDInstance

func GetUniqueValidatorIDInstance() *UniqueValidatorID

GetUniqueValidatorIDInstance returns a singleton instance

func (*UniqueValidatorID) GetUniqueID

func (s *UniqueValidatorID) GetUniqueID() uint32

GetUniqueID returns a unique ID and increment the internal variable

type WalletProfile

type WalletProfile struct {
	Profile   string
	ChainID   string
	Bootnodes []string
	Shards    int
	RPCServer [][]p2p.Peer
	Network   string
}

WalletProfile contains a section and key value pair map

func ReadWalletProfile

func ReadWalletProfile(iniBytes []byte, profile string) (*WalletProfile, error)

ReadWalletProfile reads an ini file and return WalletProfile

Directories

Path Synopsis
Package mock_utils is a generated GoMock package.
Package mock_utils is a generated GoMock package.
Package mock_log is a generated GoMock package.
Package mock_log is a generated GoMock package.

Jump to

Keyboard shortcuts

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