common

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2021 License: GPL-3.0 Imports: 18 Imported by: 1

README

common

Build Status

The common package contains the ethereum utility library.

Installation

As a subdirectory the main go-ethereum repository, you get it with go get github.com/matthieu/go-ethereum.

Usage

RLP (Recursive Linear Prefix) Encoding

RLP Encoding is an encoding scheme used by the Ethereum project. It encodes any native value or list to a string.

More in depth information about the encoding scheme see the Wiki article.

rlp := common.Encode("doge")
fmt.Printf("%q\n", rlp) // => "\0x83dog"

rlp = common.Encode([]interface{}{"dog", "cat"})
fmt.Printf("%q\n", rlp) // => "\0xc8\0x83dog\0x83cat"
decoded := common.Decode(rlp)
fmt.Println(decoded) // => ["dog" "cat"]

Patricia Trie

Patricie Tree is a merkle trie used by the Ethereum project.

More in depth information about the (modified) Patricia Trie can be found on the Wiki.

The patricia trie uses a db as backend and could be anything as long as it satisfies the Database interface found in common/db.go.

db := NewDatabase()

// db, root
trie := common.NewTrie(db, "")

trie.Put("puppy", "dog")
trie.Put("horse", "stallion")
trie.Put("do", "verb")
trie.Put("doge", "coin")

// Look up the key "do" in the trie
out := trie.Get("do")
fmt.Println(out) // => verb

trie.Delete("puppy")

The patricia trie, in combination with RLP, provides a robust, cryptographically authenticated data structure that can be used to store all (key, value) bindings.

// ... Create db/trie

// Note that RLP uses interface slices as list
value := common.Encode([]interface{}{"one", 2, "three", []interface{}{42}})
// Store the RLP encoded value of the list
trie.Put("mykey", value)

Value

Value is a Generic Value which is used in combination with RLP data or ([])interface{} structures. It may serve as a bridge between RLP data and actual real values and takes care of all the type checking and casting. Unlike Go's reflect.Value it does not panic if it's unable to cast to the requested value. It simple returns the base value of that type (e.g. Slice() returns []interface{}, Uint() return 0, etc).

Creating a new Value

NewEmptyValue() returns a new *Value with it's initial value set to a []interface{}

AppendList() appends a list to the current value.

Append(v) appends the value (v) to the current value/list.

val := common.NewEmptyValue().Append(1).Append("2")
val.AppendList().Append(3)
Retrieving values

Get(i) returns the i item in the list.

Uint() returns the value as an unsigned int64.

Slice() returns the value as a interface slice.

Str() returns the value as a string.

Bytes() returns the value as a byte slice.

Len() assumes current to be a slice and returns its length.

Byte() returns the value as a single byte.

val := common.NewValue([]interface{}{1,"2",[]interface{}{3}})
val.Get(0).Uint() // => 1
val.Get(1).Str()  // => "2"
s := val.Get(2)   // => Value([]interface{}{3})
s.Get(0).Uint()   // => 3

Decoding

Decoding streams of RLP data is simplified

val := common.NewValueFromBytes(rlpData)
val.Get(0).Uint()

Encoding

Encoding from Value to RLP is done with the Encode method. The underlying value can be anything RLP can encode (int, str, lists, bytes)

val := common.NewValue([]interface{}{1,"2",[]interface{}{3}})
rlp := val.Encode()
// Store the rlp data
Store(rlp)

Documentation

Overview

Package common contains various helper functions.

Index

Constants

View Source
const (
	// HashLength is the expected length of the hash
	HashLength = 32
	// AddressLength is the expected length of the address
	AddressLength = 20
)

Lengths of hashes and addresses in bytes.

Variables

View Source
var (
	Big1   = big.NewInt(1)
	Big2   = big.NewInt(2)
	Big3   = big.NewInt(3)
	Big0   = big.NewInt(0)
	Big32  = big.NewInt(32)
	Big256 = big.NewInt(256)
	Big257 = big.NewInt(257)
)

Common big integers often used

Functions

func AbsolutePath

func AbsolutePath(datadir string, filename string) string

AbsolutePath returns datadir + filename, or filename if it is absolute.

func Bytes2Hex

func Bytes2Hex(d []byte) string

Bytes2Hex returns the hexadecimal encoding of d.

func CopyBytes

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

CopyBytes returns an exact copy of the provided bytes.

func FileExist

func FileExist(filePath string) bool

FileExist checks if a file exists at filePath.

func FromHex

func FromHex(s string) []byte

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

func Hex2Bytes

func Hex2Bytes(str string) []byte

Hex2Bytes returns the bytes represented by the hexadecimal string str.

func Hex2BytesFixed

func Hex2BytesFixed(str string, flen int) []byte

Hex2BytesFixed returns bytes of a specified fixed length flen.

func IsHexAddress added in v1.13.1

func IsHexAddress(s string) bool

IsHexAddress verifies whether a string can represent a valid hex-encoded Ethereum address or not.

func LeftPadBytes

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

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

func LoadJSON added in v0.9.34

func LoadJSON(file string, val interface{}) error

LoadJSON reads the given file and unmarshals its content.

func MakeName

func MakeName(name, version string) string

MakeName creates a node name that follows the ethereum convention for such names. It adds the operation system name and Go runtime version the name.

func PrintDepricationWarning added in v1.13.1

func PrintDepricationWarning(str string)

PrintDepricationWarning prinst the given string in a box using fmt.Println.

func Report

func Report(extra ...interface{})

Report gives off a warning requesting the user to submit an issue to the github tracker.

func RightPadBytes

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

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

func ToHex deprecated

func ToHex(b []byte) string

ToHex returns the hex representation of b, prefixed with '0x'. For empty slices, the return value is "0x0".

Deprecated: use hexutil.Encode instead.

func ToHexArray added in v1.13.1

func ToHexArray(b [][]byte) []string

ToHexArray creates a array of hex-string based on []byte

func TrimLeftZeroes added in v1.13.1

func TrimLeftZeroes(s []byte) []byte

TrimLeftZeroes returns a subslice of s without leading zeroes

func TrimRightZeroes added in v1.13.1

func TrimRightZeroes(s []byte) []byte

TrimRightZeroes returns a subslice of s without trailing zeroes

Types

type Address

type Address [AddressLength]byte

Address represents the 20 byte address of an Ethereum account.

func BigToAddress

func BigToAddress(b *big.Int) Address

BigToAddress returns Address with byte values of b. If b is larger than len(h), b will be cropped from the left.

func BytesToAddress

func BytesToAddress(b []byte) Address

BytesToAddress returns Address with value b. If b is larger than len(h), b will be cropped from the left.

func HexToAddress

func HexToAddress(s string) Address

HexToAddress returns Address with byte values of s. If s is larger than len(h), s will be cropped from the left.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes gets the string representation of the underlying address.

func (Address) Format added in v1.13.1

func (a Address) 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 (Address) Hash

func (a Address) Hash() Hash

Hash converts an address to a hash by left-padding it with zeros.

func (Address) Hex

func (a Address) Hex() string

Hex returns an EIP55-compliant hex string representation of the address.

func (Address) ImplementsGraphQLType added in v1.13.1

func (a Address) ImplementsGraphQLType(name string) bool

ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.

func (Address) MarshalText added in v1.13.1

func (a Address) MarshalText() ([]byte, error)

MarshalText returns the hex representation of a.

func (*Address) Scan added in v1.13.1

func (a *Address) Scan(src interface{}) error

Scan implements Scanner for database/sql.

func (*Address) SetBytes

func (a *Address) SetBytes(b []byte)

SetBytes sets the address to the value of b. If b is larger than len(a) it will panic.

func (Address) Str

func (a Address) Str() string

func (Address) String added in v1.13.1

func (a Address) String() string

String implements fmt.Stringer.

func (*Address) UnmarshalGraphQL added in v1.13.1

func (a *Address) UnmarshalGraphQL(input interface{}) error

UnmarshalGraphQL unmarshals the provided GraphQL query data.

func (*Address) UnmarshalJSON added in v1.13.1

func (a *Address) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash in hex syntax.

func (*Address) UnmarshalText added in v1.13.1

func (a *Address) UnmarshalText(input []byte) error

UnmarshalText parses a hash in hex syntax.

func (Address) Value added in v1.13.1

func (a Address) Value() (driver.Value, error)

Value implements valuer for database/sql.

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 added in v1.13.1

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) ImplementsGraphQLType added in v1.13.1

func (Hash) ImplementsGraphQLType(name string) bool

ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.

func (Hash) MarshalText added in v1.13.1

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

MarshalText returns the hex representation of h.

func (*Hash) Scan added in v1.13.1

func (h *Hash) Scan(src interface{}) error

Scan implements Scanner for database/sql.

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 added in v1.13.1

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 added in v1.13.1

func (h Hash) TerminalString() string

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

func (*Hash) UnmarshalGraphQL added in v1.13.1

func (h *Hash) UnmarshalGraphQL(input interface{}) error

UnmarshalGraphQL unmarshals the provided GraphQL query data.

func (*Hash) UnmarshalJSON added in v1.13.1

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

UnmarshalJSON parses a hash in hex syntax.

func (*Hash) UnmarshalText added in v1.13.1

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

UnmarshalText parses a hash in hex syntax.

func (Hash) Value added in v1.13.1

func (h Hash) Value() (driver.Value, error)

Value implements valuer for database/sql.

type MixedcaseAddress added in v1.13.1

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

MixedcaseAddress retains the original string, which may or may not be correctly checksummed

func NewMixedcaseAddress added in v1.13.1

func NewMixedcaseAddress(addr Address) MixedcaseAddress

NewMixedcaseAddress constructor (mainly for testing)

func NewMixedcaseAddressFromString added in v1.13.1

func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error)

NewMixedcaseAddressFromString is mainly meant for unit-testing

func (*MixedcaseAddress) Address added in v1.13.1

func (ma *MixedcaseAddress) Address() Address

Address returns the address

func (*MixedcaseAddress) MarshalJSON added in v1.13.1

func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error)

MarshalJSON marshals the original value

func (*MixedcaseAddress) Original added in v1.13.1

func (ma *MixedcaseAddress) Original() string

Original returns the mixed-case input string

func (*MixedcaseAddress) String added in v1.13.1

func (ma *MixedcaseAddress) String() string

String implements fmt.Stringer

func (*MixedcaseAddress) UnmarshalJSON added in v1.13.1

func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error

UnmarshalJSON parses MixedcaseAddress

func (*MixedcaseAddress) ValidChecksum added in v1.13.1

func (ma *MixedcaseAddress) ValidChecksum() bool

ValidChecksum returns true if the address has valid checksum

type PrettyAge added in v1.13.1

type PrettyAge time.Time

PrettyAge is a pretty printed version of a time.Duration value that rounds the values up to a single most significant unit, days/weeks/years included.

func (PrettyAge) String added in v1.13.1

func (t PrettyAge) String() string

String implements the Stringer interface, allowing pretty printing of duration values rounded to the most significant time unit.

type PrettyDuration added in v1.13.1

type PrettyDuration time.Duration

PrettyDuration is a pretty printed version of a time.Duration value that cuts the unnecessary precision off from the formatted textual representation.

func (PrettyDuration) String added in v1.13.1

func (d PrettyDuration) String() string

String implements the Stringer interface, allowing pretty printing of duration values rounded to three decimals.

type StorageSize

type StorageSize float64

StorageSize is a wrapper around a float value that supports user friendly formatting.

func (StorageSize) String

func (s StorageSize) String() string

String implements the stringer interface.

func (StorageSize) TerminalString added in v1.13.1

func (s StorageSize) TerminalString() string

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

type UnprefixedAddress added in v1.13.1

type UnprefixedAddress Address

UnprefixedAddress allows marshaling an Address without 0x prefix.

func (UnprefixedAddress) MarshalText added in v1.13.1

func (a UnprefixedAddress) MarshalText() ([]byte, error)

MarshalText encodes the address as hex.

func (*UnprefixedAddress) UnmarshalText added in v1.13.1

func (a *UnprefixedAddress) UnmarshalText(input []byte) error

UnmarshalText decodes the address from hex. The 0x prefix is optional.

type UnprefixedHash added in v1.13.1

type UnprefixedHash Hash

UnprefixedHash allows marshaling a Hash without 0x prefix.

func (UnprefixedHash) MarshalText added in v1.13.1

func (h UnprefixedHash) MarshalText() ([]byte, error)

MarshalText encodes the hash as hex.

func (*UnprefixedHash) UnmarshalText added in v1.13.1

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

UnmarshalText decodes the hash from hex. The 0x prefix is optional.

Directories

Path Synopsis
Package bitutil implements fast bitwise operations.
Package bitutil implements fast bitwise operations.
Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper).
Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper).
Package hexutil implements hex encoding with 0x prefix.
Package hexutil implements hex encoding with 0x prefix.
Package math provides integer math utilities.
Package math provides integer math utilities.
Package mclock is a wrapper for a monotonic clock source
Package mclock is a wrapper for a monotonic clock source
Package prque implements a priority queue data structure supporting arbitrary value types and int64 priorities.
Package prque implements a priority queue data structure supporting arbitrary value types and int64 priorities.

Jump to

Keyboard shortcuts

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