common

package
v0.0.0-...-5663add Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: Apache-2.0, GPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package common contains various helper functions.

Package ethereum defines interfaces for interacting with Ethereum.

Index

Constants

View Source
const (
	Success                    string = "0x0"
	Unknown                    string = "0x1"
	BadRLP                     string = "0x2"
	InvalidFormat              string = "0x3"
	OutOfGasIntrinsic          string = "0x4"
	InvalidSignature           string = "0x5"
	InvalidNonce               string = "0x6"
	NotEnoughCash              string = "0x7"
	OutOfGasBase               string = "0x8"
	BlockGasLimitReached       string = "0x9"
	BadInstruction             string = "0xa"
	BadJumpDestination         string = "0xb"
	OutOfGas                   string = "0xc"
	OutOfStack                 string = "0xd"
	StackUnderflow             string = "0xe"
	NonceCheckFail             string = "0xf"
	BlockLimitCheckFail        string = "0x10"
	FilterCheckFail            string = "0x11"
	NoDeployPermission         string = "0x12"
	NoCallPermission           string = "0x13"
	NoTxPermission             string = "0x14"
	PrecompiledError           string = "0x15"
	RevertInstruction          string = "0x16"
	InvalidZeroSignatureFormat string = "0x17"
	AddressAlreadyUsed         string = "0x18"
	PermissionDenied           string = "0x19"
	CallAddressError           string = "0x1a"

	// precompile
	BCOS_RC1 string = "2.0.0-rc1"
	BCOS_RC2 string = "2.0.0-rc2"
	BCOS_RC3 string = "2.0.0-rc3"

	// system table for authority control
	USER_TABLE_PREFIX string = "_user_"
	SYS_TABLE         string = "_sys_tables_"
	SYS_TABLE_ACCESS  string = "_sys_table_access_"
	SYS_CONSENSUS     string = "_sys_consensus_"
	SYS_CNS           string = "_sys_cns_"
	SYS_CONFIG        string = "_sys_config_"

	// precompile success
	PreSuccess                      int = 0
	PermissionDenied_RC1            int = 80
	PermissionDenied_RC3            int = -50000
	TableExist                      int = 50001
	TableExist_RC3                  int = -50001
	TableNameAndAddressExist_RC1    int = 56
	TableNameAndAddressExist        int = 51000
	TableNameAndAddressExist_RC3    int = -51000
	TableNameAndAddressNotExist_RC1 int = 57
	TableNameAndAddressNotExist     int = 51001
	TableNameAndAddressNotExist_RC3 int = -51001
	InvalidNodeId                   int = -51100
	LastSealer_RC1                  int = 100
	LastSealer                      int = 51101
	LastSealer_RC3                  int = -51101
	P2pNetwork                      int = -51102
	GroupPeers                      int = -51103
	SealerList                      int = -51104
	ObserverList                    int = -51105
	ContractNameAndVersionExist     int = -51200
	VersionExceeds                  int = -51201
	InvalidKey_RC1                  int = 157
	InvalidKey                      int = 51300
	InvalidKey_RC3                  int = -51300

	TABLE_KEY_MAX_LENGTH int = 255

	BCOS_VERSION string = ""
)
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

View Source
var NotFound = errors.New("not found")

NotFound is returned by API methods if the requested item does not exist.

Functions

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 FromHex

func FromHex(s string) []byte

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

func GetJsonStr

func GetJsonStr(output string) (string, error)

GetJsonStr returns the json string according to the output

func GetStatusMessage

func GetStatusMessage(status string) string

GetStatusMessage returns the status message

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

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

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

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

func TransferToJson

func TransferToJson(code int) (string, error)

TransferToJson returns the message json according to the status code

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

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

func (a Address) ImplementsGraphQLType(name string) bool

ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.

func (Address) MarshalText

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

MarshalText returns the hex representation of a.

func (*Address) Scan

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

func (a Address) String() string

String implements fmt.Stringer.

func (*Address) UnmarshalGraphQL

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

UnmarshalGraphQL unmarshals the provided GraphQL query data.

func (*Address) UnmarshalJSON

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

UnmarshalJSON parses a hash in hex syntax.

func (*Address) UnmarshalText

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

UnmarshalText parses a hash in hex syntax.

func (Address) Value

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

Value implements valuer for database/sql.

type CallMsg

type CallMsg struct {
	From     Address  // the sender of the 'transaction'
	To       *Address // the destination contract (nil for contract creation)
	Gas      uint64   // if 0, the call executes with near-infinite gas
	GasPrice *big.Int // wei <-> gas exchange ratio
	Value    *big.Int // amount of wei sent along with the call
	Data     []byte   // input data, usually an ABI-encoded contract method invocation
}

CallMsg contains parameters for contract calls.

type ChainStateReader

type ChainStateReader interface {
	BalanceAt(ctx context.Context, account Address, blockNumber *big.Int) (*big.Int, error)
	StorageAt(ctx context.Context, account Address, key Hash, blockNumber *big.Int) ([]byte, error)
	CodeAt(ctx context.Context, account Address, blockNumber *big.Int) ([]byte, error)
	NonceAt(ctx context.Context, account Address, blockNumber *big.Int) (uint64, error)
}

ChainStateReader wraps access to the state trie of the canonical blockchain. Note that implementations of the interface may be unable to return state values for old blocks. In many cases, using CallContract can be preferable to reading raw contract storage.

type ChainSyncReader

type ChainSyncReader interface {
	SyncProgress(ctx context.Context) (*SyncProgress, error)
}

ChainSyncReader wraps access to the node's current sync status. If there's no sync currently running, it returns nil.

type ContractCaller

type ContractCaller interface {
	CallContract(ctx context.Context, call CallMsg, blockNumber *big.Int) ([]byte, error)
}

A ContractCaller provides contract calls, essentially transactions that are executed by the EVM but not mined into the blockchain. ContractCall is a low-level method to execute such calls. For applications which are structured around specific contracts, the abigen tool provides a nicer, properly typed way to perform calls.

type FilterQuery

type FilterQuery struct {
	BlockHash *Hash     // used by eth_getLogs, return logs only from block with this hash
	FromBlock *big.Int  // beginning of the queried range, nil means genesis block
	ToBlock   *big.Int  // end of the range, nil means latest block
	Addresses []Address // restricts matches to events created by specific contracts

	// The Topic list restricts matches to particular event topics. Each event has a list
	// of topics. Topics matches a prefix of that list. An empty element slice matches any
	// topic. Non-empty elements represent an alternative that matches any of the
	// contained topics.
	//
	// Examples:
	// {} or nil          matches any topic list
	// {{A}}              matches topic A in first position
	// {{}, {B}}          matches any topic in first position AND B in second position
	// {{A}, {B}}         matches topic A in first position AND B in second position
	// {{A, B}, {C, D}}   matches topic (A OR B) in first position AND (C OR D) in second position
	Topics [][]Hash
}

FilterQuery contains options for contract log filtering.

type GasEstimator

type GasEstimator interface {
	EstimateGas(ctx context.Context, call CallMsg) (uint64, error)
}

GasEstimator wraps EstimateGas, which tries to estimate the gas needed to execute a specific transaction based on the pending state. There is no guarantee that this is the true gas limit requirement as other transactions may be added or removed by miners, but it should provide a basis for setting a reasonable default.

type GasPricer

type GasPricer interface {
	SuggestGasPrice(ctx context.Context) (*big.Int, error)
}

GasPricer wraps the gas price oracle, which monitors the blockchain to determine the optimal gas price given current fee market conditions.

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

func (_ Hash) ImplementsGraphQLType(name string) bool

ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.

func (Hash) MarshalText

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

MarshalText returns the hex representation of h.

func (*Hash) Scan

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

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

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

UnmarshalGraphQL unmarshals the provided GraphQL query data.

func (*Hash) UnmarshalJSON

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

UnmarshalJSON parses a hash in hex syntax.

func (*Hash) UnmarshalText

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

UnmarshalText parses a hash in hex syntax.

func (Hash) Value

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

Value implements valuer for database/sql.

type MixedcaseAddress

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

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

func NewMixedcaseAddress

func NewMixedcaseAddress(addr Address) MixedcaseAddress

NewMixedcaseAddress constructor (mainly for testing)

func NewMixedcaseAddressFromString

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

NewMixedcaseAddressFromString is mainly meant for unit-testing

func (*MixedcaseAddress) Address

func (ma *MixedcaseAddress) Address() Address

Address returns the address

func (*MixedcaseAddress) MarshalJSON

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

MarshalJSON marshals the original value

func (*MixedcaseAddress) Original

func (ma *MixedcaseAddress) Original() string

Original returns the mixed-case input string

func (*MixedcaseAddress) String

func (ma *MixedcaseAddress) String() string

String implements fmt.Stringer

func (*MixedcaseAddress) UnmarshalJSON

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

UnmarshalJSON parses MixedcaseAddress

func (*MixedcaseAddress) ValidChecksum

func (ma *MixedcaseAddress) ValidChecksum() bool

ValidChecksum returns true if the address has valid checksum

type PendingContractCaller

type PendingContractCaller interface {
	PendingCallContract(ctx context.Context, call CallMsg) ([]byte, error)
}

PendingContractCaller can be used to perform calls against the pending state.

type PendingStateReader

type PendingStateReader interface {
	PendingBalanceAt(ctx context.Context, account Address) (*big.Int, error)
	PendingStorageAt(ctx context.Context, account Address, key Hash) ([]byte, error)
	PendingCodeAt(ctx context.Context, account Address) ([]byte, error)
	PendingNonceAt(ctx context.Context, account Address) (uint64, error)
	PendingTransactionCount(ctx context.Context) (uint, error)
}

A PendingStateReader provides access to the pending state, which is the result of all known executable transactions which have not yet been included in the blockchain. It is commonly used to display the result of ’unconfirmed’ actions (e.g. wallet value transfers) initiated by the user. The PendingNonceAt operation is a good way to retrieve the next available transaction nonce for a specific account.

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

func (s StorageSize) TerminalString() string

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

type Subscription

type Subscription interface {
	// Unsubscribe cancels the sending of events to the data channel
	// and closes the error channel.
	Unsubscribe()
	// Err returns the subscription error channel. The error channel receives
	// a value if there is an issue with the subscription (e.g. the network connection
	// delivering the events has been closed). Only one value will ever be sent.
	// The error channel is closed by Unsubscribe.
	Err() <-chan error
}

Subscription represents an event subscription where events are delivered on a data channel.

type SyncProgress

type SyncProgress struct {
	StartingBlock uint64 // Block number where sync began
	CurrentBlock  uint64 // Current block number where sync is at
	HighestBlock  uint64 // Highest alleged block number in the chain
	PulledStates  uint64 // Number of state trie entries already downloaded
	KnownStates   uint64 // Total number of state trie entries known about
}

SyncProgress gives progress indications when the node is synchronising with the Ethereum network.

type UnprefixedAddress

type UnprefixedAddress Address

UnprefixedAddress allows marshaling an Address without 0x prefix.

func (UnprefixedAddress) MarshalText

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

MarshalText encodes the address as hex.

func (*UnprefixedAddress) UnmarshalText

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

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

type UnprefixedHash

type UnprefixedHash Hash

UnprefixedHash allows marshaling a Hash without 0x prefix.

func (UnprefixedHash) MarshalText

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

MarshalText encodes the hash as hex.

func (*UnprefixedHash) UnmarshalText

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

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

Directories

Path Synopsis
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

Jump to

Keyboard shortcuts

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