common

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2019 License: Apache-2.0 Imports: 27 Imported by: 8

Documentation

Overview

Package hex utils functions.

Index

Constants

View Source
const (
	HashLength = 32
)

------------------------- package Consts, Vars Lengths of hashes and addresses in bytes.

View Source
const (
	PREFIX = "0x"
)

------------------------ package Const, Vars

Variables

View Source
var (

	// errors
	ErrBig256Range = NewError("hex number > 256 bits")
	ErrUint64Range = NewError("hex number > 64 bits")
	ErrUintRange   = NewError(fmt.Sprintf("hex number > %d bits", uintBits))
	ErrSyntax      = NewError("invalid hex string")
	ErrLeadingZero = NewError("hex number with leading zero digits")
	ErrEmptyNumber = NewError("hex string \"0x\"")
)
View Source
var (
	// E: Empty Data
	ErrEmptyData = errors.New("empty hex data")
	// E: without prefix
	ErrMissingPrefix = errors.Errorf("hex string without %s prefix", PREFIX)
	// E: odd length hex string
	ErrOddLength = errors.New("hex string of odd length")
)

errors

View Source
var (
	ErrAlreadyStarted = errors.New("already started")
	ErrAlreadyStopped = errors.New("already stopped")
)
View Source
var Fmt = func(format string, a ...interface{}) string {
	if len(a) == 0 {
		return format
	}
	return fmt.Sprintf(format, a...)
}

Like fmt.Sprintf, but skips formatting if args are empty.

View Source
var Ghex = New(PREFIX)

Functions

func ASCIITrim

func ASCIITrim(s string) string

NOTE: Assumes that s is ASCII as per IsASCIIText(), otherwise panics.

func DecodeUint64

func DecodeUint64(input string) (uint64, error)

func EnsureDir

func EnsureDir(dir string, mode os.FileMode) error

func Exit

func Exit(s string)

func FileExists

func FileExists(filePath string) bool

func GoPath

func GoPath() string

GoPath returns GOPATH env variable value. If it is not set, this function will try to call `go env GOPATH` subcommand.

func IsASCIIText

func IsASCIIText(s string) bool

Returns true if s is a non-empty printable non-tab ascii character.

func IsDirEmpty

func IsDirEmpty(name string) (bool, error)

func IsHex

func IsHex(s string) bool

IsHex returns true for non-empty hex-string prefixed with "0x"

func Kill

func Kill() error

Kill the running process by sending itself SIGTERM.

func MustReadFile

func MustReadFile(filePath string) []byte

func MustWriteFile

func MustWriteFile(filePath string, contents []byte, mode os.FileMode)

func NewID added in v1.0.0

func NewID() string

NewID generates a identifier that can be used as an identifier in the RPC interface. e.g. filter and subscription identifier.

func PanicConsensus

func PanicConsensus(v interface{})

Indicates a failure of consensus. Someone was malicious or something has gone horribly wrong. These should really boot us into an "emergency-recover" mode XXX DEPRECATED

func PanicCrisis

func PanicCrisis(v interface{})

A panic here means something has gone horribly wrong, in the form of data corruption or failure of the operating system. In a correct/healthy system, these should never fire. If they do, it's indicative of a much more serious problem. XXX DEPRECATED

func PanicQ

func PanicQ(v interface{})

For those times when we're not sure if we should panic XXX DEPRECATED

func PanicSanity

func PanicSanity(v interface{})

A panic resulting from a sanity check means there is a programmer error and some guarantee is not satisfied. XXX DEPRECATED

func Prompt

func Prompt(prompt string, defaultValue string) (string, error)

func RandBool

func RandBool() bool

func RandBytes

func RandBytes(n int) []byte

func RandFloat32

func RandFloat32() float32

func RandFloat64

func RandFloat64() float64

func RandInt

func RandInt() int

func RandInt16

func RandInt16() int16

func RandInt31

func RandInt31() int32

func RandInt31n

func RandInt31n(n int32) int32

func RandInt32

func RandInt32() int32

func RandInt63

func RandInt63() int64

func RandInt63n

func RandInt63n(n int64) int64

func RandInt64

func RandInt64() int64

func RandIntn

func RandIntn(n int) int

func RandPerm

func RandPerm(n int) []int

func RandStr

func RandStr(length int) string

func RandTime

func RandTime() time.Time

func RandUint

func RandUint() uint

func RandUint16

func RandUint16() uint16

func RandUint32

func RandUint32() uint32

func RandUint64

func RandUint64() uint64

func ReadFile

func ReadFile(filePath string) ([]byte, error)

func Seed

func Seed(seed int64)

func SplitAndTrim

func SplitAndTrim(s, sep, cutset string) []string

SplitAndTrim slices s into all subslices separated by sep and returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed. If sep is empty, SplitAndTrim splits after each UTF-8 sequence. First part is equivalent to strings.SplitN with a count of -1.

func StringInSlice

func StringInSlice(a string, list []string) bool

StringInSlice returns true if a is found the list.

func StripHex

func StripHex(s string) string

StripHex returns hex string without leading "0x"

func TrapSignal

func TrapSignal(cb func())

TrapSignal catches the SIGTERM and executes cb function. After that it exits with code 1.

func WriteFile

func WriteFile(filePath string, contents []byte, mode os.FileMode) error

Types

type BaseService

type BaseService struct {
	Logger log.Logger
	// contains filtered or unexported fields
}

Classical-inheritance-style service declarations. Services can be started, then stopped, then optionally restarted.

Users can override the OnStart/OnStop methods. In the absence of errors, these methods are guaranteed to be called at most once. If OnStart returns an error, service won't be marked as started, so the user can call Start again.

A call to Reset will panic, unless OnReset is overwritten, allowing OnStart/OnStop to be called again.

The caller must ensure that Start and Stop are not called concurrently.

It is ok to call Stop without calling Start first.

Typical usage:

type FooService struct {
	BaseService
	// private fields
}

func NewFooService() *FooService {
	fs := &FooService{
		// init
	}
	fs.BaseService = *NewBaseService(log, "FooService", fs)
	return fs
}

func (fs *FooService) OnStart() error {
	fs.BaseService.OnStart() // Always call the overridden method.
	// initialize private fields
	// start subroutines, etc.
}

func (fs *FooService) OnStop() error {
	fs.BaseService.OnStop() // Always call the overridden method.
	// close/destroy private fields
	// stop subroutines, etc.
}

func NewBaseService

func NewBaseService(logger log.Logger, name string, impl Service) *BaseService

NewBaseService creates a new BaseService.

func (*BaseService) IsRunning

func (bs *BaseService) IsRunning() bool

IsRunning implements Service by returning true or false depending on the service's state.

func (*BaseService) OnReset

func (bs *BaseService) OnReset() error

OnReset implements Service by panicking.

func (*BaseService) OnStart

func (bs *BaseService) OnStart() error

OnStart implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStart()

func (*BaseService) OnStop

func (bs *BaseService) OnStop()

OnStop implements Service by doing nothing. NOTE: Do not put anything in here, that way users don't need to call BaseService.OnStop()

func (*BaseService) Quit

func (bs *BaseService) Quit() <-chan struct{}

Quit Implements Service by returning a quit channel.

func (*BaseService) Reset

func (bs *BaseService) Reset() error

Reset implements Service by calling OnReset callback (if defined). An error will be returned if the service is running.

func (*BaseService) SetLogger

func (bs *BaseService) SetLogger(l log.Logger)

SetLogger implements Service by setting a logger.

func (*BaseService) Start

func (bs *BaseService) Start() error

Start implements Service by calling OnStart (if defined). An error will be returned if the service is already running or stopped. Not to start the stopped service, you need to call Reset.

func (*BaseService) Stop

func (bs *BaseService) Stop() error

Stop implements Service by calling OnStop (if defined) and closing quit channel. An error will be returned if the service is already stopped.

func (*BaseService) String

func (bs *BaseService) String() string

String implements Servce by returning a string representation of the service.

func (*BaseService) Wait

func (bs *BaseService) Wait()

Wait blocks until the service is stopped.

type Big

type Big big.Int

Big marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".

Negative integers are not supported at this time. Attempting to marshal them will return an error. Values larger than 256bits are rejected by Unmarshal but will be marshaled without error.

func NewBig

func NewBig(bigint *big.Int) *Big

NewBig new Big from big.Int

func (Big) MarshalJSON

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

MarshalJSON implements encoding.JSONMarshaler.

func (Big) MarshalText

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

MarshalText implements encoding.TextMarshaler

func (Big) String

func (b Big) String() string

String returns the hex encoding of b.

func (Big) ToBigInt

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

ToBigInt return big.Int

func (Big) ToBytes

func (b Big) ToBytes() []byte

ToBytes return []byte

func (*Big) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (*Big) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler

type Bytes

type Bytes []byte

func NewBytes

func NewBytes(data []byte) *Bytes

New new Bytes

func (Bytes) Bytes

func (bz Bytes) Bytes() []byte

Allow it to fulfill various interfaces in light-client, etc...

func (Bytes) Format

func (bz Bytes) Format(s fmt.State, verb rune)

func (Bytes) Marshal

func (bz Bytes) Marshal() ([]byte, error)

Marshal needed for protobuf compatibility

func (Bytes) MarshalJSON

func (bz Bytes) MarshalJSON() ([]byte, error)

MarshalJSON implement encoding/json Marshaler interface.

func (Bytes) String

func (bz Bytes) String() string

func (*Bytes) Unmarshal

func (bz *Bytes) Unmarshal(data []byte) error

Unmarshal needed for protobuf compatibility

func (*Bytes) UnmarshalJSON

func (bz *Bytes) UnmarshalJSON(data []byte) error

This is the point of Bytes.

func (*Bytes) UnmarshalText

func (bz *Bytes) UnmarshalText(data []byte) error

type Error

type Error interface {
	Error() string
	Stacktrace() Error
	Trace(offset int, format string, args ...interface{}) Error
	Data() interface{}
}

Usage with arbitrary error data:

```go

// Error construction
type MyError struct{}
var err1 error = NewErrorWithData(MyError{}, "my message")
...
// Wrapping
var err2 error  = ErrorWrap(err1, "another message")
if (err1 != err2) { panic("should be the same")
...
// Error handling
switch err2.Data().(type){
	case MyError: ...
    default: ...
}

```

func ErrorWrap

func ErrorWrap(cause interface{}, format string, args ...interface{}) Error

func NewError

func NewError(format string, args ...interface{}) Error

New Error with formatted message. The Error's Data will be a FmtError type.

func NewErrorWithData

func NewErrorWithData(data interface{}) Error

New Error with specified data.

type FmtError

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

FmtError is the data type for NewError() (e.g. NewError().Data().(FmtError)) Theoretically it could be used to switch on the format string.

```go

// Error construction
var err1 error = NewError("invalid username %v", "BOB")
var err2 error = NewError("another kind of error")
...
// Error handling
switch err1.Data().(cmn.FmtError).Format() {
	case "invalid username %v": ...
	case "another kind of error": ...
    default: ...
}

```

func (FmtError) Error

func (fe FmtError) Error() string

func (FmtError) Format

func (fe FmtError) Format() string

func (FmtError) String

func (fe FmtError) String() string

type Hash

type Hash [HashLength]byte

Hash represents the 32 byte Keccak256 hash of arbitrary data.

func BigToHash

func BigToHash(b *big.Int) Hash

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

func BytesToHash

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 HexToHash

func HexToHash(s string) Hash

HexToHash sets byte representation of s to hash. If b is larger than len(h), b will be cropped from the left.

func (Hash) Big

func (h Hash) Big() *big.Int

Big converts a hash to a big integer.

func (Hash) Bytes

func (h Hash) Bytes() []byte

Bytes gets the byte representation of the underlying hash.

func (Hash) Format

func (h Hash) Format(s fmt.State, c rune)

Format implements fmt.Formatter, forcing the byte slice to be formatted as is, without going through the stringer interface used for logging.

func (Hash) Generate

func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value

Generate implements testing/quick.Generator.

func (Hash) Hex

func (h Hash) Hex() string

Hex converts a hash to a hex string.

func (Hash) MarshalJSON

func (h Hash) MarshalJSON() ([]byte, error)

func (*Hash) SetBytes

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

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

func (h Hash) TerminalString() string

TerminalString implements log.TerminalStringer, formatting a string for console output during logging.

func (*Hash) UnmarshalJSON

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

UnmarshalJSON parses a hash in hex syntax.

type Hex

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

Hex Encode and Decode hex string with prefix 0x

func New

func New(prefix string) *Hex

func (*Hex) Decode

func (h *Hex) Decode(dst, src []byte) (int, error)

Decode hex []byte to struct []byte

func (*Hex) DecodeLen

func (h *Hex) DecodeLen(n int) int

DecodeLen decode dst len without prefix

func (*Hex) DecodeString

func (h *Hex) DecodeString(data string) ([]byte, error)

DecodeString decode hex string to []byte

func (*Hex) Encode

func (h *Hex) Encode(dst, src []byte) (int, error)

func (*Hex) EncodeBig

func (h *Hex) EncodeBig(data *big.Int) []byte

EncodeBig big.Int to []byte

func (*Hex) EncodeLen

func (h *Hex) EncodeLen(n int) int

EncodeLen get dst []byte len

func (*Hex) EncodeToString

func (h *Hex) EncodeToString(data []byte) string

EncodeToString encode []byte to string

func (*Hex) EncodeUint

func (h *Hex) EncodeUint(data uint) []byte

EncodeUint uint to []byte

func (*Hex) EncodeUint64

func (h *Hex) EncodeUint64(data uint64) []byte

EncodeUint64 uint64 to []byte

func (*Hex) HasPrefix

func (h *Hex) HasPrefix(data []byte) bool

HasPrefix check data has prefix

func (*Hex) MustDecodeString

func (h *Hex) MustDecodeString(data string) []byte

MustDecode decode hex string to []byte or panic error

func (*Hex) String

func (h *Hex) String() string

type Rand

type Rand struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Rand is a prng, that is seeded with OS randomness. The OS randomness is obtained from crypto/rand, however none of the provided methods are suitable for cryptographic usage. They all utilize math/rand's prng internally.

All of the methods here are suitable for concurrent use. This is achieved by using a mutex lock on all of the provided methods.

func NewRand

func NewRand() *Rand

func (*Rand) Bool

func (r *Rand) Bool() bool

Bool returns a uniformly random boolean

func (*Rand) Bytes

func (r *Rand) Bytes(n int) []byte

Bytes returns n random bytes generated from the internal prng.

func (*Rand) Float32

func (r *Rand) Float32() float32

func (*Rand) Float64

func (r *Rand) Float64() float64

func (*Rand) Int

func (r *Rand) Int() int

func (*Rand) Int16

func (r *Rand) Int16() int16

func (*Rand) Int31

func (r *Rand) Int31() int32

func (*Rand) Int31n

func (r *Rand) Int31n(n int32) int32

func (*Rand) Int32

func (r *Rand) Int32() int32

func (*Rand) Int63

func (r *Rand) Int63() int64

func (*Rand) Int63n

func (r *Rand) Int63n(n int64) int64

func (*Rand) Int64

func (r *Rand) Int64() int64

func (*Rand) Intn

func (r *Rand) Intn(n int) int

Intn returns, as an int, a uniform pseudo-random number in the range [0, n). It panics if n <= 0.

func (*Rand) Perm

func (r *Rand) Perm(n int) []int

Perm returns a pseudo-random permutation of n integers in [0, n).

func (*Rand) Seed

func (r *Rand) Seed(seed int64)

func (*Rand) Str

func (r *Rand) Str(length int) string

Str constructs a random alphanumeric string of given length.

func (*Rand) Time

func (r *Rand) Time() time.Time

func (*Rand) Uint

func (r *Rand) Uint() uint

func (*Rand) Uint16

func (r *Rand) Uint16() uint16

func (*Rand) Uint32

func (r *Rand) Uint32() uint32

func (*Rand) Uint64

func (r *Rand) Uint64() uint64

type Service

type Service interface {
	// Start the service.
	// If it's already started or stopped, will return an error.
	// If OnStart() returns an error, it's returned by Start()
	Start() error
	OnStart() error

	// Stop the service.
	// If it's already stopped, will return an error.
	// OnStop must never error.
	Stop() error
	OnStop()

	// Reset the service.
	// Panics by default - must be overwritten to enable reset.
	Reset() error
	OnReset() error

	// Return true if the service is running
	IsRunning() bool

	// Quit returns a channel, which is closed once service is stopped.
	Quit() <-chan struct{}

	// String representation of the service
	String() string

	// SetLogger sets a logger.
	SetLogger(log.Logger)
}

Service defines a service that can be started, stopped, and reset.

type Uint

type Uint uint

Uint marshals/unmarshals as a JSON string with 0x prefix.

func NewUint

func NewUint(i uint) *Uint

func (Uint) MarshalJSON

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

MarshalJSON implements encoding.JSONMarshaler.

func (Uint) MarshalText

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

MarshalText implements encoding.TextMarshaler.

func (Uint) String

func (b Uint) String() string

String returns the hex encoding of b.

func (Uint) ToBytes

func (b Uint) ToBytes() []byte

ToBytes return the []byte

func (Uint) Touint

func (b Uint) Touint() uint

Touint return the uint

func (*Uint) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (*Uint) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler.

type Uint64

type Uint64 uint64

Uint64 marshals/unmarshals as a JSON string with 0x prefix. The zero value marshals as "0x0".

func NewUint64

func NewUint64(i uint64) *Uint64

NewUint64 create Uint64 from uint64

func (Uint64) MarshalJSON

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

MarshalJSON implements encoding.JSONMarshaler.

func (Uint64) MarshalText

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

MarshalText implements encoding.TextMarshaler.

func (Uint64) String

func (b Uint64) String() string

String returns the hex encoding of b.

func (Uint64) ToBytes

func (b Uint64) ToBytes() []byte

ToBytes return []byte

func (Uint64) Touint64

func (b Uint64) Touint64() uint64

Touint64 return uint64

func (*Uint64) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (*Uint64) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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