common

package module
v1.7.4 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2024 License: Apache-2.0 Imports: 27 Imported by: 15

README

go-common

Documentation

Index

Constants

View Source
const (
	ETNone             ElectionType = 0
	ETVrf              ElectionType = 1
	ETManagedCommittee ElectionType = 4
	// Deprecated
	ETFixedCommittee ElectionType = 2
	// Deprecated
	ETFixedSpectator ElectionType = 3

	NilEpoch  = EpochNum(math.MaxUint64)
	NilEra    = EraNum(math.MaxUint64)
	NilHeight = Height(math.MaxUint64)
	NilBlock  = BlockNum(math.MaxUint32)
)

ETManagedCommittee:

  1. The consensus nodes in this chain will not participate in the election of other chains until the nodes quit from the consensus of this chain
  2. This type of chain no longer reports reward request, that is, there is no reward
  3. The start time of the election in this chain is the same as that in VRF, but the election request is broadcast directly on the basic network of main chain without packaging in a block
  4. Nodes that can participate in the election on thi chain will be stored under the key (models.AddressOfChainSettings, models.ManagedCommNodeIdsName) in this chain in the form of nodeid list. The byte slice value formed by the end to end connection of multiple values. By modifying this value, we can control the list of candidates who can run in the next election.
  5. When receiving the election request, all nodes will judge whether their nodeid is in the candidate list. If it is, they can join the basic network and the next consensus network of the chain, wait for the synchronization information, and then send the election results (Registration). The process here is same with VRF election, but the registration message type is different
  6. There's no lower limit for committee.size, and same upper limit with VRF election. The committee is composed of registered and legal candidates, sorted by nodeid from small to large, packaged and broadcast to the network. The process here is same with VRF election, but the election algorithm is different.
  7. 在此链中共识的节点不再参与其他链的选举,直到节点退出此链的共识
  8. 此类型链不再上报奖励请求,即无奖励
  9. 此链的选举开始时间与VRF一致,但选举请求不经过打包直接在0链基础网络上广播
  10. 可以参与选举的节点,会以NodeID列表的方式存储在本链models.AddressOfChainSettings的 models.ManagedCommNodeIdsName为名的键值中,多个值首尾相接形成的byte slice值。通过修改这 个值,来控制下次可以参选的候选人名单。
  11. 所有节点收到选举请求时,会判断自身NodeID是否在候选人名单中,如果在,就可以加入该链基础网络和下 届共识网络等待同步信息后再发送选举结果(报名),此处流程与VRF选举一致,不过报名消息类型不同
  12. 选举不再控制committee.size的下限,上限与VRF选举一致,Committee由报名的且合法的候选人,按 NodeID由小到大排序组成,并打包广播到本链网络中,除选举算法与VRF不同,流程完全一致
View Source
const (
	// default configuration
	DefaultP2PPort1      = 31000
	DefaultP2pPort2      = 31050
	DefaultRpcAddress    = "127.0.0.1:23017"
	DefaultEthRpcAddress = "127.0.0.1:32007"
	DefaultCompatible    = true

	// chain id related
	ReservedMaxChainID uint32 = 1 << 20
	MainChainID               = ChainID(0)
	NilChainID                = ChainID(ReservedMaxChainID)

	// length of types
	NodeIDBits        = 512
	NodeIDBytes       = NodeIDBits / 8
	HashLength        = 32
	AddressLength     = 20
	SeedLength        = 20
	ChainBytesLength  = 4 // chain id
	HeightBytesLength = 8 // height

	// upper limit of shards:<= 2^MaxExponentOfShards
	MaxExponentOfShards = 8
)
View Source
const (
	// event type of monitoring
	P2P = iota
	Event
	Block
)
View Source
const (
	// 0: origin
	// 1: add Version/Auditors
	ChainInfoVersion = 1
)

Variables

View Source
var (
	TypeOfAddress = reflect.TypeOf((*Address)(nil)).Elem()
	TypeOfHash    = reflect.TypeOf((*Hash)(nil)).Elem()
	EmptyNodeID   = NodeID{}
	EmptyAddress  = Address{}
	SystemNodeID  NodeID // NodeID of current node, which is initialized from the configuration file when the system starts

	TxCount       uint64
	NetDelay      []int                                       // range of system network delay [NetDelay[0]-NetDelay[1]]
	WaitingTime   time.Duration                               // Waiting time for consensus state switching, waiting for other nodes
	LastMsgTime   int64                                       // Timestamp of the last P2P message in the system
	LastEventTime int64                                       // Timestamp of the last consensus event processed
	LastBlockTime int64                                       // Timestamp of the last Block time
	LastBlocks    = LastBlockMap{M: make(map[ChainID]Height)} // The height of the last block processed by each chain
	PkgedBlocks   = LastBlockMap{M: make(map[ChainID]Height)} // Record the last block that each chain has been packaged by main chain
	Overflow      bool                                        // delta pool overflowed?
	NdType        *NodeType
	ForChain      *ChainID
	FullData      bool
	StandAlone    bool // if startup in standalone mode (one chain mode)
)
View Source
var (
	MainChainStruct = ChainStruct{
		ID:       MainChainID,
		ParentID: NilChainID,
		Mode:     Root,
	}

	// TypeOfChainStructPtr   = reflect.TypeOf((*ChainStruct)(nil))
	TypeOfChainInfosPtr = reflect.TypeOf((*ChainInfos)(nil))
)
View Source
var (
	DefaultStarterPK = "" /* 130-byte string literal not displayed */

	BlocksInEpoch uint64 = 1000
	EpochsInEra   uint64 = 36

	// base chainid for ethereum compatible
	BigChainIDBaseV2 uint64 = 100007
	BigChainIDBase   uint64 = 70000
)
View Source
var (
	DefaultRpcEndpoint    = Endpoint{NetType: "tcp", Address: DefaultRpcAddress}
	DefaultEthRpcEndpoint = Endpoint{NetType: "tcp", Address: DefaultEthRpcAddress}
)
View Source
var (
	EmptyPlaceHolder     struct{} = struct{}{}
	EmptyByteSliceHolder []byte   = make([]byte, 0)

	BytesBufferPool = sync.Pool{
		New: func() interface{} {
			return new(bytes.Buffer)
		},
	}

	BigIntPool = sync.Pool{
		New: func() interface{} {
			return new(big.Int)
		},
	}

	ErrAlreadyInitialized  = errors.New("already initialized")
	ErrAlreadyStarted      = errors.New("already started")
	ErrAlreadyStopped      = errors.New("already stopped")
	ErrNeedInitialization  = errors.New("need initialization")
	ErrNotStarted          = errors.New("not started yet")
	ErrIllegalStatus       = errors.New("illegal status")
	ErrNoAdapter           = errors.New("no adapter")
	ErrInsufficientLength  = errors.New("insufficient length")
	ErrLength              = errors.New("length error")
	ErrNil                 = errors.New("nil value")
	ErrNotFound            = errors.New("not found")
	ErrDuplicated          = errors.New("duplicated")
	ErrIllegalParams       = errors.New("illegal parameters")
	ErrUnsupported         = errors.New("unsupported")
	ErrUnknown             = errors.New("unknown error")
	ErrAlreadyDone         = errors.New("already done, operation ignored")
	ErrReservedAddress     = errors.New("reserved address")
	ErrMissMatch           = errors.New("miss match")
	ErrInsufficientBalance = errors.New("insufficient balance for transfer")

	EmptyHash    = Hash{}
	NilHashSlice = []byte(nil)
	NilHash      = BytesToHash(NilHashSlice)

	EmptyNodeHashSlice []byte
	EmptyNodeHash      Hash
)
View Source
var ErrGasLimitReached = errors.New("gas limit reached")

Functions

func BigIntForRLP added in v1.5.0

func BigIntForRLP(i *big.Int) *big.Int

func Bytes2Hex

func Bytes2Hex(d []byte) string

Bytes2Hex returns the hexadecimal encoding of d.

func BytesForRLP added in v1.5.0

func BytesForRLP(bs []byte) []byte

func BytesIntersection

func BytesIntersection(a, b [][]byte) [][]byte

func BytesIntersectionMap

func BytesIntersectionMap(a map[string]struct{}, b [][]byte) [][]byte

func BytesSliceEqual added in v1.4.0

func BytesSliceEqual(a, b [][]byte) bool

func CipherHash256

func CipherHash256(pro HashProvider, in ...[]byte) []byte

func CloneByteSlice

func CloneByteSlice(bytes []byte) []byte

func CompareSlices added in v1.3.6

func CompareSlices(a, b interface{}, objComparer func(x, y interface{}) int) int

func ConcatenateBytes

func ConcatenateBytes(bss [][]byte) []byte

Join the slice array of the parameter to return a slice. Nil and empty are allowed. The returned slice is not nil

func CopyBytes

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

CopyBytes returns an exact copy of the provided bytes.

func CopyBytesSlice

func CopyBytesSlice(in [][]byte) [][]byte

func DatabasePath

func DatabasePath(basePath string, id ChainID) string

func DecodeHex added in v1.7.2

func DecodeHex(h string) ([]byte, error)

func EncodeAndHash

func EncodeAndHash(o interface{}) ([]byte, error)

Hash calculation after serializing objects

func ForPrint

func ForPrint(v interface{}, poss ...int) []byte

func ForPrintSlice

func ForPrintSlice(s []byte, startPos int, endPos int) []byte

func ForPrintSliceString

func ForPrintSliceString(v interface{}, maxSize ...int) string

func ForPrintValue

func ForPrintValue(val reflect.Value, startPos, endPos int) []byte

func FormalizeBasePath

func FormalizeBasePath(path string) string

func FromHex

func FromHex(s string) []byte

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

func HasHexPrefix

func HasHexPrefix(str string) bool

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

func Hash256NoError

func Hash256NoError(in ...[]byte) []byte

func Hash256s

func Hash256s(in ...[]byte) ([]byte, error)

func HashEquals

func HashEquals(h1, h2 *Hash) bool

func HashLess

func HashLess(a, b Hash) bool

func HashObject

func HashObject(o interface{}) ([]byte, error)

If the object implements common.Hasher Interface, the HashValue() method is directly used to generate the hash value. Otherwise, hash will be performed after serializing the object

func HashPair

func HashPair(a []byte, b []byte) []byte

func HashPairOrder added in v1.3.24

func HashPairOrder(order bool, a, b []byte) ([]byte, error)

func HashRipemd160

func HashRipemd160(data []byte) []byte

func HashSliceEquals

func HashSliceEquals(h1, h2 []byte) bool

func HashsEquals

func HashsEquals(hs1, hs2 []Hash) bool

func HeaderIndexHash

func HeaderIndexHash(posBuffer [13]byte, index byte) []byte

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 HomeDir

func HomeDir() string

func InitShareObject

func InitShareObject(sopath string) *plugin.Plugin

func InitSharedObjectWithError added in v1.3.0

func InitSharedObjectWithError(sopath string) (*plugin.Plugin, error)

func InvalidHash added in v1.3.26

func InvalidHash(bs []byte) bool

func IsHex

func IsHex(str string) bool

IsHex validates whether each byte is valid hexadecimal string.

func IsHexAddress

func IsHexAddress(s string) bool

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

func IsHexCharacter

func IsHexCharacter(c byte) bool

isHexCharacter returns bool of c being a valid hexadecimal.

func IsNilHash

func IsNilHash(bs []byte) bool

func IsNodeIDIn

func IsNodeIDIn(nidhs []Hash, nid NodeID) bool

func KeyCount

func KeyCount() map[string]int

func LeftPadBytes

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

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

func MerkleHash

func MerkleHash(hashList [][]byte, toBeProof int, proofs *MerkleProofs) (root []byte, err error)

depth: If it is a positive number, it is the depth of the specified merkle tree. At this time, if the number of leaves of the complete binary tree specified by the depth is greater than len(hashList), at most one NilHashSlice is supplemented per layer

func MerkleHashComplete

func MerkleHashComplete(hashList [][]byte, toBeProof int, proofs *MerkleProofs) ([]byte, error)

func MerkleHashCompleteOld added in v1.3.46

func MerkleHashCompleteOld(hashList [][]byte, toBeProof int, proofs *MerkleProofs) ([]byte, error)

MerkleHash Calculate merkle tree root hash with hashlist parameter according to fixed algorithm. If proofs is not nil, put the merkle tree proof of the value of hashList[tobeproof] into proofs in order Return error is not nil if there's an error, []byte is meaningless. Proofs DOES NOT GUARANTEE no change at this time toBeProof is the index of the object to be proved in the hashlist array

func PackNodeIdsToBytes

func PackNodeIdsToBytes(nodeIds []NodeID) []byte

func ParseBytesToNodeIdBytes

func ParseBytesToNodeIdBytes(s []byte) ([][]byte, error)

func PointerCompare added in v1.3.29

func PointerCompare(a, b interface{}) (cmp int, needCompare bool)

func PointerSliceLess

func PointerSliceLess(slice interface{}, i, j int) (less bool, needCompare bool)

When sorting a pointer type object slice, the Less method needs to be written. The first part is to determine whether the object indicated by the i and j is nil. Nil is considered to be the smallest. If both are nil, they are considered to be equal. Only when both of them are not nil, the subsequent comparison is needed, and there is no need to check nil at this time. When needCompare returns false, the Less method can directly return the returned less value; otherwise, the comparison of the indexed objects needs to continue

func PrintBytesSlice

func PrintBytesSlice(bss [][]byte, length int) string

func RandomByteSlices added in v1.3.46

func RandomByteSlices(count, size int) [][]byte

func RandomBytes

func RandomBytes(length int) []byte

func RegisterNoCheckAddress

func RegisterNoCheckAddress(addrs ...Address)

func RegisterReservedAddress

func RegisterReservedAddress(addrs ...Address)

func RegisterSystemContract

func RegisterSystemContract(noGas bool, addrs ...Address)

func ReverseBytes

func ReverseBytes(bs []byte) []byte

func RightPadBytes

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

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

func ShiftBits added in v1.3.37

func ShiftBits(b0, b1 byte, shifts uint8, length ...uint8) byte

let b0.bit(0~7) and b1.bit(0~7) be bit(0~15), and returns bit(shifts, shifts+length) 0 <= shifts <= 7; 1<= length <= 8 default:8 ShiftBytes(0xf0, 0xf, 3, 7) would be 0x7e ShiftBytes(0xf0, 0xf, 3) would be 0xfe

func SlicesMerkleHash added in v1.4.0

func SlicesMerkleHash(values [][]byte, toBeProof int, proofs *MerkleProofs) (rootHash []byte, err error)

func SlicesMerkleHashComplete added in v1.4.0

func SlicesMerkleHashComplete(values [][]byte, toBeProof int, proofs *MerkleProofs) (rootHash []byte, err error)

func SlicesToHashs added in v1.4.0

func SlicesToHashs(bss [][]byte) [][]byte

func SplitBytes

func SplitBytes(bs []byte, size int) ([][]byte, error)

Divide bs into slices according to size, and each slice length is size

func SubBytes added in v1.3.37

func SubBytes(bs []byte, from, size int) ([]byte, error)

cut bytes from bs, bits [from, to)

func SystemHash256

func SystemHash256(in ...[]byte) []byte

func ToHeaderPosHashBuffer

func ToHeaderPosHashBuffer(id ChainID, height Height) [13]byte

func ValuesMerkleHash added in v1.3.26

func ValuesMerkleHash(values interface{}, toBeProof int, proofs *MerkleProofs) (rootHash []byte, err error)

func ValuesMerkleTreeHash

func ValuesMerkleTreeHash(values interface{}, toBeProof int, proofs *MerkleProofs) (rootHash []byte, err error)

func ValuesToHashs added in v1.3.25

func ValuesToHashs(values interface{}) ([][]byte, error)

func Watch

func Watch(tp int)

Monitor the event occurrence time

func WatchDelta

func WatchDelta(ovfl bool)

Monitoring Delta

func WatchHeight

func WatchHeight(id ChainID, height Height)

monitoring the height

Types

type AbstractService

type AbstractService struct {
	InitFunc  func() error
	StartFunc func() error
	CloseFunc func() error
	// contains filtered or unexported fields
}

func (*AbstractService) Close

func (s *AbstractService) Close() error

func (AbstractService) Copy

func (*AbstractService) Init

func (s *AbstractService) Init() error

func (*AbstractService) SetChanger

func (s *AbstractService) SetChanger(changer ServiceStateChanger)

func (*AbstractService) Start

func (s *AbstractService) Start() error

type AccountSharding

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

func (AccountSharding) AllIDs

func (as AccountSharding) AllIDs() []ChainID

func (AccountSharding) Clone added in v1.3.6

func (as AccountSharding) Clone() ShardInfo

func (AccountSharding) GetMaskBits

func (as AccountSharding) GetMaskBits() uint

func (AccountSharding) LocalID

func (as AccountSharding) LocalID() ChainID

func (AccountSharding) Number

func (as AccountSharding) Number() int

func (AccountSharding) ParentID

func (as AccountSharding) ParentID() ChainID

func (AccountSharding) Pos

func (as AccountSharding) Pos(id ChainID) int

Returns the location of ID in shard

func (AccountSharding) ShardTo

func (as AccountSharding) ShardTo(v interface{}) ChainID

func (*AccountSharding) String

func (as *AccountSharding) String() string

type AccountShards

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

func NewAccountShards

func NewAccountShards(parent ChainStruct, chains []ChainID) AccountShards

func (AccountShards) Clone added in v1.3.6

func (s AccountShards) Clone() AccountShards

func (AccountShards) GetMaskBits

func (s AccountShards) GetMaskBits() uint

type Address

type Address [AddressLength]byte

func AddressFromPubSlice

func AddressFromPubSlice(pub []byte) (Address, error)

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 BytesToAddressP

func BytesToAddressP(b []byte) *Address

func CreateAddress

func CreateAddress(b Address, nonce uint64) Address

CreateAddress creates an ethereum address given the bytes and the nonce

func CreateAddress2 added in v1.0.1

func CreateAddress2(b Address, salt [32]byte, inithash []byte) Address

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 StringsToAddresses

func StringsToAddresses(strings []string) []Address

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

func (a *Address) Clone() *Address

func (*Address) Cmp added in v1.3.6

func (a *Address) Cmp(o *Address) int

func (Address) Copy added in v1.3.31

func (a Address) Copy() *Address

func (*Address) Equal added in v1.3.30

func (a *Address) Equal(o *Address) bool

func (*Address) ForRLP added in v1.5.0

func (a *Address) ForRLP() *Address

func (*Address) FromRLP added in v1.5.0

func (a *Address) FromRLP() *Address

func (*Address) Generate

func (a *Address) Generate() error

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

func (a Address) IsNoGas() bool

func (Address) IsReserved

func (a Address) IsReserved() bool

func (Address) IsSystemContract

func (a Address) IsSystemContract() bool

func (Address) MarshalText

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

MarshalText returns the hex representation of a.

func (Address) NoCheck

func (a Address) NoCheck() bool

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) Slice added in v1.3.6

func (a *Address) Slice() []byte

func (Address) String

func (a Address) String() string

func (*Address) ToString added in v1.3.30

func (a *Address) ToString() string

func (*Address) UnmarshalJSON added in v1.3.4

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

func (a *Address) Value() Address

type AddressShard

type AddressShard struct {
	Index BitIndex // The index of the last bit (starting from 0), note that it is not the bit length (starting from 1)
	Value Bits
}

func (*AddressShard) IsIn

func (s *AddressShard) IsIn(addr Address) bool

func (*AddressShard) IsValid

func (s *AddressShard) IsValid() bool

type Addresser

type Addresser interface {
	Address() Address
}

type BitIndex

type BitIndex int

func (BitIndex) BitPos

func (p BitIndex) BitPos() uint

the bit index of the lowest byte (from highest 0 to lowest 7)

func (BitIndex) BytePos

func (p BitIndex) BytePos() int

the index of the location byte

func (BitIndex) Mask

func (p BitIndex) Mask(b byte) byte

returns higher n bits of b, which n is is the bit index of the lowest byte

type Bits

type Bits []byte

func (Bits) Bit

func (bs Bits) Bit(index BitIndex) bool

return true if the bit at index is 1, otherwise return false

func (Bits) Bits

func (bs Bits) Bits(length int) []bool

Returns the value of the highest consecutive length bits, and returns true when corresponding to bit 1, otherwise false. If the length of bs is not enough, the actual length of the returned array may be less than length

func (Bits) Byte

func (bs Bits) Byte(index int) (v byte, exist bool)

type BlockNum

type BlockNum uint32 // block number in one epoch

func (BlockNum) Bytes

func (bn BlockNum) Bytes() []byte

func (BlockNum) IsFirstOfEpoch added in v1.3.29

func (bn BlockNum) IsFirstOfEpoch() bool

func (BlockNum) IsLastOfEpoch

func (bn BlockNum) IsLastOfEpoch() bool

Is it the last block in an epoch

func (BlockNum) IsNil

func (bn BlockNum) IsNil() bool

func (BlockNum) IsValid added in v1.3.26

func (bn BlockNum) IsValid() bool

func (BlockNum) String

func (bn BlockNum) String() string

type BootNode

type BootNode struct {
	NodeID         NodeID `yaml:"nodeID" json:"nodeID"`       // ID of Node
	IP             string `yaml:"ip" json:"ip"`               //
	BasicPort      uint16 `yaml:"bNetPort" json:"bNetPort"`   // port for basic net
	ConsensusPort0 uint16 `yaml:"cNetPort0" json:"cNetPort0"` // port for consensus net 0
	ConsensusPort1 uint16 `yaml:"cNetPort1" json:"cNetPort1"` // port for consensus net 1
	DataPort       uint16 `yaml:"dNetPort" json:"dNetPort"`   // The data network is only used when transferring data between shard chains, and it uses the DataPort of the parent chain
}

Network entry: only supports network discovery, if it is only BootNode, there is no need to establish a TCP link (otherwise data forwarding is required, and the algorithm will fail in a structured network) BootNode must be a data node, and the data node may not be a BootNode, otherwise it cannot be judged and punished. Therefore, bootnode will still establish a tcp link

type ChainAttr

type ChainAttr string // Indicate the type, capacity, characteristics, etc. of the chain
const (
	AttrPoC    ChainAttr = "POC"    // Support algorithm of Proof of Capacity
	AttrReward ChainAttr = "REWARD" // Reward chain, there can only be one
	AttrNoGas  ChainAttr = "NOGAS"  // This chain and descendant chain do not charge gas fee, can be covered by descendant chain attribute
)

func (ChainAttr) IsValid

func (a ChainAttr) IsValid() bool

type ChainAttrs

type ChainAttrs []ChainAttr // Multiple Attributes that the chain may have

func (*ChainAttrs) Add

func (a *ChainAttrs) Add(attrs ...ChainAttr) error

Because the length is not large, de-duplication runs in rotation

func (*ChainAttrs) AddByName

func (a *ChainAttrs) AddByName(names ...string) error

func (ChainAttrs) Clone

func (a ChainAttrs) Clone() ChainAttrs

func (ChainAttrs) Contains

func (a ChainAttrs) Contains(attr ChainAttr) bool

func (ChainAttrs) FromMap

func (a ChainAttrs) FromMap(m map[ChainAttr]struct{}) ChainAttrs

func (ChainAttrs) Len

func (a ChainAttrs) Len() int

func (ChainAttrs) Less

func (a ChainAttrs) Less(i, j int) bool

func (ChainAttrs) Swap

func (a ChainAttrs) Swap(i, j int)

func (ChainAttrs) ToMap

func (a ChainAttrs) ToMap() map[ChainAttr]struct{}

func (ChainAttrs) ToStringSlice

func (a ChainAttrs) ToStringSlice() []string

type ChainID

type ChainID uint32 // ID of chain

func BytesToChainID

func BytesToChainID(bs []byte) ChainID

func (ChainID) Bytes

func (id ChainID) Bytes() []byte

func (ChainID) Compare added in v1.3.1

func (id ChainID) Compare(o ChainID) int

func (ChainID) Formalize

func (id ChainID) Formalize() []byte

func (ChainID) FromBig added in v1.3.40

func (id ChainID) FromBig(bi *big.Int) (cid ChainID, ok bool)

func (ChainID) FromFormalize added in v1.3.26

func (id ChainID) FromFormalize(bs []byte) ChainID

func (ChainID) HashValue

func (id ChainID) HashValue() ([]byte, error)

func (ChainID) IsMain

func (id ChainID) IsMain() bool

func (ChainID) IsNil

func (id ChainID) IsNil() bool

func (ChainID) IsReserved

func (id ChainID) IsReserved() bool

func (ChainID) IsSub

func (id ChainID) IsSub() bool

func (ChainID) IsUserDefined

func (id ChainID) IsUserDefined() bool

func (ChainID) String

func (id ChainID) String() string

type ChainIDs

type ChainIDs []ChainID

func (ChainIDs) Clone

func (ids ChainIDs) Clone() ChainIDs

func (ChainIDs) Equal added in v1.3.43

func (ids ChainIDs) Equal(os ChainIDs) bool

func (ChainIDs) Len

func (ids ChainIDs) Len() int

func (ChainIDs) Less

func (ids ChainIDs) Less(i, j int) bool

func (ChainIDs) String added in v1.3.43

func (ids ChainIDs) String() string

func (ChainIDs) Swap

func (ids ChainIDs) Swap(i, j int)

type ChainInfos

type ChainInfos struct {
	ChainStruct    `json:"chain"`
	SecondCoinId   CoinID       // ID of the local currency of this chain, 0 is the basic currency, indicating that the chain does not have a local currency
	SecondCoinName string       // If there is a local currency, it is the display name of the currency, otherwise it is ""
	HaveSecondCoin bool         // not in use, but should be !SecondCoinId.IsSovereign()
	AdminPubs      [][]byte     // Administrators' public key list
	GenesisCommIds NodeIDs      // Members of the genesis committee (orderly, only the genesis chain has a genesis committee, and the first committees of other chains are elected through the creation process)
	BootNodes      []Dataserver // BootNodes information
	Election       ElectionType // The election type of chain consensus committee
	ChainVersion   string       // not in use
	Syncblock      bool         // not in use
	GenesisDatas   NodeIDs      // Genesis data nodes
	Datas          NodeIDs      `json:"datanodes"` // Current data nodes, including all the genesis data nodes
	Attributes     ChainAttrs   // chain attributes
	Auditors       NodeIDs      // auditor ids (Auditors+GenesisDatas+Datas=AllAuditors)
	Version        uint16       // version, 1: add Version/Auditors
}

TODO: v1.3.6,Currently BootNode and DataNode can be set separately, but DataRpcPort should

be in DataNode instead of BootNode.  Two new attributes can be added: GenesisDataInfos and
DataInfos, which are used to save the ID/IP and RPC port number of the data node. In order
to be compatible with the old version, when the new field is empty, the hash is not
calculated, and the chain structure can only be modified through the system contract. Only
then will all the values of GenesisDatas/Datas be filled with RPC information and put into
GenesisDataInfos/DataInfos.

TODO: v1.5.0,The DataPort should also be in the DataNode settings; at the same time, the

sharding information needs to be added, because the current sharding prefix is determined
according to the number of shards under the same parent chain, but our chain can only do
one-to-two splits. That is to say, the prefixes of the shards under the same parent chain
are likely to be inconsistent in length. For example, there are 5 shards under chain 1 and
their prefixes are: 00, 01, 100, 101, 11, where 100 and 101 are split by 10. Then, this
information can only be recorded in the chain structure, and it has an effect when generating
ShardInfo.

TODO: v1.3.6,目前BootNode和DataNode可以分开设置,但DataRpcPort应该在DataNode中,而不是BootNode。

可以新增两个属性:GenesisDataInfos和DataInfos,用来保存数据节点的ID/IP以及RPC端口号,为了兼容旧版本,
当新增字段为空时不计算Hash,并只有在通过系统合约修改链结构时才会将所有GenesisDatas/Datas的值补上RPC信
息放到GenesisDataInfos/DataInfos中。

TODO: v1.5.0,DataPort也应该在DataNode的设置中;同时需要增加分片信息,因为目前的分片前缀是根据在同一

父链下分片的个数确定的,但我们的链只能做一分二的动作,也就是说同一父链下的分片前缀很有可能长度不一致,如1链
下有5个分片他们的前缀分别为:00,01,100,101,11,其中100和101是由10分裂而来的,这个信息只能记录在链结
构中,在生成ShardInfo时产生效果。

func (*ChainInfos) AddBootNode

func (c *ChainInfos) AddBootNode(bootNode Dataserver) bool

func (*ChainInfos) AddDataNode

func (c *ChainInfos) AddDataNode(node NodeID) bool

func (*ChainInfos) AddrIsAdmin

func (c *ChainInfos) AddrIsAdmin(addr Address) bool

func (*ChainInfos) Clone

func (c *ChainInfos) Clone() *ChainInfos

func (*ChainInfos) GetAuditorIds added in v1.3.26

func (c *ChainInfos) GetAuditorIds() NodeIDs

func (*ChainInfos) GetAuditorMap added in v1.3.26

func (c *ChainInfos) GetAuditorMap() map[NodeID]struct{}

func (*ChainInfos) GetDataNodes

func (c *ChainInfos) GetDataNodes() []NodeID

func (*ChainInfos) HasAttribute

func (c *ChainInfos) HasAttribute(attr ChainAttr) bool

func (*ChainInfos) HasDataNode

func (c *ChainInfos) HasDataNode(nid NodeID) bool

func (*ChainInfos) HashValue added in v1.3.26

func (c *ChainInfos) HashValue() ([]byte, error)

func (*ChainInfos) Index

func (c *ChainInfos) Index(nid NodeID) int

func (*ChainInfos) IsGenesisDataNode

func (c *ChainInfos) IsGenesisDataNode(nid NodeID) bool

func (*ChainInfos) IsMainChain

func (c *ChainInfos) IsMainChain() bool

func (*ChainInfos) IsPocChain

func (c *ChainInfos) IsPocChain() bool

func (*ChainInfos) IsRewardChain

func (c *ChainInfos) IsRewardChain() bool

func (*ChainInfos) Key

func (c *ChainInfos) Key() []byte

func (*ChainInfos) PubIsAdmin

func (c *ChainInfos) PubIsAdmin(pub []byte) bool

func (*ChainInfos) RemoveBootNode

func (c *ChainInfos) RemoveBootNode(node NodeID) bool

func (*ChainInfos) RemoveDataNode

func (c *ChainInfos) RemoveDataNode(node NodeID) bool

func (*ChainInfos) ReportTo

func (c *ChainInfos) ReportTo() ChainID

The target chain which the current chain reports to, It's not necessary consistent with ParentID

func (*ChainInfos) Sort

func (c *ChainInfos) Sort()

func (*ChainInfos) String

func (c *ChainInfos) String() string

type ChainInfosShouldBe

type ChainInfosShouldBe struct {
	ChainStruct
	ReportTo          ChainID      // Record the destination chain when this chain reports the Header (not necessarily the same as the parent chain, such as: child chain shards are reported to the main chain shard or main chain 0)
	Attributes        ChainAttrs   // Chain attributes (PoC/Reward/NoGas, etc.)
	LocalCurrencyID   CoinID       // ID of the local currency of this chain, 0 is the basic currency, indicating that the chain does not have a local currency
	LocalCurrencyName string       // If there is a local currency, it is the display name of the currency, otherwise it is ""
	AdminPubs         [][]byte     // Administrators' public key list
	GenesisCommIds    NodeIDs      // Members of the genesis committee (orderly, only the genesis chain has a genesis committee, and the first committees of other chains are elected through the creation process)
	BootNodes         []BootNode   // Entrance of the chain, no less than N (N=1)
	Election          ElectionType // The election type of chain consensus committee
	DataNodes         DataNodes    // Chain data node. There is no more genesis and non-genesis, but the number of data nodes should not be less than M (M=3). If there is no data node, it can be considered as a virtual chain
	Extra             string       // Extra information
}

type ChainMode

type ChainMode byte
const (
	// chain mode
	Root ChainMode = 0x10 + iota
	Branch
	Shard
	UnknownMode
)

func (ChainMode) String

func (m ChainMode) String() string

type ChainStruct

type ChainStruct struct {
	ID       ChainID   `json:"id"`
	ParentID ChainID   `json:"parentid"`
	Mode     ChainMode `json:"mode"`
}

TODO v1.5.0 The chain ID and the parent chain ID form a logical chain ID tree with chain

0 as the root.
1. main chain (chainid=0) as root of the tree,responsible for maintaining chain structure
   and generating global seed
2. shards of main chain:There may be a second layer. When the number of sub chains reaches
   a certain level, the main chain can also be partitioned. The parentid of each main chain
   shard is the main chain 0. These main chain shards are mainly responsible for receiving,
   verifying and packaging the block hashs reported by each sub chain (including sub chain
   shards).
3. sub chain:All the business chains which parentids are the main chain. If the sub chain
   is not partitioned, the chain is an entity chain, and it needs to report the block to
   the superior regularly (when the main chain is not partitioned: to main chain 0; when
   the main chain is partitioned: the calculated main chain shard according to the attribute
   setting of the shard). Because it is an entity chain, the transaction is performed on
   the chain.
4. shards of sub chain:When there are too many sub chain accounts or too many transactions,
   the sub chain can be divided into two shards (each shard can continue to be divided, which
   means that the users on the old shard are divided into new shards, and the parentid of
   all shards is same with each other: sub chain ID). When a sub chain is partitioned, the
   sub chain becomes a virtual chain. The virtual chain does not need consensus. All the
   shards only need the dataport in the bootnode of the sub chain to build the data network.
   All transactions take place on the corresponding shard. The parentid of the sharding chain
   is the subchain ID. The shard regularly reports the block information to the superior (the
   main chain, which is same as the subchain).

TODO v1.5.0 链ID及父链ID组成了一颗以0链为根的逻辑链ID树。

  1. 根为0号主链,负责维护链结构及全局Seed;

  2. 主链的分片:可能存在的第二层,当子链达到一定数量时主链也可以分片,每个主链分片的ParentID都是0号主链, 这些主链分片主要负责接收、验证及打包各子链(包括子链的分片)上报的块头。

  3. 子链:所有业务的链,ParentID为0号主链。如果子链没有分片,则此链为实体链,需要定期向上级(主链无分片 时:向0号主链,主链有分片时:根据主链分片的属性设定计算得到的主链分片)上报块头。因为是实体链,链上完成 相应交易。

  4. 子链的分片:当子链账户过多或交易过大时,子链可以分裂为2个分片(每个分片还可以继续分裂,分片分裂仅代表 其用户段被分割到新的分片中,所有分片的ParentID都是相同的:子链ID)。当一个子链有了分片,该子链就成为虚拟 链,该虚拟链无需共识,所有分片仅需要该子链BootNode中的DataPort来组建数据网络。所有交易都发生在对应的分 片上。分片链的ParentID为子链ID,定期向上级(主链)汇报块头信息(同子链)。

    Generation of shards (sketch): one existing chain A

  5. Create two new chains, A1 and A2, one shard account prefix Bit:0, one prefix Bit:1

  6. Stop chain A and make data unchangeable

  7. Copy the data of chain A to A1 and A2 (more simply, divide half of the data nodes of chain A to A1 and the other half to A2, but how to ensure that the operation of chain A is not affected? )

  8. Start elections for the committees of A1 and A2

  9. After the two chain elections are all successful, start A1 / A2

    分片的生成(初步想法):已存在的链A

  10. 新建2条链A1,A2,一个分片账户前缀Bit:0,一个账户前缀Bit:1

  11. 停A链,锁定数据

  12. 将链A数据复制给A1, A2(更简单一些,将链A的数据节点分一半给A1,另一半给A2,但是如何保证链A运行不受影响?)

  13. 选举A1,A2两条链的委员会

  14. 两条链选举全部成功后,启动A1/A2

func NewChainStruct

func NewChainStruct(id, parentId ChainID) (cs *ChainStruct, err error)

func (ChainStruct) Clone added in v1.3.6

func (s ChainStruct) Clone() ChainStruct

func (ChainStruct) String

func (s ChainStruct) String() string

func (ChainStruct) Validate

func (s ChainStruct) Validate() error

type Cipherer

type Cipherer interface {
	Priv() []byte
	Pub() []byte
}

key pair

type CoinID

type CoinID uint16 // ID of currency,TKM=0

func (CoinID) IsSovereign

func (c CoinID) IsSovereign() bool

return true if it is basic currency, false if it is other currencies (the local currency of each chain)

type CommID

type CommID int

func (CommID) ShouldPropose added in v1.3.30

func (i CommID) ShouldPropose(commSize int) int

should proposed blocks number in one epoch

func (CommID) String

func (i CommID) String() string

type DataNode

type DataNode struct {
	NodeID     NodeID // ID of node
	IsGenesis  bool   // Whether it is a genesis data node, it is only a flag
	RpcAddress string // The RPC address and port of the data node (in order to resist attacks, the address of the cluster application can be used to proxy a group of full nodes)
}

data node for chain

type DataNodes

type DataNodes []DataNode

sorted by(IsGenesis, NodeID)

func (DataNodes) Len

func (ds DataNodes) Len() int

func (DataNodes) Less

func (ds DataNodes) Less(i, j int) bool

func (DataNodes) Swap

func (ds DataNodes) Swap(i, j int)

type Dataserver

type Dataserver struct {
	ChainID        uint32 `yaml:"chainID" 		json:"chainID"`
	NodeIDString   string `yaml:"nodeID" 		json:"nodeID"`
	IP             string `yaml:"ip" 			json:"ip"`
	BasicPort      uint16 `yaml:"bNetPort" 		json:"bNetPort"`
	ConsensusPort0 uint16 `yaml:"cNetPort0" 	json:"cNetPort0"`
	ConsensusPort1 uint16 `yaml:"cNetPort1" 	json:"cNetPort1"`
	DataPort0      uint16 `yaml:"dNetPort0" 	json:"dNetPort0"`
	DataPort1      uint16 `yaml:"dNetPort1" 	json:"dNetPort1"`
	DataRpcPort    uint16 `yaml:"dataRpcPort" 	json:"dataRpcPort"`
}

func (*Dataserver) Clone

func (d *Dataserver) Clone() *Dataserver

func (Dataserver) Compare

func (d Dataserver) Compare(o Dataserver) int

func (Dataserver) GetNodeID

func (d Dataserver) GetNodeID() (*NodeID, error)

func (*Dataserver) GetRpcAddr

func (d *Dataserver) GetRpcAddr() string

func (*Dataserver) HashValue

func (d *Dataserver) HashValue() ([]byte, error)

func (Dataserver) String

func (d Dataserver) String() string

func (Dataserver) Validation

func (d Dataserver) Validation() error

type DvppError

type DvppError struct {
	Message  string
	Embedded error
}

func NewDvppError

func NewDvppError(msg string, embeded error) DvppError

func (DvppError) Error

func (e DvppError) Error() string

type ElectionType

type ElectionType byte

func StringToElectionType

func StringToElectionType(name string) (ElectionType, bool)

String to ElectionType, invalid string bool returns false

func (ElectionType) Exclusiveness

func (t ElectionType) Exclusiveness() bool

func (ElectionType) IsManaged

func (t ElectionType) IsManaged() bool

func (ElectionType) IsValid

func (t ElectionType) IsValid() bool

func (ElectionType) IsVrf

func (t ElectionType) IsVrf() bool

func (ElectionType) Name

func (t ElectionType) Name() string

Returns the name of an electiontype that is valid in the chain structure configuration

func (ElectionType) RewardNeeded

func (t ElectionType) RewardNeeded() bool

func (ElectionType) String

func (t ElectionType) String() string

type Endpoint

type Endpoint struct {
	NetType string `yaml:"net" json:"net"`
	Address string `yaml:"addr" json:"addr"`
}

func (Endpoint) IsNil

func (ep Endpoint) IsNil() bool

func (Endpoint) Network

func (ep Endpoint) Network() string

func (Endpoint) String

func (ep Endpoint) String() string

type EpochNum

type EpochNum uint64 // cycle for one committee consensus

func (EpochNum) Bytes

func (en EpochNum) Bytes() []byte

func (*EpochNum) Clone added in v1.3.30

func (en *EpochNum) Clone() *EpochNum

func (*EpochNum) Cmp added in v1.3.30

func (en *EpochNum) Cmp(o *EpochNum) int

func (EpochNum) Compare added in v1.3.26

func (en EpochNum) Compare(o EpochNum) int

func (EpochNum) Diff added in v1.3.26

func (en EpochNum) Diff(o EpochNum) (diff uint64, cmpRet int)

func (EpochNum) FirstHeight added in v1.3.29

func (en EpochNum) FirstHeight() Height

func (EpochNum) IsNil

func (en EpochNum) IsNil() bool

func (EpochNum) LastHeight added in v1.3.26

func (en EpochNum) LastHeight() Height

func (EpochNum) String

func (en EpochNum) String() string

func (*EpochNum) ToString added in v1.3.30

func (en *EpochNum) ToString() string

type EraNum

type EraNum uint64 // cycle for Required Reserve management

func (EraNum) Bytes

func (e EraNum) Bytes() []byte

func (*EraNum) Clone added in v1.3.26

func (e *EraNum) Clone() *EraNum

func (*EraNum) Cmp added in v1.3.26

func (e *EraNum) Cmp(o *EraNum) int

func (EraNum) Compare added in v1.3.26

func (e EraNum) Compare(o EraNum) int

func (*EraNum) Equal added in v1.3.26

func (e *EraNum) Equal(o *EraNum) bool

func (*EraNum) Hash added in v1.3.30

func (e *EraNum) Hash() Hash

func (EraNum) IsNil

func (e EraNum) IsNil() bool

func (*EraNum) Slice added in v1.6.2

func (e *EraNum) Slice() []byte

func (*EraNum) String

func (e *EraNum) String() string

func (*EraNum) Value

func (e *EraNum) Value() EraNum

type GasPool

type GasPool uint64

GasPool tracks the amount of gas available during execution of the transactions in a block. The zero value is a pool with zero gas available.

func (*GasPool) AddGas

func (gp *GasPool) AddGas(amount uint64) *GasPool

AddGas makes gas available for execution.

func (*GasPool) Gas

func (gp *GasPool) Gas() uint64

Gas returns the amount of gas remaining in the pool.

func (*GasPool) String

func (gp *GasPool) String() string

func (*GasPool) SubGas

func (gp *GasPool) SubGas(amount uint64) error

SubGas deducts the given amount from the pool if enough gas is available and returns an error otherwise.

type Hash

type Hash [HashLength]byte

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 BytesToHashP

func BytesToHashP(b []byte) *Hash

func CopyHashs

func CopyHashs(hs []Hash) []Hash

func EncodeHash

func EncodeHash(v interface{}) Hash

Call the HashObject method and turn the result into a hash object. If there is an error, all 0 Hash object will be returned

func Hash256

func Hash256(v ...[]byte) Hash

func Hash256WithError

func Hash256WithError(v ...[]byte) (Hash, error)

func Hash256p

func Hash256p(v ...[]byte) *Hash

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 NewHash

func NewHash(b []byte) *Hash

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

func (h *Hash) Clone() *Hash

func (*Hash) Equal added in v1.3.26

func (h *Hash) Equal(v *Hash) bool

func (*Hash) ForRLP added in v1.5.0

func (h *Hash) ForRLP() *Hash

func (*Hash) FromRLP added in v1.5.0

func (h *Hash) FromRLP() *Hash

func (Hash) Generate

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

Generate implements testing/quick.Generator.

func (Hash) HashValue

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

func (Hash) Hex

func (h Hash) Hex() string

Hex converts a hash to a hex string.

func (Hash) Invalid added in v1.3.26

func (h Hash) Invalid() bool

func (Hash) IsEmpty

func (h Hash) IsEmpty() bool

func (Hash) IsEmptyNode added in v1.3.26

func (h Hash) IsEmptyNode() bool

func (Hash) IsNil

func (h Hash) IsNil() bool

func (Hash) MarshalText

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

MarshalText returns the hex representation of h.

func (*Hash) PrintString

func (h *Hash) PrintString() string

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

func (h *Hash) Slice() []byte

func (*Hash) SliceEqual

func (h *Hash) SliceEqual(val []byte) bool

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

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

UnmarshalText parses a hash in hex syntax.

type HashItem added in v1.3.37

type HashItem struct {
	Val   Hash
	Order bool // true for Item.Val on the left side, false for right side
}

type HashProvider added in v1.6.0

type HashProvider interface {
	Hasher() hash.Hash
}
var SystemHashProvider HashProvider = systemHasher{}

type Hasher

type Hasher interface {
	HashValue() ([]byte, error)
}

Interface type that can calculate hash values

type Height

type Height uint64 // block height

func BytesToHeight

func BytesToHeight(bs []byte) Height

func ToHeight

func ToHeight(epoch EpochNum, bn BlockNum) Height

func (Height) BlockNum

func (h Height) BlockNum() BlockNum

func (Height) Bytes

func (h Height) Bytes() []byte

func (*Height) Clone added in v1.3.26

func (h *Height) Clone() *Height

func (Height) Compare

func (h Height) Compare(o Height) int

func (Height) Diff added in v1.3.26

func (h Height) Diff(o Height) (diff uint64, cmpRet int)

func (Height) EpochNum

func (h Height) EpochNum() EpochNum

func (*Height) Equal added in v1.3.6

func (h *Height) Equal(o *Height) bool

func (Height) EraNum

func (h Height) EraNum() EraNum

func (Height) FromBig added in v1.3.40

func (h Height) FromBig(bi *big.Int) (height Height, ok bool)

func (*Height) Hash added in v1.3.30

func (h *Height) Hash() Hash

func (Height) HashValue

func (h Height) HashValue() ([]byte, error)

func (Height) IsFirstOfEpoch added in v1.3.29

func (h Height) IsFirstOfEpoch() bool

func (Height) IsLastOfEpoch

func (h Height) IsLastOfEpoch() bool

Is it the last block in an epoch

func (Height) IsNil

func (h Height) IsNil() bool

func (Height) RemoveRemainder added in v1.3.26

func (h Height) RemoveRemainder(n Height) Height

func (*Height) Slice added in v1.6.2

func (h *Height) Slice() []byte

func (Height) Split

func (h Height) Split() (epochNum EpochNum, blockNum BlockNum)

func (*Height) String

func (h *Height) String() string

func (Height) UsefulBlock added in v1.3.8

func (h Height) UsefulBlock() BlockNum

func (Height) UsefulEpoch added in v1.3.7

func (h Height) UsefulEpoch() EpochNum

type Identifier

type Identifier interface {
	Cipherer
	Address() Address
	AddressP() *Address
}

account

type IndentLevel added in v1.3.6

type IndentLevel int

func (IndentLevel) DoubleByteSlice added in v1.3.40

func (l IndentLevel) DoubleByteSlice(slices [][]byte) string

func (IndentLevel) IndentString added in v1.3.6

func (l IndentLevel) IndentString() string

func (IndentLevel) InfoString added in v1.3.14

func (l IndentLevel) InfoString(o interface{}) string

type Infoer added in v1.3.14

type Infoer interface {
	InfoString(level IndentLevel) string
}

type LastBlockMap

type LastBlockMap struct {
	M map[ChainID]Height
	// contains filtered or unexported fields
}

func (*LastBlockMap) CAS

func (m *LastBlockMap) CAS(key ChainID, value Height) bool

When the value is greater than the currently saved value, replace it and return true. Otherwise, return false

func (*LastBlockMap) CopyMap

func (m *LastBlockMap) CopyMap() map[ChainID]Height

func (*LastBlockMap) Get

func (m *LastBlockMap) Get(key ChainID) (Height, bool)

func (*LastBlockMap) Set

func (m *LastBlockMap) Set(key ChainID, value Height)

type LruMap

type LruMap struct {
	Map *lru.Cache
}

func NewLruMap

func NewLruMap(size int) *LruMap

func (*LruMap) Add

func (m *LruMap) Add(key interface{}, value interface{}) bool

func (*LruMap) Clear

func (m *LruMap) Clear()

func (*LruMap) Contains

func (m *LruMap) Contains(key interface{}) bool

func (*LruMap) Get

func (m *LruMap) Get(key interface{}) interface{}

func (*LruMap) Remove

func (m *LruMap) Remove(key interface{})

type MerkleProofs

type MerkleProofs struct {
	// Use ToBeProof to calculate the Hash list of Hash with index starting from 0 in order
	Hashs []Hash `json:"hashs"`
	// Bit operands. The bit corresponding to the index of hashs indicates that the corresponding
	// hash value is placed left (1) or right (0) during hash operation, and the order is exactly
	// the binary value of the proved object
	Paths *big.Int `json:"paths"`
	// To save storage it is used to shrink consecutive identical hash values. Each MoreTime means
	// MerkleProofs.Hashs[MoreTime.Index] repeats MoreTime.Times times more than itself
	Repeats MoreTimes `json:"repeats"`
}

Since 16 bit counting is used in serialization, the maximum supported proof height cannot exceed 65535

func NewMerkleProofs

func NewMerkleProofs() *MerkleProofs

func (*MerkleProofs) Append

func (p *MerkleProofs) Append(h Hash, order bool)

h: a point on the proofing path order: Is this point on the left side (true) or the right side (false) of the proof path

func (*MerkleProofs) BigKey added in v1.3.19

func (p *MerkleProofs) BigKey(bigKey *big.Int, startAt int) int

func (*MerkleProofs) Clone

func (p *MerkleProofs) Clone() *MerkleProofs

func (*MerkleProofs) Deserialization

func (p *MerkleProofs) Deserialization(r io.Reader) (shouldBeNil bool, err error)

func (*MerkleProofs) Equal added in v1.3.26

func (p *MerkleProofs) Equal(o *MerkleProofs) bool

func (*MerkleProofs) Get

func (p *MerkleProofs) Get(fullIndex int) (h Hash, order bool, err error)

Gets the hash value corresponding with index (starting from 0) on the proof path and its order. If order is true, the hash value returned should be placed in the left, otherwise, right

func (*MerkleProofs) InfoString added in v1.3.19

func (p *MerkleProofs) InfoString(level IndentLevel) string

func (*MerkleProofs) Iterate added in v1.3.24

func (p *MerkleProofs) Iterate(hashCallback func(val []byte, order bool) error) error

func (*MerkleProofs) Len

func (p *MerkleProofs) Len() int

func (*MerkleProofs) Order

func (p *MerkleProofs) Order(i int) bool

Whether the corresponding hash value should be placed left (true) or right (false) when calculating the upper level hash

func (*MerkleProofs) Proof

func (p *MerkleProofs) Proof(toBeProof Hash) ([]byte, error)

According to the input, calculate the hash according to the proof, and return the result. If the proof is empty, the input is returned

func (*MerkleProofs) Serialization

func (p *MerkleProofs) Serialization(w io.Writer) error

p==nil: 1 byte (common.NilOrFalse)

p!=nil && len(p.Repeats)==0 1 byte (common.NotNilOrTrue) + binary.BigEndian.PutUint16(len(Hashs)) + Hashs[0] + ... + Hashs[len(Hashs)-1] + binary.BigEndian.PutUint16(len(Paths.Bytes())) + Paths.Bytes()

p!=nil && len(p.Repeats)>0 1 byte (common.Version0) + binary.BigEndian.PutUint16(len(Hashs)) + Hashs[0] + ... + Hashs[len(Hashs)-1] + binary.BigEndian.PutUint16(len(Paths.Bytes())) + Paths.Bytes() + binary.BigEndian.PutUint16(len(Repeats)) + binary.BigEndian.PutUint16(Repeats[0].Index) + binary.BigEndian.PutUint16(Repeats[0].Times) + ... + binary.BigEndian.PutUint16(Repeats[len(Repeats)-1].Index) + binary.BigEndian.PutUint16(Repeats[len(Repeats)-1].Times)

func (MerkleProofs) String

func (p MerkleProofs) String() string

func (*MerkleProofs) Summary added in v1.3.29

func (p *MerkleProofs) Summary() string

func (*MerkleProofs) ToItems added in v1.3.37

func (p *MerkleProofs) ToItems() ([]HashItem, error)

type MoreTime added in v1.3.37

type MoreTime struct {
	Index int `json:"i"`     // the index of MerkleProofs.Hashs
	Times int `json:"times"` // how many more times the Hash repeats (one time in Hashs not included)
}

func (MoreTime) Equal added in v1.3.37

func (m MoreTime) Equal(o MoreTime) bool

func (MoreTime) IsValid added in v1.3.37

func (m MoreTime) IsValid() bool

func (MoreTime) String added in v1.3.37

func (m MoreTime) String() string

type MoreTimes added in v1.3.37

type MoreTimes []MoreTime

func (MoreTimes) Append added in v1.3.37

func (ms MoreTimes) Append(index int) MoreTimes

func (MoreTimes) Clone added in v1.3.37

func (ms MoreTimes) Clone() MoreTimes

func (MoreTimes) Count added in v1.3.37

func (ms MoreTimes) Count() int

func (MoreTimes) Equal added in v1.3.37

func (ms MoreTimes) Equal(os MoreTimes) bool

func (MoreTimes) Find added in v1.3.37

func (ms MoreTimes) Find(index int) (times int, exist bool)

func (MoreTimes) GetHashsIndex added in v1.3.37

func (ms MoreTimes) GetHashsIndex(fullIndex int) int

get index of MerkleProofs.Hashs by the index of the expanded full hash list

func (MoreTimes) IsValid added in v1.3.37

func (ms MoreTimes) IsValid() bool

type NetInfo

type NetInfo struct {
	NodeID *NodeID // ID of node
	// contains filtered or unexported fields
}

func NewNetInfo

func NewNetInfo(id *NodeID, basicAddr, consensusAddr1 string, consensusAddr2 string, dataPort1, dataPort2 string) NetInfo

func (NetInfo) AddAddr

func (n NetInfo) AddAddr(ntype NetType, addr *Endpoint)

func (NetInfo) GetAddr

func (n NetInfo) GetAddr(ntype NetType) *Endpoint

type NetType

type NetType byte
const (
	// network type
	BasicNet NetType = iota
	ConsensusNet1
	ConsensusNet2
	RootDataNet   // Only in the main chain layer, including all data nodes of the main chain and its sub chains
	BranchDataNet // Only in the sub chain layer, including all data nodes of the sub chain and its shards

)

func ChooseConNetByEpoch

func ChooseConNetByEpoch(num EpochNum) NetType

func (NetType) String

func (n NetType) String() string

type NodeID

type NodeID [NodeIDBytes]byte

func BytesToNodeID

func BytesToNodeID(b []byte) NodeID

func BytesToNodeIDP added in v1.3.6

func BytesToNodeIDP(b []byte) *NodeID

func GenerateNodeID

func GenerateNodeID() *NodeID

func ParseBytesToNodeIds

func ParseBytesToNodeIds(s []byte) ([]NodeID, error)

func ParseNodeID

func ParseNodeID(nodeString string) (*NodeID, error)

func ParseNodeIDBytes

func ParseNodeIDBytes(nodeBytes []byte) (*NodeID, error)

func StringsToNodeIDs

func StringsToNodeIDs(strings []string) ([]NodeID, error)

func (*NodeID) Bytes

func (nid *NodeID) Bytes() []byte

func (*NodeID) Clone

func (nid *NodeID) Clone() *NodeID

func (*NodeID) Compare

func (nid *NodeID) Compare(to *NodeID) int

func (*NodeID) Generate

func (nid *NodeID) Generate() error

func (NodeID) Hash

func (nid NodeID) Hash() Hash

func (*NodeID) HashValue

func (nid *NodeID) HashValue() ([]byte, error)

compatible with Hash() method

func (NodeID) InfoString added in v1.3.20

func (nid NodeID) InfoString(_ IndentLevel) string

func (NodeID) MarshalText

func (nid NodeID) MarshalText() ([]byte, error)

func (NodeID) New

func (nid NodeID) New() *NodeID

func (*NodeID) SetBytes

func (nid *NodeID) SetBytes(b []byte)

func (NodeID) String

func (nid NodeID) String() string

func (*NodeID) UnmarshalText

func (nid *NodeID) UnmarshalText(input []byte) error

type NodeIDSet

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

func NewNodeIDSet

func NewNodeIDSet(ids ...*NodeID) *NodeIDSet

func (*NodeIDSet) Delete

func (ns *NodeIDSet) Delete(id *NodeID)

func (*NodeIDSet) Get

func (ns *NodeIDSet) Get(i int) (*NodeID, bool)

func (*NodeIDSet) GetIndex

func (ns *NodeIDSet) GetIndex(id *NodeID) (int, bool)

func (*NodeIDSet) GetNodeIDs

func (ns *NodeIDSet) GetNodeIDs(chainid ChainID) NodeIDs

func (*NodeIDSet) Len

func (ns *NodeIDSet) Len() int

func (*NodeIDSet) Less

func (ns *NodeIDSet) Less(i, j int) bool

func (*NodeIDSet) Put

func (ns *NodeIDSet) Put(id *NodeID) bool

func (*NodeIDSet) Swap

func (ns *NodeIDSet) Swap(i, j int)

type NodeIDs

type NodeIDs []NodeID

func ByteSlicesToNodeIDs

func ByteSlicesToNodeIDs(bss [][]byte) (NodeIDs, error)

func IdentifiersToNodeIDs

func IdentifiersToNodeIDs(nis []NodeIdentifier) NodeIDs

func (*NodeIDs) AppendByHex

func (ns *NodeIDs) AppendByHex(nidHex string) error

func (NodeIDs) Clone

func (ns NodeIDs) Clone() NodeIDs

func (NodeIDs) Contains

func (ns NodeIDs) Contains(nid NodeID) bool

func (NodeIDs) Equal added in v1.3.26

func (ns NodeIDs) Equal(os NodeIDs) bool

func (NodeIDs) InfoString added in v1.3.20

func (ns NodeIDs) InfoString(level IndentLevel) string

func (NodeIDs) IsIn

func (ns NodeIDs) IsIn(nid NodeID) bool

func (NodeIDs) Len

func (ns NodeIDs) Len() int

func (NodeIDs) Less

func (ns NodeIDs) Less(i, j int) bool

func (NodeIDs) Remove

func (ns NodeIDs) Remove(os NodeIDs) NodeIDs

func (NodeIDs) Swap

func (ns NodeIDs) Swap(i, j int)

func (NodeIDs) ToBytesSlice

func (ns NodeIDs) ToBytesSlice() [][]byte

func (NodeIDs) ToMap

func (ns NodeIDs) ToMap() map[NodeID]struct{}

func (NodeIDs) Union

func (ns NodeIDs) Union(os NodeIDs) NodeIDs

type NodeIdentifier

type NodeIdentifier interface {
	Cipherer
	NodeID() NodeID
	NodeIDP() *NodeID
}

node

type NodeType

type NodeType byte
const (
	Consensus    NodeType = 0
	Data         NodeType = 1
	Memo         NodeType = 2
	NoneNodeType NodeType = 0xFF
)

func (NodeType) String

func (n NodeType) String() string

type RoutinePool

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

func NewRoutinePool

func NewRoutinePool(name string, routineSize int, queueSize int, workFunc WorkerFunc, keyGetter func(interface{}) string) *RoutinePool

func (*RoutinePool) HigherLen added in v1.3.0

func (p *RoutinePool) HigherLen() int

returns the number of objects in the queue with higher priority

func (*RoutinePool) LowerLen added in v1.3.0

func (p *RoutinePool) LowerLen() int

returns the number of objects in the queue with lower priority

func (*RoutinePool) PostHigher

func (p *RoutinePool) PostHigher(v interface{})

func (*RoutinePool) PostLower

func (p *RoutinePool) PostLower(v interface{})

func (*RoutinePool) Start

func (p *RoutinePool) Start()

func (*RoutinePool) Stop

func (p *RoutinePool) Stop()

func (*RoutinePool) String added in v1.3.7

func (p *RoutinePool) String() string

type Seed

type Seed [SeedLength]byte

func BytesToSeed

func BytesToSeed(b []byte) Seed

func BytesToSeedP added in v1.3.46

func BytesToSeedP(b []byte) *Seed

func (*Seed) Byte

func (s *Seed) Byte() []byte

func (*Seed) Clone

func (s *Seed) Clone() *Seed

func (*Seed) Equal added in v1.3.46

func (s *Seed) Equal(o *Seed) bool

func (*Seed) Equals

func (s *Seed) Equals(v interface{}) bool

func (*Seed) Generate

func (s *Seed) Generate() error

func (*Seed) Hash added in v1.3.30

func (s *Seed) Hash() Hash

func (*Seed) IsZero

func (s *Seed) IsZero() bool

func (*Seed) SetBytes

func (s *Seed) SetBytes(b []byte) *Seed

func (*Seed) Slice added in v1.6.2

func (s *Seed) Slice() []byte

func (*Seed) String

func (s *Seed) String() string

type Service

type Service interface {
	String() string
	Init() error
	Start() error
	Close() error
}

type ServiceStateChanger

type ServiceStateChanger interface {
	Initializer() error
	Starter() error
	Closer() error
}

type ServiceStatus

type ServiceStatus byte
const (
	// state of system services
	SSCreated ServiceStatus = iota
	SSInitialized
	SSStarted
	SSStopped
)

func (*ServiceStatus) CheckInit

func (ss *ServiceStatus) CheckInit() error

func (*ServiceStatus) CheckStart

func (ss *ServiceStatus) CheckStart() error

func (*ServiceStatus) CheckStop

func (ss *ServiceStatus) CheckStop() error

type ShardInfo

type ShardInfo interface {
	GetMaskBits() uint           // How many digits are used to calculate the shard location
	LocalID() ChainID            // LocalID returns current chain/shard chainID
	AllIDs() []ChainID           // AllOthers returns all chainID besides local chainID
	ShardTo(interface{}) ChainID // ShardTo returns a shard chainID according to the parameter.
	Pos(id ChainID) int          // The index in the shard group of the incoming chainid
	Clone() ShardInfo
}

func NewShardInfo

func NewShardInfo(parent ChainStruct, currentChain ChainID, shards []ChainID) ShardInfo

type Version added in v1.3.15

type Version uint64

func NewNodeVersion added in v1.3.15

func NewNodeVersion(major, minor, patch uint64) (Version, error)

func (Version) Major added in v1.3.15

func (v Version) Major() uint64

func (Version) Minor added in v1.3.15

func (v Version) Minor() uint64

func (Version) Patch added in v1.3.15

func (v Version) Patch() uint64

func (Version) String added in v1.3.15

func (v Version) String() string

type WorkerFunc

type WorkerFunc func(workerName string, event interface{})

Directories

Path Synopsis
Package abi implements the Ethereum ABI (Application Binary Interface).
Package abi implements the Ethereum ABI (Application Binary Interface).
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.
rlp
Package rlp implements the RLP serialization format.
Package rlp implements the RLP serialization format.
internal/rlpstruct
Package rlpstruct implements struct processing for RLP encoding/decoding.
Package rlpstruct implements struct processing for RLP encoding/decoding.

Jump to

Keyboard shortcuts

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