common

package module
v0.0.0-...-a87a6b4 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2023 License: GPL-3.0 Imports: 16 Imported by: 3

Documentation

Overview

Package common contains various helper functions.

Index

Constants

View Source
const (
	// CfgConfigPath defines custom config path
	CfgConfigPath = "config.path"

	// CfgDataPath defines custom DB path
	CfgDataPath = "data.path"

	// CfgKeyPath defines custom key path
	CfgKeyPath = "key.path"

	// CfgNodeType indicates the type of the node, e.g. blockchain node/edge node
	CfgNodeType = "node.type"
	// CfgForceValidateSnapshot defines wether validation of snapshot can be skipped
	CfgForceValidateSnapshot = "snapshot.force_validate"

	// CfgGenesisHash defines the hash of the genesis block
	CfgGenesisHash = "genesis.hash"
	// CfgGenesisChainID defines the chainID.
	CfgGenesisChainID = "genesis.chainID"

	// CfgConsensusMaxEpochLength defines the maxium length of an epoch.
	CfgConsensusMaxEpochLength = "consensus.maxEpochLength"
	// CfgConsensusMinBlockTime defines the minimal block interval (in seconds)
	CfgConsensusMinBlockInterval = "consensus.minBlockInterval"
	// CfgConsensusMessageQueueSize defines the capacity of consensus message queue.
	CfgConsensusMessageQueueSize = "consensus.messageQueueSize"
	// CfgConsensusEdgeNodeVoteQueueSize defines the capacity of edge node vote message queue.
	CfgConsensusEdgeNodeVoteQueueSize = "consensus.edgeNodeVoteQueueSize"
	// CfgConsensusPassThroughSentryVote defines the how sentry vote is handled.
	CfgConsensusPassThroughSentryVote = "consensus.passThroughSentryVote"

	// CfgStorageRollingEnabled indicates whether rolling is enabled
	CfgStorageRollingEnabled = "storage.stateRollingEnabled"
	// CfgStorageStatePruningEnabled indicates whether state pruning is enabled
	CfgStorageStatePruningEnabled = "storage.statePruningEnabled"
	// CfgStorageStatePruningInterval indicates the purning interval (in terms of blocks)
	CfgStorageStatePruningInterval = "storage.statePruningInterval"
	// CfgStorageStatePruningRetainedBlocks indicates the number of blocks prior to the latest finalized block to be retained
	CfgStorageStatePruningRetainedBlocks = "storage.statePruningRetainedBlocks"
	// CfgStorageStatePruningSkipCheckpoints indicates if the checkpoint state trie should be retained
	CfgStorageStatePruningSkipCheckpoints = "storage.statePruningSkipCheckpoints"
	// CfgStorageLevelDBCacheSize indicates Level DB cache size
	CfgStorageLevelDBCacheSize = "storage.levelDBCacheSize"
	// CfgStorageLevelDBHandles indicates Level DB handle count
	CfgStorageLevelDBHandles = "storage.levelDBHandles"
	// CfgStorageRollingInterval is the block interval that we start new db layer
	CfgStorageRollingInterval = "storage.rollingInterval"

	// CfgSyncMessageQueueSize defines the capacity of Sync Manager message queue.
	CfgSyncMessageQueueSize = "sync.messageQueueSize"
	// CfgSyncDownloadByHash indicates whether should download blocks using hash.
	CfgSyncDownloadByHash = "sync.downloadByHash"
	// CfgSyncDownloadByHeader indicates whether should download blocks using header.
	CfgSyncDownloadByHeader = "sync.downloadByHeader"

	// CfgP2POpt sets which P2P network to use: p2p, libp2p, or both.
	CfgP2POpt = "p2p.opt"
	// CfgP2PReuseStream sets whether to reuse libp2p stream
	CfgP2PReuseStream = "p2p.reuseStream"
	// CfgP2PName sets the ID of local node in P2P network.
	CfgP2PName = "p2p.name"
	// CfgP2PVersion sets the version of P2P network.
	CfgP2PVersion = "p2p.version"
	// CfgP2PProtocolPrefix sets the protocol prefix of P2P network.
	CfgP2PProtocolPrefix = "p2p.protocolPrefix"
	// CfgP2PPort sets the port used by P2P network.
	CfgP2PPort = "p2p.port"
	// CfgP2PLPort sets the port used by P2P network.
	CfgP2PLPort = "p2p.libp2pPort"
	// CfgP2PIsBootstrapNode specifies whether the node acts as a boostrap node
	CfgP2PIsBootstrapNode = "p2p.isBootstrapNode"
	// CfgP2PBootstrapNodePurgePeerInterval specifies the interval (in seconds) for a bootstrap node to purge all non-seed peers
	//CfgP2PBootstrapNodePurgePeerInterval = "p2p.bootstrapNodePurgePeerInterval"
	// CfgP2PBootstrapSeeds sets the boostrap peers.
	CfgP2PBootstrapSeeds = "p2p.bootstrapSeeds"
	// CfgP2PSeeds sets the seed peers.
	CfgP2PSeeds = "p2p.seeds"
	// CfgLibP2PSeeds sets the boostrap peers in libp2p format.
	CfgLibP2PSeeds = "p2p.libp2pSeeds"
	// CfgLibP2PRendezvous is the libp2p rendezvous string
	CfgLibP2PRendezvous = "p2p.libp2pRendezvous"
	// CfgP2PMessageQueueSize sets the message queue size for network interface.
	CfgP2PMessageQueueSize = "p2p.messageQueueSize"
	// CfgP2PSeedPeerOnlyOutbound decides whether only the seed peers can be outbound peers.
	CfgP2PSeedPeerOnlyOutbound = "p2p.seedPeerOnlyOutbound"
	// CfgP2PSeedPeerOnly decides whether the node will connect to peers other than the seeds.
	CfgP2PSeedPeerOnly = "p2p.seedPeerOnly"
	// CfgP2PMinNumPeers specifies the minimal number of peers a node tries to maintain
	CfgP2PMinNumPeers = "p2p.minNumPeers"
	// CfgP2PMaxNumPeers specifies the maximal number of peers a node can simultaneously connected to
	CfgP2PMaxNumPeers = "p2p.maxNumPeers"
	// CfgMaxNumPersistentPeers sets the max number of peers to persist for normal nodes
	CfgMaxNumPersistentPeers = "p2p.maxNumPersistentPeers"
	// CfgP2PMaxNumPeersToBroadcast specifies the maximal number of peers to broadcast a message to
	CfgP2PMaxNumPeersToBroadcast = "p2p.maxNumPeersToBroadcast"
	// CfgBufferPoolSize defines the number of buffers in the pool.
	CfgBufferPoolSize = "p2p.bufferPoolSize"
	// CfgP2PConnectionFIFO specifies if the incoming connection policy is FIFO or LIFO
	CfgP2PConnectionFIFO = "p2p.connectionFIFO"
	// CfgP2PNatMapping sets whether to perform NAT mapping
	CfgP2PNatMapping = "p2p.natMapping"
	// CfgP2PMaxConnections specifies the number of max connections a node can accept
	CfgP2PMaxConnections = "p2p.maxConnections"

	// CfgSyncInboundResponseWhitelist filters inbound messages based on peer ID.
	CfgSyncInboundResponseWhitelist = "sync.inboundResponseWhitelist"

	// CfgRPCEnabled sets whether to run RPC service.
	CfgRPCEnabled = "rpc.enabled"
	// CfgRPCAddress sets the binding address of RPC service.
	CfgRPCAddress = "rpc.address"
	// CfgRPCPort sets the port of RPC service.
	CfgRPCPort = "rpc.port"
	// CfgRPCMaxConnections limits concurrent connections accepted by RPC server.
	CfgRPCMaxConnections = "rpc.maxConnections"
	// CfgRPCTimeoutSecs set a timeout for RPC.
	CfgRPCTimeoutSecs = "rpc.timeoutSecs"

	// CfgLogLevels sets the log level.
	CfgLogLevels = "log.levels"
	// CfgLogPrintSelfID determines whether to print node's ID in log (Useful in simulation when
	// there are more than one node running).
	CfgLogPrintSelfID = "log.printSelfID"

	// CfgSentryRoundLength defines the length of a sentry voting round.
	CfgSentryRoundLength = "sentry.roundLength"

	// Graphite Server to collet metrics
	CfgMetricsServer = "metrics.server"

	// CfgProfEnabled to enable profiling
	CfgProfEnabled = "prof.enabled"

	// CfgForceGCEnabled to enable force GC
	CfgForceGCEnabled = "gc.enabled"

	// CfgDebugLogSelectedEENPs to enable logging of selected eenps
	CfgDebugLogSelectedEENPs = "debug.logSelectedEENPs"
)
View Source
const (
	// HashLength is the expected length of the hash
	HashLength = 32
	// AddressLength is the expected length of the adddress
	AddressLength = 20
)

Lengths of hashes and addresses in bytes.

View Source
const CheckpointInterval = int64(100)

CheckpointInterval defines the interval between checkpoints.

View Source
const (
	FeatureSentry uint64 = 0
)

Starting block heights of features.

View Source
const HeightEnableDneroV1 uint64 = 1001 // block #1001

HeightEnableDneroV1 specifies the minimal block height to enable the DneroV1.0 feature.

View Source
const HeightEnableDneroV2 uint64 = 100001 // block #100001

HeightEnableDneroV2 specifies the minimal block height to enable the DneroV2.0 feature.

View Source
const HeightEnableSmartContract uint64 = 60001 // block #60001

HeightEnableSmartContract specifies the minimal block height to eanble the Turing-complete smart contract support

View Source
const HeightEnableValidatorReward uint64 = 50001 // block #50001

HeightEnableValidatorReward specifies the minimal block height to enable the validtor DTOKEN reward

View Source
const HeightNewFeeAdjustment uint64 = 80001 // block #80001

HeightNewFeeAdjustment specifies the block heigth to enable transaction fee burning adjustment

View Source
const HeightRPCCompatibility uint64 = 70001 // block #70001

HeightRPCCompatibility specifies the block height to enable Ethereum compatible RPC support

View Source
const HeightSampleStakingReward uint64 = 90001 // block #90001

HeightSampleStakingReward specifies the block heigth to enable sampling of staking reward

View Source
const HeightSupportDneroTokenInSmartContract uint64 = 120001 // block #120001

HeightSupportDneroTokenInSmartContract specifies the block height to support Dnero in smart contracts

View Source
const HeightSupportWrappedDnero uint64 = 150001 // block #150001

HeightSupportWrappedDnero specifies the block height to support wrapped Dnero

View Source
const HeightTxWrapperExtension uint64 = 110001 // block #110001

HeightTxWrapperExtension specifies the block height to extend the Tx Wrapper

View Source
const InitialConfig = `# Dnero configuration
p2p:
  port: 6000
  seeds: 127.0.0.1:7000,127.0.0.1:8000
`

InitialConfig is the default configuration produced by init command.

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)

	BigMaxUint16 = new(big.Int).SetUint64(1<<16 - 1)
	BigMaxUint32 = new(big.Int).SetUint64(1<<32 - 1)
	BigMaxUint64 = new(big.Int).SetUint64(1<<64 - 1)
)

Common big integers often used

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

func IsCheckPointHeight(height uint64) bool

IsCheckPointHeight returns if a block height is a checkpoint.

func IsHexAddress

func IsHexAddress(s string) bool

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

func LastCheckPointHeight

func LastCheckPointHeight(height uint64) uint64

LastCheckPointHeight returns the height of the last checkpoint

func LeftPadBytes

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

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

func Parallel

func Parallel(tasks ...func())

Parallel executes multiple tasks in parallel

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 WriteFileAtomic

func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error

WriteFileAtomic writes to newBytes to filePath. Guaranteed not to lose *both* oldBytes and newBytes, (assuming that the OS is perfect)

func WriteInitialConfig

func WriteInitialConfig(filePath string) error

WriteInitialConfig writes initial config file to file system.

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

func (a Address) Big() *big.Int

Big converts an address to a big integer.

func (Address) Bytes

func (a Address) Bytes() []byte

Bytes gets the string representation of the underlying address.

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

func (a Address) IsEmpty() bool

IsEmpty returns whether this address is empty.

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

type Bytes []byte

Bytes represents bytes type.

func (Bytes) String

func (b Bytes) String() string

type ChannelIDEnum

type ChannelIDEnum byte

ChannelIDEnum defines the channelID for different type of data for synchronization among blockchain nodes

const (

	// ChannelIDInvalid indicates an invalid channel
	ChannelIDInvalid ChannelIDEnum = iota

	// ChannelIDCheckpoint indicates the channel for Checkpoint
	ChannelIDCheckpoint

	// ChannelIDHeader indicates the channel for Header
	ChannelIDHeader

	// ChannelIDBlock indicates the channel for Block
	ChannelIDBlock

	// ChannelIDProposal indicates the channel for Proposal
	ChannelIDProposal

	// ChannelIDCC indicates the channel for Commit Certificate
	ChannelIDCC

	// ChannelIDVote indicates the channel for Vote
	ChannelIDVote

	// ChannelIDTransaction indicates the channel for Transaction
	ChannelIDTransaction

	// ChannelIDPeerDiscovery indicates the channel for Peer Discovery information exchange
	ChannelIDPeerDiscovery

	// ChannelIDPing indicates the channel for Ping/Pong messages between peers
	ChannelIDPing

	// ChannelIDSentry indicates the channel for Sentry messages between peers
	ChannelIDSentry

	// ChannelIDNATMapping indicates the channel for NAT Mapping messages between peers
	ChannelIDNATMapping

	// ChannelIDEliteEdgeNode indicates the channel for Elite Edge Node vote messages
	ChannelIDEliteEdgeNodeVote

	// ChannelIDAggregatedEliteEdgeNodeVotes indicates the channel for Elite Edge Node aggregated vote messages
	ChannelIDAggregatedEliteEdgeNodeVotes
)

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

func (h Hash) IsEmpty() bool

IsEmpty checks whether a hash is empty.

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

type JSONBig big.Int

func (JSONBig) MarshalText

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

MarshalText implements encoding.TextMarshaler

func (*JSONBig) ToInt

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

ToInt converts b to a big.Int.

func (*JSONBig) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (*JSONBig) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler

type JSONUint64

type JSONUint64 uint64

func (JSONUint64) MarshalText

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

MarshalText implements encoding.TextMarshaler.

func (*JSONUint64) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler.

func (*JSONUint64) UnmarshalText

func (b *JSONUint64) UnmarshalText(raw []byte) error

UnmarshalText implements encoding.TextUnmarshaler

type MessageIDEnum

type MessageIDEnum uint8
const (
	MessageIDInvRequest MessageIDEnum = iota
	MessageIDInvResponse
	MessageIDDataRequest
	MessageIDDataResponse
)

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 NodeType

type NodeType int

NodeType defines different types of nodes in the network

const (

	// NodeTypeInvalid indicates an invalid type of node
	NodeTypeInvalid NodeType = iota

	// NodeTypeBlockchainNode indicates the node/peer is a blockchain node (i.e. validator/sentry/wallet node)
	NodeTypeBlockchainNode

	// NodeTypeEdgeNode indicates the node/peer is an edge node
	NodeTypeEdgeNode
)

type P2POptEnum

type P2POptEnum int

P2POptEnum defines the p2p network

const (

	// P2POptOld indicates the old p2p network
	P2POptOld P2POptEnum = iota

	// P2POptLibp2p indicates libp2p network
	P2POptLibp2p

	// P2POptBoth indicates using both networks at the same time
	P2POptBoth
)

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 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.
Go port of Coda Hale's Metrics library
Go port of Coda Hale's Metrics library
exp
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler
Hook go-metrics into expvar on any /debug/metrics request, load all vars from the registry into expvar, and execute regular expvar handler

Jump to

Keyboard shortcuts

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