types

package
v0.0.0-...-f47aca1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2020 License: Apache-2.0 Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxHeaderBytes 区块头的最大大小(包括了amino开销)
	MaxHeaderBytes int64 = 632

	// MaxAminoOverheadForBlock - maximum amino overhead to encode a block (up to
	// MaxBlockSizeBytes in size) not including it's parts except Data.
	// This means it also excludes the overhead for individual transactions.
	// To compute individual transactions' overhead use types.ComputeAminoOverhead(tx types.Tx, fieldNum int).
	//
	// Uvarint length of MaxBlockSizeBytes: 4 bytes
	// 2 fields (2 embedded):               2 bytes
	// Uvarint length of Data.Txs:          4 bytes
	// Data.Txs field:                      1 byte
	MaxAminoOverheadForBlock int64 = 11
)
View Source
const (
	// Block level events for mass consumption by users.
	// These events are triggered from the state package,
	// after a block has been committed.
	// These are also used by the tx indexer for async indexing.
	// All of this data can be fetched through the rpc.
	EventNewBlock            = "NewBlock"
	EventNewBlockHeader      = "NewBlockHeader"
	EventTx                  = "Tx"
	EventValidatorSetUpdates = "ValidatorSetUpdates"

	// Internal consensus events.
	// These are used for testing the consensus state machine.
	// They can also be used to build real-time consensus visualizers.
	EventCompleteProposal = "CompleteProposal"
	EventLock             = "Lock"
	EventNewRound         = "NewRound"
	EventNewRoundStep     = "NewRoundStep"
	EventPolka            = "Polka"
	EventRelock           = "Relock"
	EventTimeoutPropose   = "TimeoutPropose"
	EventTimeoutWait      = "TimeoutWait"
	EventUnlock           = "Unlock"
	EventValidBlock       = "ValidBlock"
	EventVote             = "Vote"
)

Reserved event types (alphabetically sorted).

View Source
const (
	// EventTypeKey is a reserved composite key for event name.
	EventTypeKey = "tm.event"
	// TxHashKey is a reserved key, used to specify transaction's hash.
	// see EventBus#PublishEventTx
	TxHashKey = "tx.hash"
	// TxHeightKey is a reserved key, used to specify transaction block's height.
	// see EventBus#PublishEventTx
	TxHeightKey = "tx.height"
)
View Source
const (
	// MaxBlockSizeBytes 区块的最大大小.
	MaxBlockSizeBytes = 104857600 // 100MB

	// BlockPartSizeBytes 是块部分的大小.
	BlockPartSizeBytes = 65536 // 64kB

	// MaxBlockPartsCount 一个区块最多有几部分.
	MaxBlockPartsCount = (MaxBlockSizeBytes / BlockPartSizeBytes) + 1

	MaxContractSizeBytes = 5242880 // 5MB
)
View Source
const (
	ABCIEvidenceTypeDuplicateVote = "duplicate/vote"
	ABCIEvidenceTypeMock          = "mock/evidence"
)
View Source
const (
	ABCIPubKeyTypeEd25519   = "ed25519"
	ABCIPubKeyTypeSr25519   = "sr25519"
	ABCIPubKeyTypeSecp256k1 = "secp256k1"
)
View Source
const (
	// MaxTotalVotingPower - 最大允许的总投票权.
	// 在所有情况下都必须足够小:
	// 1. 防止在IncrementProposerPriority()中裁剪
	// 2. 让(diff + diffMax-1)在IncrementProposerPriority()中不溢出
	// (Proof of 1 is tricky, left to the reader).
	// 它可能更高,但是对于我们的目的而言足够大,并且为防御目的留出了空间.
	MaxTotalVotingPower = int64(math.MaxInt64) / 8

	// PriorityWindowSizeFactor - 是一个常数,乘以总投票权可得出验证者优先级之间的最大允许距离。
	PriorityWindowSizeFactor = 2
)
View Source
const (
	// chainID的最大长度
	MaxChainIDLen = 50
)
View Source
const (
	// MaxEvidenceBytes 是一个证据的最大大小(其中包括amino负载)。
	MaxEvidenceBytes int64 = 484
)
View Source
const (
	MaxEvidenceBytesDenominator = 10
)
View Source
const (
	// MaxVoteBytes is a maximum vote size (including amino overhead).
	MaxVoteBytes int64 = 223
)
View Source
const (
	// MaxVotesCount 是集合中的最大投票数。在ValidateBasic函数中使用,以防御DOS攻击。
	// 请注意,这意味着对验证者数量的相应限制。
	MaxVotesCount = 10000
)
View Source
const TimeFormat = time.RFC3339Nano

TimeFormat is used for generating the sigs

Variables

View Source
var (
	EventQueryCompleteProposal    = QueryForEvent(EventCompleteProposal)
	EventQueryLock                = QueryForEvent(EventLock)
	EventQueryNewBlock            = QueryForEvent(EventNewBlock)
	EventQueryNewBlockHeader      = QueryForEvent(EventNewBlockHeader)
	EventQueryNewRound            = QueryForEvent(EventNewRound)
	EventQueryNewRoundStep        = QueryForEvent(EventNewRoundStep)
	EventQueryPolka               = QueryForEvent(EventPolka)
	EventQueryRelock              = QueryForEvent(EventRelock)
	EventQueryTimeoutPropose      = QueryForEvent(EventTimeoutPropose)
	EventQueryTimeoutWait         = QueryForEvent(EventTimeoutWait)
	EventQueryTx                  = QueryForEvent(EventTx)
	EventQueryUnlock              = QueryForEvent(EventUnlock)
	EventQueryValidatorSetUpdates = QueryForEvent(EventValidatorSetUpdates)
	EventQueryValidBlock          = QueryForEvent(EventValidBlock)
	EventQueryVote                = QueryForEvent(EventVote)
)
View Source
var (
	ErrPartSetUnexpectedIndex = errors.New("error part set unexpected index")
	ErrPartSetInvalidProof    = errors.New("error part set invalid proof")
)
View Source
var (
	ErrInvalidBlockPartSignature = errors.New("error invalid block part signature")
	ErrInvalidBlockPartHash      = errors.New("error invalid block part hash")
)
View Source
var (
	ErrVoteUnexpectedStep            = errors.New("unexpected step")
	ErrVoteInvalidValidatorIndex     = errors.New("invalid validator index")
	ErrVoteInvalidValidatorAddress   = errors.New("invalid validator address")
	ErrVoteInvalidSignature          = errors.New("invalid signature")
	ErrVoteInvalidBlockHash          = errors.New("invalid block hash")
	ErrVoteNonDeterministicSignature = errors.New("non-deterministic signature")
	ErrVoteNil                       = errors.New("nil vote")
)
View Source
var ErroringMockPVErr = errors.New("erroringMockPV always returns an error")
View Source
var (
	// MaxSignatureSize  Proposal和Vote中允许的签名最大大小.
	// XXX: secp256k1没有定义大小或最大大小.
	MaxSignatureSize = tmmath.MaxInt(ed25519.SignatureSize, 64)
)
View Source
var PB2TM = pb2tm{}

PB2TM is used for converting protobuf ABCI to Tendermint ABCI. UNSTABLE

View Source
var (
	PeerStateKey = "ConsensusReactor.peerState"
)

不稳定 啊这,就这???

View Source
var TM2PB = tm2pb{}

TM2PB is used for converting Tendermint ABCI to protobuf ABCI. UNSTABLE

Functions

func CanonicalTime

func CanonicalTime(t time.Time) string

CanonicalTime can be used to stringify time in a canonical way.

func ComputeAminoOverhead

func ComputeAminoOverhead(tx Tx, fieldNum int) int64

ComputeAminoOverhead calculates the overhead for amino encoding a transaction. The overhead consists of varint encoding the field number and the wire type (= length-delimited = 2), and another varint encoding the length of the transaction. The field number can be the field number of the particular transaction, or the field number of the parenting struct that contains the transactions []Tx as a field (this field number is repeated for each contained Tx). If some []Tx are encoded directly (without a parenting struct), the default fieldNum is also 1 (see BinFieldNum in amino.MarshalBinaryBare).

func EventQueryTxFor

func EventQueryTxFor(tx Tx) tmpubsub.Query

func EvidenceToProto

func EvidenceToProto(evidence Evidence) (*tmproto.Evidence, error)

func GetCodec

func GetCodec() *amino.Codec

GetCodec returns a codec used by the package. For testing purposes only.

func IsErrNotEnoughVotingPowerSigned

func IsErrNotEnoughVotingPowerSigned(err error) bool

IsErrNotEnoughVotingPowerSigned returns true if err is ErrNotEnoughVotingPowerSigned.

func IsVoteTypeValid

func IsVoteTypeValid(t SignedMsgType) bool

IsVoteTypeValid 如果是一个合法的投票类型,返回true

func MaxDataBytes

func MaxDataBytes(maxBytes int64, valsCount, evidenceCount int) int64

MaxDataBytes returns the maximum size of block's data.

XXX: Panics on negative result.

func MaxDataBytesUnknownEvidence

func MaxDataBytesUnknownEvidence(maxBytes int64, valsCount int) int64

MaxDataBytesUnknownEvidence returns the maximum size of block's data when evidence count is unknown. MaxEvidencePerBlock will be used for the size of evidence.

XXX: Panics on negative result.

func MaxEvidencePerBlock

func MaxEvidencePerBlock(blockMaxBytes int64) (int64, int64)

MaxEvidencePerBlock 返回证据最大占用空间和最多可以存放多少个证据。 TODO: change to a constant, or to a fraction of the validator set size. See https://github.com/wjbbig/candy/issues/2590

func QueryForEvent

func QueryForEvent(eventType string) tmpubsub.Query

func RandValidator

func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator)

RandValidator 随机生成一个验证者,仅用于测试。 UNSTABLE

func RandValidatorSet

func RandValidatorSet(numValidators int, votingPower int64) (*ValidatorSet, []PrivValidator)

RandValidatorSet returns a randomized validator set, useful for testing. NOTE: PrivValidator are in order. UNSTABLE

func RegisterBlockAmino

func RegisterBlockAmino(cdc *amino.Codec)

func RegisterEventDatas

func RegisterEventDatas(cdc *amino.Codec)

func RegisterEvidences

func RegisterEvidences(cdc *amino.Codec)

func RegisterMockEvidences

func RegisterMockEvidences(cdc *amino.Codec)

func RegisterMockEvidencesGlobal

func RegisterMockEvidencesGlobal()

For testing purposes only

func ValidateHash

func ValidateHash(h []byte) error

ValidateHash 如果哈希不为空,但是他的长度不等于tmhash.Size,返回错误

func ValidateTime

func ValidateTime(t time.Time) error

ValidateTime执行基本的时间验证,以确保时间不会漂移太多:+/- 一年。 TODO: reduce this to eg 1 day NOTE: DO NOT USE in ValidateBasic methods in this package. This function can only be used for real time validation, like on proposals and votes in the consensus. If consensus is stuck, and rounds increase for more than a day, having only a 1-day band here could break things... Can't use for validating blocks because we may be syncing years worth of history.

func ValidatorListString

func ValidatorListString(vals []*Validator) string

ValidatorListString returns a prettified validator list for logging purposes. ValidatorListString 返回一个美化的验证器列表以用于日志记录。

Types

type ABCIResult

type ABCIResult struct {
	Code uint32         `json:"code"`
	Data bytes.HexBytes `json:"data"`
}

ABCIResult 是ResponseDeliverTx的确定性组件. TODO: add tags and other fields https://github.com/wjbbig/candy/issues/1007

func NewResultFromResponse

func NewResultFromResponse(response *abci.ResponseDeliverTx) ABCIResult

NewResultFromResponse creates ABCIResult from ResponseDeliverTx.

func (ABCIResult) Bytes

func (a ABCIResult) Bytes() []byte

Bytes 返回使用amino编码的 ABCIResult

type ABCIResults

type ABCIResults []ABCIResult

ABCIResults wraps the deliver tx results to return a proof

func NewResults

func NewResults(responses []*abci.ResponseDeliverTx) ABCIResults

NewResults creates ABCIResults from the list of ResponseDeliverTx.

func (ABCIResults) Bytes

func (a ABCIResults) Bytes() []byte

Bytes serializes the ABCIResponse using amino

func (ABCIResults) Hash

func (a ABCIResults) Hash() []byte

Hash returns a merkle hash of all results

func (ABCIResults) ProveResult

func (a ABCIResults) ProveResult(i int) merkle.SimpleProof

ProveResult returns a merkle proof of one result from the set

type Address

type Address = crypto.Address

Address is hex bytes.

type Block

type Block struct {
	Header     `json:"header"`
	Data       `json:"data"`
	Evidence   EvidenceData `json:"evidence"`
	LastCommit *Commit      `json:"last_commit"`
	// contains filtered or unexported fields
}

Block defines the atomic unit of a Tendermint blockchain.

func MakeBlock

func MakeBlock(height int64, txs []Tx, lastCommit *Commit, evidence []Evidence) *Block

MakeBlock returns a new block with an empty header, except what can be computed from itself. It populates the same set of fields validated by ValidateBasic.

func (*Block) Hash

func (b *Block) Hash() tmbytes.HexBytes

Hash computes and returns the block hash. If the block is incomplete, block hash is nil for safety.

func (*Block) HashesTo

func (b *Block) HashesTo(hash []byte) bool

HashesTo is a convenience function that checks if a block hashes to the given argument. Returns false if the block is nil or the hash is empty.

func (*Block) MakePartSet

func (b *Block) MakePartSet(partSize int) *PartSet

MakePartSet returns a PartSet containing parts of a serialized block. This is the form in which the block is gossipped to peers. CONTRACT: partSize is greater than zero.

func (*Block) Marshal

func (b *Block) Marshal() ([]byte, error)

Marshal returns the amino encoding.

func (*Block) MarshalTo

func (b *Block) MarshalTo(data []byte) (int, error)

MarshalTo calls Marshal and copies to the given buffer.

func (*Block) Size

func (b *Block) Size() int

Size returns size of the block in bytes.

func (*Block) String

func (b *Block) String() string

String returns a string representation of the block

func (*Block) StringIndented

func (b *Block) StringIndented(indent string) string

StringIndented returns a string representation of the block

func (*Block) StringShort

func (b *Block) StringShort() string

StringShort returns a shortened string representation of the block

func (*Block) Unmarshal

func (b *Block) Unmarshal(bs []byte) error

Unmarshal deserializes from amino encoded form.

func (*Block) ValidateBasic

func (b *Block) ValidateBasic() error

ValidateBasic performs basic validation that doesn't involve state data. It checks the internal consistency of the block. Further validation is done using state#ValidateBlock.

type BlockEventPublisher

type BlockEventPublisher interface {
	PublishEventNewBlock(block EventDataNewBlock) error
	PublishEventNewBlockHeader(header EventDataNewBlockHeader) error
	PublishEventTx(EventDataTx) error
	PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates) error
}

BlockEventPublisher publishes all block related events

type BlockID

type BlockID struct {
	Hash        tmbytes.HexBytes `json:"hash"`
	PartsHeader PartSetHeader    `json:"parts"`
}

BlockID defines the unique ID of a block as its Hash and its PartSetHeader

func BlockIDFromProto

func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error)

FromProto protobuf类型转为普通类型 It returns an error if the block id is invalid.

func (BlockID) Equals

func (blockID BlockID) Equals(other BlockID) bool

Equals 用于blockID与blockID之间的比较

func (BlockID) IsComplete

func (blockID BlockID) IsComplete() bool

IsComplete 验证blockID是否符合要求

func (BlockID) IsZero

func (blockID BlockID) IsZero() bool

IsZero returns true if this is the BlockID of a nil block.

func (BlockID) Key

func (blockID BlockID) Key() string

Key 返回机器可读的blockID字符串

func (BlockID) String

func (blockID BlockID) String() string

String 返回人类可读的blockID字符串

func (*BlockID) ToProto

func (blockID *BlockID) ToProto() tmproto.BlockID

ToProto 转为protobuf类型

func (BlockID) ValidateBasic

func (blockID BlockID) ValidateBasic() error

ValidateBasic performs basic validation.

type BlockIDFlag

type BlockIDFlag byte

BlockIDFlag indicates which BlockID the signature is for.

const (
	// BlockIDFlagAbsent - 没有收到验证者的投票.
	BlockIDFlagAbsent BlockIDFlag = iota + 1
	// BlockIDFlagCommit - 对Commit.BlockID投票.
	BlockIDFlagCommit
	// BlockIDFlagNil - 对nil投票.
	BlockIDFlagNil
)

type BlockMeta

type BlockMeta struct {
	BlockID   BlockID `json:"block_id"`   // 区块ID
	BlockSize int     `json:"block_size"` // 区块大小
	Header    Header  `json:"header"`     // 区块头
	NumTxs    int     `json:"num_txs"`    // 交易数量
}

BlockMeta 包含了元数据.

func NewBlockMeta

func NewBlockMeta(block *Block, blockParts *PartSet) *BlockMeta

NewBlockMeta 返回一个BlockMeta.

func (*BlockMeta) Marshal

func (bm *BlockMeta) Marshal() ([]byte, error)

Marshal returns the amino encoding.

func (*BlockMeta) MarshalTo

func (bm *BlockMeta) MarshalTo(data []byte) (int, error)

MarshalTo calls Marshal and copies to the given buffer.

func (*BlockMeta) Size

func (bm *BlockMeta) Size() int

Size returns the size of the amino encoding, in bytes.

func (*BlockMeta) Unmarshal

func (bm *BlockMeta) Unmarshal(bs []byte) error

Unmarshal deserializes from amino encoded form.

func (*BlockMeta) ValidateBasic

func (bm *BlockMeta) ValidateBasic() error

ValidateBasic performs basic validation.

type BlockParams

type BlockParams struct {
	MaxBytes int64 `json:"max_bytes"`
	MaxGas   int64 `json:"max_gas"`
	// 连续块之间的最小时间增量 (in milliseconds)
	// Not exposed to the application.
	TimeIotaMs int64 `json:"time_iota_ms"`
}

BlockParams define limits on the block size and gas plus minimum time between blocks.

func DefaultBlockParams

func DefaultBlockParams() BlockParams

DefaultBlockParams 返回默认的 BlockParams.

type CanonicalBlockID

type CanonicalBlockID struct {
	Hash        bytes.HexBytes
	PartsHeader CanonicalPartSetHeader
}

func CanonicalizeBlockID

func CanonicalizeBlockID(blockID BlockID) CanonicalBlockID

type CanonicalPartSetHeader

type CanonicalPartSetHeader struct {
	Hash  bytes.HexBytes
	Total int
}

func CanonicalizePartSetHeader

func CanonicalizePartSetHeader(psh PartSetHeader) CanonicalPartSetHeader

type CanonicalProposal

type CanonicalProposal struct {
	Type      SignedMsgType // type alias for byte
	Height    int64         `binary:"fixed64"`
	Round     int64         `binary:"fixed64"`
	POLRound  int64         `binary:"fixed64"`
	BlockID   CanonicalBlockID
	Timestamp time.Time
	ChainID   string
}

func CanonicalizeProposal

func CanonicalizeProposal(chainID string, proposal *Proposal) CanonicalProposal

type CanonicalVote

type CanonicalVote struct {
	Type      SignedMsgType // type alias for byte
	Height    int64         `binary:"fixed64"`
	Round     int64         `binary:"fixed64"`
	BlockID   CanonicalBlockID
	Timestamp time.Time
	ChainID   string
}

func CanonicalizeVote

func CanonicalizeVote(chainID string, vote *Vote) CanonicalVote

type Commit

type Commit struct {
	// NOTE: The signatures are in order of address to preserve the bonded
	// ValidatorSet order.签名按照地址的顺序保存已绑定的ValidatorSet顺序。
	// Any peer with a block can gossip signatures by index with a peer without
	// recalculating the active ValidatorSet. 任何具有块的对等点都可以通过索引传递签名,而无需重新计算活动验证器集。
	Height     int64       `json:"height"`
	Round      int         `json:"round"`
	BlockID    BlockID     `json:"block_id"`
	Signatures []CommitSig `json:"signatures"`
	// contains filtered or unexported fields
}

Commit 包含了一个区块被一组验证者提交的证据。 注意: Commit 对于高度1是空的,但绝对不是nil的

func CommitFromProto

func CommitFromProto(cp *tmproto.Commit) (*Commit, error)

FromProto sets a protobuf Commit to the given pointer. It returns an error if the commit is invalid.

func MakeCommit

func MakeCommit(blockID BlockID, height int64, round int,
	voteSet *VoteSet, validators []PrivValidator, now time.Time) (*Commit, error)

func NewCommit

func NewCommit(height int64, round int, blockID BlockID, commitSigs []CommitSig) *Commit

NewCommit returns a new Commit.

func (*Commit) BitArray

func (commit *Commit) BitArray() *bits.BitArray

BitArray returns a BitArray of which validators voted for BlockID or nil in this commit. Implements VoteSetReader.

func (*Commit) GetByIndex

func (commit *Commit) GetByIndex(valIdx int) *Vote

GetByIndex returns the vote corresponding to a given validator index. Panics if `index >= commit.Size()`. Implements VoteSetReader.

func (*Commit) GetHeight

func (commit *Commit) GetHeight() int64

GetHeight returns height of the commit. Implements VoteSetReader.

func (*Commit) GetRound

func (commit *Commit) GetRound() int

GetRound returns height of the commit. Implements VoteSetReader.

func (*Commit) GetVote

func (commit *Commit) GetVote(valIdx int) *Vote

GetVote converts the CommitSig for the given valIdx to a Vote. Returns nil if the precommit at valIdx is nil. Panics if valIdx >= commit.Size().

func (*Commit) Hash

func (commit *Commit) Hash() tmbytes.HexBytes

Hash returns the hash of the commit

func (*Commit) IsCommit

func (commit *Commit) IsCommit() bool

IsCommit returns true if there is at least one signature. Implements VoteSetReader.

func (*Commit) Size

func (commit *Commit) Size() int

Size returns the number of signatures in the commit. Implements VoteSetReader.

func (*Commit) StringIndented

func (commit *Commit) StringIndented(indent string) string

StringIndented returns a string representation of the commit

func (*Commit) ToProto

func (commit *Commit) ToProto() *tmproto.Commit

ToProto converts Commit to protobuf

func (*Commit) Type

func (commit *Commit) Type() byte

Type returns the vote type of the commit, which is always VoteTypePrecommit Implements VoteSetReader.

func (*Commit) ValidateBasic

func (commit *Commit) ValidateBasic() error

ValidateBasic performs basic validation that doesn't involve state data. Does not actually check the cryptographic signatures.

func (*Commit) VoteSignBytes

func (commit *Commit) VoteSignBytes(chainID string, valIdx int) []byte

VoteSignBytes constructs the SignBytes for the given CommitSig. The only unique part of the SignBytes is the Timestamp - all other fields signed over are otherwise the same for all validators. Panics if valIdx >= commit.Size().

type CommitSig

type CommitSig struct {
	BlockIDFlag      BlockIDFlag `json:"block_id_flag"`
	ValidatorAddress Address     `json:"validator_address"`
	Timestamp        time.Time   `json:"timestamp"`
	Signature        []byte      `json:"signature"`
}

CommitSig 是提交投票中的一部分

func NewCommitSigAbsent

func NewCommitSigAbsent() CommitSig

NewCommitSigAbsent returns new CommitSig with BlockIDFlagAbsent. Other fields are all empty.

func NewCommitSigForBlock

func NewCommitSigForBlock(signature []byte, valAddr Address, ts time.Time) CommitSig

NewCommitSigForBlock returns new CommitSig with BlockIDFlagCommit.

func (CommitSig) Absent

func (cs CommitSig) Absent() bool

Absent returns true if CommitSig is absent.

func (CommitSig) BlockID

func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID

BlockID returns the Commit's BlockID if CommitSig indicates signing, otherwise - empty BlockID.

func (CommitSig) ForBlock

func (cs CommitSig) ForBlock() bool

ForBlock returns true if CommitSig is for the block.

func (*CommitSig) FromProto

func (cs *CommitSig) FromProto(csp tmproto.CommitSig) error

FromProto sets a protobuf CommitSig to the given pointer. It returns an error if the CommitSig is invalid.

func (CommitSig) String

func (cs CommitSig) String() string

func (*CommitSig) ToProto

func (cs *CommitSig) ToProto() *tmproto.CommitSig

Protobuf和CommitSig的互相转换 ToProto converts CommitSig to protobuf

func (CommitSig) ValidateBasic

func (cs CommitSig) ValidateBasic() error

ValidateBasic performs basic validation.

type ConsensusParams

type ConsensusParams struct {
	Block     BlockParams     `json:"block"`
	Evidence  EvidenceParams  `json:"evidence"`
	Validator ValidatorParams `json:"validator"`
}

ConsensusParams 包含决定区块是否有效的重要共识参数。

func DefaultConsensusParams

func DefaultConsensusParams() *ConsensusParams

DefaultConsensusParams 返回默认值的 ConsensusParams.

func (*ConsensusParams) Equals

func (params *ConsensusParams) Equals(params2 *ConsensusParams) bool

func (*ConsensusParams) Hash

func (params *ConsensusParams) Hash() []byte

Hash returns a hash of a subset of the parameters to store in the block header. Only the Block.MaxBytes and Block.MaxGas are included in the hash. This allows the ConsensusParams to evolve more without breaking the block protocol. No need for a Merkle tree here, just a small struct to hash.

func (ConsensusParams) Update

func (params ConsensusParams) Update(params2 *abci.ConsensusParams) ConsensusParams

Update returns a copy of the params with updates from the non-zero fields of p2. NOTE: note: must not modify the original

func (*ConsensusParams) Validate

func (params *ConsensusParams) Validate() error

Validate validates the ConsensusParams to ensure all values are within their allowed limits, and returns an error if they are not.

type Contract

type Contract struct {
	ID    string `json:"id"`
	Bytes []byte `json:"bytes"`
}

func FromProto

func FromProto(contract *tmproto.Contract) *Contract

func (*Contract) Hash

func (c *Contract) Hash() []byte

func (*Contract) String

func (c *Contract) String() string

func (*Contract) ToProto

func (c *Contract) ToProto() *tmproto.Contract

func (*Contract) ValidateBasic

func (c *Contract) ValidateBasic() error

type Data

type Data struct {

	// Txs that will be applied by state @ block.Height+1.
	// NOTE: not all txs here are valid.  We're just agreeing on the order first.
	// This means that block.AppHash does not include these txs.
	Txs Txs `json:"txs"`
	// contains filtered or unexported fields
}

Data contains the set of transactions included in the block

func (*Data) Hash

func (data *Data) Hash() tmbytes.HexBytes

Hash returns the hash of the data

func (*Data) StringIndented

func (data *Data) StringIndented(indent string) string

StringIndented returns a string representation of the transactions

type DuplicateVoteEvidence

type DuplicateVoteEvidence struct {
	PubKey crypto.PubKey
	VoteA  *Vote
	VoteB  *Vote
}

DuplicateVoteEvidence 包含了验证者重复签名的证据

func NewDuplicateVoteEvidence

func NewDuplicateVoteEvidence(pubkey crypto.PubKey, vote1 *Vote, vote2 *Vote) *DuplicateVoteEvidence

NewDuplicateVoteEvidence 创建DuplicateVoteEvidence,并赋予两个冲突的投票以正确的顺序。 如果其中一张票为零,则返回的证据也为零

func (*DuplicateVoteEvidence) Address

func (dve *DuplicateVoteEvidence) Address() []byte

Address returns the address of the validator.

func (*DuplicateVoteEvidence) Bytes

func (dve *DuplicateVoteEvidence) Bytes() []byte

Hash returns the hash of the evidence.

func (*DuplicateVoteEvidence) Equal

func (dve *DuplicateVoteEvidence) Equal(ev Evidence) bool

Equal checks if two pieces of evidence are equal.

func (*DuplicateVoteEvidence) Hash

func (dve *DuplicateVoteEvidence) Hash() []byte

Hash returns the hash of the evidence.

func (*DuplicateVoteEvidence) Height

func (dve *DuplicateVoteEvidence) Height() int64

Height returns the height this evidence refers to.

func (*DuplicateVoteEvidence) String

func (dve *DuplicateVoteEvidence) String() string

String returns a string representation of the evidence.

func (*DuplicateVoteEvidence) Time

func (dve *DuplicateVoteEvidence) Time() time.Time

Time return the time the evidence was created

func (*DuplicateVoteEvidence) ValidateBasic

func (dve *DuplicateVoteEvidence) ValidateBasic() error

ValidateBasic performs basic validation.

func (*DuplicateVoteEvidence) Verify

func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error

Verify returns an error if the two votes aren't conflicting. To be conflicting, they must be from the same validator, for the same H/R/S, but for different blocks.

type ErrEvidenceInvalid

type ErrEvidenceInvalid struct {
	Evidence   Evidence
	ErrorValue error
}

ErrEvidenceInvalid 封装证据,并指出如何出错或出错的原因。

func NewErrEvidenceInvalid

func NewErrEvidenceInvalid(ev Evidence, err error) *ErrEvidenceInvalid

NewErrEvidenceInvalid 使用给定的错误,创建一个ErrEvidenceInvalid

func (*ErrEvidenceInvalid) Error

func (err *ErrEvidenceInvalid) Error() string

Error 返回字符串.

type ErrEvidenceOverflow

type ErrEvidenceOverflow struct {
	MaxNum int64
	GotNum int64
}

ErrEvidenceOverflow 适用于区块中证据过多的情况.

func NewErrEvidenceOverflow

func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow

NewErrEvidenceOverflow 当got > max时,返回ErrEvidenceOverflow.

func (*ErrEvidenceOverflow) Error

func (err *ErrEvidenceOverflow) Error() string

Error 返回字符串.

type ErrInvalidCommitHeight

type ErrInvalidCommitHeight struct {
	Expected int64
	Actual   int64
}

ErrInvalidCommitHeight is returned when we encounter a commit with an unexpected height.

func NewErrInvalidCommitHeight

func NewErrInvalidCommitHeight(expected, actual int64) ErrInvalidCommitHeight

func (ErrInvalidCommitHeight) Error

func (e ErrInvalidCommitHeight) Error() string

type ErrInvalidCommitSignatures

type ErrInvalidCommitSignatures struct {
	Expected int
	Actual   int
}

ErrInvalidCommitSignatures is returned when we encounter a commit where the number of signatures doesn't match the number of validators.

func NewErrInvalidCommitSignatures

func NewErrInvalidCommitSignatures(expected, actual int) ErrInvalidCommitSignatures

func (ErrInvalidCommitSignatures) Error

type ErrNotEnoughVotingPowerSigned

type ErrNotEnoughVotingPowerSigned struct {
	Got    int64
	Needed int64
}

ErrNotEnoughVotingPowerSigned is returned when not enough validators signed a commit.

func (ErrNotEnoughVotingPowerSigned) Error

type ErrVoteConflictingVotes

type ErrVoteConflictingVotes struct {
	*DuplicateVoteEvidence
}

func NewConflictingVoteError

func NewConflictingVoteError(val *Validator, vote1, vote2 *Vote) *ErrVoteConflictingVotes

func (*ErrVoteConflictingVotes) Error

func (err *ErrVoteConflictingVotes) Error() string

type ErroringMockPV

type ErroringMockPV struct {
	MockPV
}

func NewErroringMockPV

func NewErroringMockPV() *ErroringMockPV

func (*ErroringMockPV) SignProposal

func (pv *ErroringMockPV) SignProposal(chainID string, proposal *Proposal) error

Implements PrivValidator.

func (*ErroringMockPV) SignVote

func (pv *ErroringMockPV) SignVote(chainID string, vote *Vote) error

Implements PrivValidator.

type EventBus

type EventBus struct {
	service.BaseService
	// contains filtered or unexported fields
}

EventBus是用于通过系统的所有事件的通用总线。所有呼叫均被代理到基础pubsub服务器。 必须使用EventBus发布所有事件,以确保数据类型正确。

func NewEventBus

func NewEventBus() *EventBus

NewEventBus 返回一个新的事件总线

func NewEventBusWithBufferCapacity

func NewEventBusWithBufferCapacity(cap int) *EventBus

NewEventBusWithBufferCapacity 使用给定的缓冲容量来生产事件总线.

func (*EventBus) NumClientSubscriptions

func (b *EventBus) NumClientSubscriptions(clientID string) int

func (*EventBus) NumClients

func (b *EventBus) NumClients() int

func (*EventBus) OnStart

func (b *EventBus) OnStart() error

func (*EventBus) OnStop

func (b *EventBus) OnStop()

func (*EventBus) Publish

func (b *EventBus) Publish(eventType string, eventData TMEventData) error

func (*EventBus) PublishEventCompleteProposal

func (b *EventBus) PublishEventCompleteProposal(data EventDataCompleteProposal) error

func (*EventBus) PublishEventLock

func (b *EventBus) PublishEventLock(data EventDataRoundState) error

func (*EventBus) PublishEventNewBlock

func (b *EventBus) PublishEventNewBlock(data EventDataNewBlock) error

func (*EventBus) PublishEventNewBlockHeader

func (b *EventBus) PublishEventNewBlockHeader(data EventDataNewBlockHeader) error

func (*EventBus) PublishEventNewRound

func (b *EventBus) PublishEventNewRound(data EventDataNewRound) error

func (*EventBus) PublishEventNewRoundStep

func (b *EventBus) PublishEventNewRoundStep(data EventDataRoundState) error

func (*EventBus) PublishEventPolka

func (b *EventBus) PublishEventPolka(data EventDataRoundState) error

func (*EventBus) PublishEventRelock

func (b *EventBus) PublishEventRelock(data EventDataRoundState) error

func (*EventBus) PublishEventTimeoutPropose

func (b *EventBus) PublishEventTimeoutPropose(data EventDataRoundState) error

func (*EventBus) PublishEventTimeoutWait

func (b *EventBus) PublishEventTimeoutWait(data EventDataRoundState) error

func (*EventBus) PublishEventTx

func (b *EventBus) PublishEventTx(data EventDataTx) error

PublishEventTx publishes tx event with events from Result. Note it will add predefined keys (EventTypeKey, TxHashKey). Existing events with the same keys will be overwritten.

func (*EventBus) PublishEventUnlock

func (b *EventBus) PublishEventUnlock(data EventDataRoundState) error

func (*EventBus) PublishEventValidBlock

func (b *EventBus) PublishEventValidBlock(data EventDataRoundState) error

func (*EventBus) PublishEventValidatorSetUpdates

func (b *EventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpdates) error

func (*EventBus) PublishEventVote

func (b *EventBus) PublishEventVote(data EventDataVote) error

func (*EventBus) SetLogger

func (b *EventBus) SetLogger(l log.Logger)

func (*EventBus) Subscribe

func (b *EventBus) Subscribe(
	ctx context.Context,
	subscriber string,
	query tmpubsub.Query,
	outCapacity ...int,
) (Subscription, error)

func (*EventBus) SubscribeUnbuffered

func (b *EventBus) SubscribeUnbuffered(
	ctx context.Context,
	subscriber string,
	query tmpubsub.Query,
) (Subscription, error)

此方法可用于本地共识浏览器和同步测试。请勿用于面向公众/不受信任的订阅!

func (*EventBus) Unsubscribe

func (b *EventBus) Unsubscribe(ctx context.Context, subscriber string, query tmpubsub.Query) error

func (*EventBus) UnsubscribeAll

func (b *EventBus) UnsubscribeAll(ctx context.Context, subscriber string) error

type EventBusSubscriber

type EventBusSubscriber interface {
	Subscribe(ctx context.Context, subscriber string, query tmpubsub.Query, outCapacity ...int) (Subscription, error)
	Unsubscribe(ctx context.Context, subscriber string, query tmpubsub.Query) error
	UnsubscribeAll(ctx context.Context, subscriber string) error

	NumClients() int
	NumClientSubscriptions(clientID string) int
}

type EventDataCompleteProposal

type EventDataCompleteProposal struct {
	Height int64  `json:"height"`
	Round  int    `json:"round"`
	Step   string `json:"step"`

	BlockID BlockID `json:"block_id"`
}

type EventDataNewBlock

type EventDataNewBlock struct {
	Block *Block `json:"block"`

	ResultBeginBlock abci.ResponseBeginBlock `json:"result_begin_block"`
	ResultEndBlock   abci.ResponseEndBlock   `json:"result_end_block"`
}

type EventDataNewBlockHeader

type EventDataNewBlockHeader struct {
	Header Header `json:"header"`

	NumTxs           int64                   `json:"num_txs"` // Number of txs in a block
	ResultBeginBlock abci.ResponseBeginBlock `json:"result_begin_block"`
	ResultEndBlock   abci.ResponseEndBlock   `json:"result_end_block"`
}

type EventDataNewRound

type EventDataNewRound struct {
	Height int64  `json:"height"`
	Round  int    `json:"round"`
	Step   string `json:"step"`

	Proposer ValidatorInfo `json:"proposer"`
}

type EventDataRoundState

type EventDataRoundState struct {
	Height int64  `json:"height"`
	Round  int    `json:"round"`
	Step   string `json:"step"`
}

NOTE: This goes into the replay WAL

type EventDataString

type EventDataString string

type EventDataTx

type EventDataTx struct {
	TxResult
}

All txs fire EventDataTx

type EventDataValidatorSetUpdates

type EventDataValidatorSetUpdates struct {
	ValidatorUpdates []*Validator `json:"validator_updates"`
}

type EventDataVote

type EventDataVote struct {
	Vote *Vote
}

type Evidence

type Evidence interface {
	Height() int64                                     // height of the equivocation
	Time() time.Time                                   // time of the equivocation
	Address() []byte                                   // address of the equivocating validator
	Bytes() []byte                                     // bytes which comprise the evidence
	Hash() []byte                                      // hash of the evidence
	Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
	Equal(Evidence) bool                               // check equality of evidence

	ValidateBasic() error
	String() string
}

Evidence 表示验证者的任何可证明的恶意活动

func EvidenceFromProto

func EvidenceFromProto(evidence *tmproto.Evidence) (Evidence, error)

type EvidenceData

type EvidenceData struct {
	Evidence EvidenceList `json:"evidence"`
	// contains filtered or unexported fields
}

EvidenceData contains any evidence of malicious wrong-doing by validators

func (*EvidenceData) Hash

func (data *EvidenceData) Hash() tmbytes.HexBytes

Hash returns the hash of the data.

func (*EvidenceData) StringIndented

func (data *EvidenceData) StringIndented(indent string) string

StringIndented returns a string representation of the evidence.

type EvidenceList

type EvidenceList []Evidence

EvidenceList is a list of Evidence. Evidences is not a word.

func (EvidenceList) Has

func (evl EvidenceList) Has(evidence Evidence) bool

Has returns true if the evidence is in the EvidenceList.

func (EvidenceList) Hash

func (evl EvidenceList) Hash() []byte

Hash returns the simple merkle root hash of the EvidenceList.

func (EvidenceList) String

func (evl EvidenceList) String() string

type EvidenceParams

type EvidenceParams struct {
	MaxAgeNumBlocks int64         `json:"max_age_num_blocks"` // only accept new evidence more recent than this
	MaxAgeDuration  time.Duration `json:"max_age_duration"`
}

EvidenceParams 决定我们如何处理不法行为的证据。

func DefaultEvidenceParams

func DefaultEvidenceParams() EvidenceParams

DefaultEvidenceParams Params returns a default EvidenceParams.

type GenesisDoc

type GenesisDoc struct {
	GenesisTime     time.Time          `json:"genesis_time"`
	ChainID         string             `json:"chain_id"`
	ConsensusParams *ConsensusParams   `json:"consensus_params,omitempty"`
	Validators      []GenesisValidator `json:"validators,omitempty"`
	AppHash         tmbytes.HexBytes   `json:"app_hash"`
	AppState        json.RawMessage    `json:"app_state,omitempty"`
}

GenesisDoc defines the initial conditions for a candy blockchain, in particular its validator set.

func GenesisDocFromFile

func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error)

GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc.

func GenesisDocFromJSON

func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error)

GenesisDocFromJSON unmarshalls JSON data into a GenesisDoc.

func (*GenesisDoc) SaveAs

func (genDoc *GenesisDoc) SaveAs(file string) error

SaveAs is a utility method for saving GenensisDoc as a JSON file.

func (*GenesisDoc) ValidateAndComplete

func (genDoc *GenesisDoc) ValidateAndComplete() error

ValidateAndComplete checks that all necessary fields are present and fills in defaults for optional fields left empty

func (*GenesisDoc) ValidatorHash

func (genDoc *GenesisDoc) ValidatorHash() []byte

ValidatorHash returns the hash of the validator set contained in the GenesisDoc

type GenesisValidator

type GenesisValidator struct {
	Address Address       `json:"address"`
	PubKey  crypto.PubKey `json:"pub_key"`
	Power   int64         `json:"power"`
	Name    string        `json:"name"`
}

GenesisValidator is an initial validator.

type HashedParams

type HashedParams struct {
	BlockMaxBytes int64
	BlockMaxGas   int64
}

HashedParams 是 ConsensusParams 的子集. 它使用amino编码并放入 Header.ConsensusHash.

type Header struct {
	// 区块基本信息
	Version version.Consensus `json:"version"`
	ChainID string            `json:"chain_id"`
	Height  int64             `json:"height"`
	Time    time.Time         `json:"time"`

	// 上一个区块的信息
	LastBlockID BlockID `json:"last_block_id"`

	// 区块数据的哈希
	LastCommitHash tmbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
	DataHash       tmbytes.HexBytes `json:"data_hash"`        // 交易哈希

	// hashes from the app output from the prev block
	ValidatorsHash     tmbytes.HexBytes `json:"validators_hash"`      // validators for the current block
	NextValidatorsHash tmbytes.HexBytes `json:"next_validators_hash"` // validators for the next block
	ConsensusHash      tmbytes.HexBytes `json:"consensus_hash"`       // consensus params for current block
	AppHash            tmbytes.HexBytes `json:"app_hash"`             // state after txs from the previous block
	// root hash of all results from the txs from the previous block
	LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`

	// 共识信息
	EvidenceHash    tmbytes.HexBytes `json:"evidence_hash"`    // 包含在区块中的证据哈希
	ProposerAddress Address          `json:"proposer_address"` // 区块提出者的地址
}

Header 定义了Tendermint区块的头结构。 NOTE: changes to the Header should be duplicated in: - header.Hash() - abci.Header - https://github.com/tendermint/spec/blob/master/spec/blockchain/blockchain.md

func HeaderFromProto

func HeaderFromProto(ph *tmproto.Header) (Header, error)

HeaderFromProto sets a protobuf Header to the given pointer. It returns an error if the header is invalid.

func (*Header) Hash

func (h *Header) Hash() tmbytes.HexBytes

Hash 返回区块头哈希. It computes a Merkle tree from the header fields ordered as they appear in the Header. Returns nil if ValidatorHash is missing, since a Header is not valid unless there is a ValidatorsHash (corresponding to the validator set).

func (*Header) Populate

func (h *Header) Populate(
	version version.Consensus, chainID string,
	timestamp time.Time, lastBlockID BlockID,
	valHash, nextValHash []byte,
	consensusHash, appHash, lastResultsHash []byte,
	proposerAddress Address,
)

Populate 用状态导出的数据来填充区块头。 在MakeBlock之后调用这个方法来填充区块头。

func (*Header) StringIndented

func (h *Header) StringIndented(indent string) string

StringIndented returns a string representation of the header

func (*Header) ToProto

func (h *Header) ToProto() *tmproto.Header

ToProto 将Header转为protobuf

func (Header) ValidateBasic

func (h Header) ValidateBasic() error

ValidateBasic 验证区块头,返回错误 NOTE: 时间戳不在这里验证

type MockEvidence

type MockEvidence struct {
	EvidenceHeight  int64
	EvidenceTime    time.Time
	EvidenceAddress []byte
}

UNSTABLE

func NewMockEvidence

func NewMockEvidence(height int64, eTime time.Time, idx int, address []byte) MockEvidence

UNSTABLE

func (MockEvidence) Address

func (e MockEvidence) Address() []byte

func (MockEvidence) Bytes

func (e MockEvidence) Bytes() []byte

func (MockEvidence) Equal

func (e MockEvidence) Equal(ev Evidence) bool

func (MockEvidence) Hash

func (e MockEvidence) Hash() []byte

func (MockEvidence) Height

func (e MockEvidence) Height() int64

func (MockEvidence) String

func (e MockEvidence) String() string

func (MockEvidence) Time

func (e MockEvidence) Time() time.Time

func (MockEvidence) ValidateBasic

func (e MockEvidence) ValidateBasic() error

func (MockEvidence) Verify

func (e MockEvidence) Verify(chainID string, pubKey crypto.PubKey) error

type MockPV

type MockPV struct {
	PrivKey crypto.PrivKey
	// contains filtered or unexported fields
}

MockPV implements PrivValidator without any safety or persistence. Only use it for testing.

func NewMockPV

func NewMockPV() MockPV

func NewMockPVWithParams

func NewMockPVWithParams(privKey crypto.PrivKey, breakProposalSigning, breakVoteSigning bool) MockPV

NewMockPVWithParams allows one to create a MockPV instance, but with finer grained control over the operation of the mock validator. This is useful for mocking test failures.

func (MockPV) DisableChecks

func (pv MockPV) DisableChecks()

XXX: Implement.

func (MockPV) GetPubKey

func (pv MockPV) GetPubKey() (crypto.PubKey, error)

Implements PrivValidator.

func (MockPV) SignProposal

func (pv MockPV) SignProposal(chainID string, proposal *Proposal) error

Implements PrivValidator.

func (MockPV) SignVote

func (pv MockPV) SignVote(chainID string, vote *Vote) error

Implements PrivValidator.

func (MockPV) String

func (pv MockPV) String() string

String returns a string representation of the MockPV.

type MockRandomEvidence

type MockRandomEvidence struct {
	MockEvidence
	// contains filtered or unexported fields
}

UNSTABLE

func NewMockRandomEvidence

func NewMockRandomEvidence(height int64, eTime time.Time, address []byte, randBytes []byte) MockRandomEvidence

UNSTABLE

func (MockRandomEvidence) Hash

func (e MockRandomEvidence) Hash() []byte

type NopEventBus

type NopEventBus struct{}

-----------------------------------------------------------------------------

func (NopEventBus) PublishEventCompleteProposal

func (NopEventBus) PublishEventCompleteProposal(data EventDataRoundState) error

func (NopEventBus) PublishEventLock

func (NopEventBus) PublishEventLock(data EventDataRoundState) error

func (NopEventBus) PublishEventNewBlock

func (NopEventBus) PublishEventNewBlock(data EventDataNewBlock) error

func (NopEventBus) PublishEventNewBlockHeader

func (NopEventBus) PublishEventNewBlockHeader(data EventDataNewBlockHeader) error

func (NopEventBus) PublishEventNewRound

func (NopEventBus) PublishEventNewRound(data EventDataRoundState) error

func (NopEventBus) PublishEventNewRoundStep

func (NopEventBus) PublishEventNewRoundStep(data EventDataRoundState) error

func (NopEventBus) PublishEventPolka

func (NopEventBus) PublishEventPolka(data EventDataRoundState) error

func (NopEventBus) PublishEventRelock

func (NopEventBus) PublishEventRelock(data EventDataRoundState) error

func (NopEventBus) PublishEventTimeoutPropose

func (NopEventBus) PublishEventTimeoutPropose(data EventDataRoundState) error

func (NopEventBus) PublishEventTimeoutWait

func (NopEventBus) PublishEventTimeoutWait(data EventDataRoundState) error

func (NopEventBus) PublishEventTx

func (NopEventBus) PublishEventTx(data EventDataTx) error

func (NopEventBus) PublishEventUnlock

func (NopEventBus) PublishEventUnlock(data EventDataRoundState) error

func (NopEventBus) PublishEventValidatorSetUpdates

func (NopEventBus) PublishEventValidatorSetUpdates(data EventDataValidatorSetUpdates) error

func (NopEventBus) PublishEventVote

func (NopEventBus) PublishEventVote(data EventDataVote) error

func (NopEventBus) Subscribe

func (NopEventBus) Subscribe(
	ctx context.Context,
	subscriber string,
	query tmpubsub.Query,
	out chan<- interface{},
) error

func (NopEventBus) Unsubscribe

func (NopEventBus) Unsubscribe(ctx context.Context, subscriber string, query tmpubsub.Query) error

func (NopEventBus) UnsubscribeAll

func (NopEventBus) UnsubscribeAll(ctx context.Context, subscriber string) error

type P2PID

type P2PID string

UNSTABLE XXX: duplicate of p2p.ID to avoid dependence between packages. Perhaps we can have a minimal types package containing this (and other things?) that both `types` and `p2p` import ?

type Part

type Part struct {
	Index int                `json:"index"`
	Bytes tmbytes.HexBytes   `json:"bytes"`
	Proof merkle.SimpleProof `json:"proof"`
}

func (*Part) String

func (part *Part) String() string

字符串化

func (*Part) StringIndented

func (part *Part) StringIndented(indent string) string

func (*Part) ValidateBasic

func (part *Part) ValidateBasic() error

ValidateBasic 执行基础验证。

type PartSet

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

func NewPartSetFromData

func NewPartSetFromData(data []byte, partSize int) *PartSet

从data数据中获取一个不变的,完整的PartSet。 The data bytes are split into "partSize" chunks, and merkle tree computed.

func NewPartSetFromHeader

func NewPartSetFromHeader(header PartSetHeader) *PartSet

Returns an empty PartSet ready to be populated.

func (*PartSet) AddPart

func (ps *PartSet) AddPart(part *Part) (bool, error)

func (*PartSet) BitArray

func (ps *PartSet) BitArray() *bits.BitArray

func (*PartSet) Count

func (ps *PartSet) Count() int

func (*PartSet) GetPart

func (ps *PartSet) GetPart(index int) *Part

func (*PartSet) GetReader

func (ps *PartSet) GetReader() io.Reader

func (*PartSet) HasHeader

func (ps *PartSet) HasHeader(header PartSetHeader) bool

func (*PartSet) Hash

func (ps *PartSet) Hash() []byte

func (*PartSet) HashesTo

func (ps *PartSet) HashesTo(hash []byte) bool

func (*PartSet) Header

func (ps *PartSet) Header() PartSetHeader

func (*PartSet) IsComplete

func (ps *PartSet) IsComplete() bool

func (*PartSet) MarshalJSON

func (ps *PartSet) MarshalJSON() ([]byte, error)

func (*PartSet) StringShort

func (ps *PartSet) StringShort() string

func (*PartSet) Total

func (ps *PartSet) Total() int

type PartSetHeader

type PartSetHeader struct {
	Total int              `json:"total"`
	Hash  tmbytes.HexBytes `json:"hash"`
}

func PartSetHeaderFromProto

func PartSetHeaderFromProto(ppsh *tmproto.PartSetHeader) (*PartSetHeader, error)

FromProto protobuf 转 PartSetHeader

func (PartSetHeader) Equals

func (psh PartSetHeader) Equals(other PartSetHeader) bool

func (PartSetHeader) IsZero

func (psh PartSetHeader) IsZero() bool

func (PartSetHeader) String

func (psh PartSetHeader) String() string

func (*PartSetHeader) ToProto

func (psh *PartSetHeader) ToProto() tmproto.PartSetHeader

ToProto 转换BlockPartSetHeaderID为protobuf

func (PartSetHeader) ValidateBasic

func (psh PartSetHeader) ValidateBasic() error

ValidateBasic 执行基础验证。

type PartSetReader

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

func NewPartSetReader

func NewPartSetReader(parts []*Part) *PartSetReader

func (*PartSetReader) Read

func (psr *PartSetReader) Read(p []byte) (n int, err error)

type PrivValidator

type PrivValidator interface {
	GetPubKey() (crypto.PubKey, error)

	SignVote(chainID string, vote *Vote) error
	SignProposal(chainID string, proposal *Proposal) error
}

PrivValidator defines the functionality of a local Tendermint validator that signs votes and proposals, and never double signs.

type PrivValidatorsByAddress

type PrivValidatorsByAddress []PrivValidator

func (PrivValidatorsByAddress) Len

func (pvs PrivValidatorsByAddress) Len() int

func (PrivValidatorsByAddress) Less

func (pvs PrivValidatorsByAddress) Less(i, j int) bool

func (PrivValidatorsByAddress) Swap

func (pvs PrivValidatorsByAddress) Swap(i, j int)

type Proposal

type Proposal struct {
	Type      SignedMsgType
	Height    int64     `json:"height"`
	Round     int       `json:"round"`
	POLRound  int       `json:"pol_round"` // -1 if null.
	BlockID   BlockID   `json:"block_id"`
	Timestamp time.Time `json:"timestamp"`
	Signature []byte    `json:"signature"`
}

Proposal defines a block proposal for the consensus. It refers to the block by BlockID field. It must be signed by the correct proposer for the given Height/Round to be considered valid. It may depend on votes from a previous round, a so-called Proof-of-Lock (POL) round, as noted in the POLRound. If POLRound >= 0, then BlockID corresponds to the block that is locked in POLRound. Proposal 定义了一个共识的区块proposal。它使用字段BlockID来指向区块。

func NewProposal

func NewProposal(height int64, round int, polRound int, blockID BlockID) *Proposal

NewProposal returns a new Proposal. If there is no POLRound, polRound should be -1.

func ProposalFromProto

func ProposalFromProto(pp *tmproto.Proposal) (*Proposal, error)

FromProto sets a protobuf Proposal to the given pointer. It returns an error if the proposal is invalid.

func (*Proposal) SignBytes

func (p *Proposal) SignBytes(chainID string) []byte

SignBytes returns the Proposal bytes for signing

func (*Proposal) String

func (p *Proposal) String() string

String returns a string representation of the Proposal.

func (*Proposal) ToProto

func (p *Proposal) ToProto() *tmproto.Proposal

ToProto converts Proposal to protobuf

func (*Proposal) ValidateBasic

func (p *Proposal) ValidateBasic() error

ValidateBasic performs basic validation.

type Signable

type Signable interface {
	SignBytes(chainID string) []byte
}

Signable is an interface for all signable things. It typically removes signatures before serializing. SignBytes returns the bytes to be signed NOTE: chainIDs are part of the SignBytes but not necessarily the object themselves. NOTE: Expected to panic if there is an error marshalling.

type SignedHeader

type SignedHeader struct {
	*Header `json:"header"`

	Commit *Commit `json:"commit"`
}

SignedHeader is a header along with the commits that prove it. It is the basis of the lite client.

func SignedHeaderFromProto

func SignedHeaderFromProto(shp *tmproto.SignedHeader) (*SignedHeader, error)

FromProto sets a protobuf SignedHeader to the given pointer. It returns an error if the hader or the commit is invalid.

func (SignedHeader) String

func (sh SignedHeader) String() string

func (SignedHeader) StringIndented

func (sh SignedHeader) StringIndented(indent string) string

StringIndented returns a string representation of the SignedHeader.

func (*SignedHeader) ToProto

func (sh *SignedHeader) ToProto() *tmproto.SignedHeader

ToProto converts SignedHeader to protobuf

func (SignedHeader) ValidateBasic

func (sh SignedHeader) ValidateBasic(chainID string) error

ValidateBasic does basic consistency checks and makes sure the header and commit are consistent. NOTE: This does not actually check the cryptographic signatures. Make sure to use a Verifier to validate the signatures actually provide a significantly strong proof for this header's validity.

type SignedMsgType

type SignedMsgType byte

SignedMsgType is a type of signed message in the consensus.

const (
	// Votes
	PrevoteType   SignedMsgType = 0x01
	PrecommitType SignedMsgType = 0x02

	// Proposals
	ProposalType SignedMsgType = 0x20
)

type Subscription

type Subscription interface {
	Out() <-chan tmpubsub.Message
	Cancelled() <-chan struct{}
	Err() error
}

type TMEventData

type TMEventData interface {
}

TMEventData implements events.EventData.

type Tx

type Tx []byte

Tx is an arbitrary byte array. NOTE: Tx has no types at this level, so when wire encoded it's just length-prefixed. Might we want types here ?

func (Tx) Hash

func (tx Tx) Hash() []byte

Hash computes the TMHASH hash of the wire encoded transaction.

func (Tx) String

func (tx Tx) String() string

String returns the hex-encoded transaction as a string.

type TxEventPublisher

type TxEventPublisher interface {
	PublishEventTx(EventDataTx) error
}

type TxProof

type TxProof struct {
	RootHash tmbytes.HexBytes   `json:"root_hash"`
	Data     Tx                 `json:"data"`
	Proof    merkle.SimpleProof `json:"proof"`
}

TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree.

func (TxProof) Leaf

func (tp TxProof) Leaf() []byte

Leaf returns the hash(tx), which is the leaf in the merkle tree which this proof refers to.

func (TxProof) Validate

func (tp TxProof) Validate(dataHash []byte) error

Validate verifies the proof. It returns nil if the RootHash matches the dataHash argument, and if the proof is internally consistent. Otherwise, it returns a sensible error.

type TxResult

type TxResult struct {
	Height int64                  `json:"height"`
	Index  uint32                 `json:"index"`
	Tx     Tx                     `json:"tx"`
	Result abci.ResponseDeliverTx `json:"result"`
}

TxResult contains results of executing the transaction.

One usage is indexing transaction results.

type Txs

type Txs []Tx

Txs is a slice of Tx.

func (Txs) Hash

func (txs Txs) Hash() []byte

Hash returns the Merkle root hash of the transaction hashes. i.e. the leaves of the tree are the hashes of the txs.

func (Txs) Index

func (txs Txs) Index(tx Tx) int

Index returns the index of this transaction in the list, or -1 if not found

func (Txs) IndexByHash

func (txs Txs) IndexByHash(hash []byte) int

IndexByHash returns the index of this transaction hash in the list, or -1 if not found

func (Txs) Proof

func (txs Txs) Proof(i int) TxProof

Proof returns a simple merkle proof for this node. Panics if i < 0 or i >= len(txs) TODO: optimize this!

type Validator

type Validator struct {
	Address     Address       `json:"address"`
	PubKey      crypto.PubKey `json:"pub_key"`
	VotingPower int64         `json:"voting_power"`

	ProposerPriority int64 `json:"proposer_priority"`
}

Volatile state for each Validator NOTE: The ProposerPriority is not included in Validator.Hash(); make sure to update that method if changes are made here

func NewValidator

func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator

func ValidatorFromProto

func ValidatorFromProto(vp *tmproto.Validator) (*Validator, error)

FromProto 将protobuf类型validator转为普通类型. 如果公钥不合法,将返回错误。

func (*Validator) Bytes

func (v *Validator) Bytes() []byte

Bytes 以给定的投票权计算出每个验证器唯一的编码。这些字节在共识中被哈希。它排除了地址, 因为这与公钥是冗余的,也排除了ProposerPriority,因为这个值在每一轮共识中都会变化。

func (*Validator) CompareProposerPriority

func (v *Validator) CompareProposerPriority(other *Validator) *Validator

返回一个拥有更高的ProposerPriority的验证器.

func (*Validator) Copy

func (v *Validator) Copy() *Validator

创建验证器的新副本,以便我们可以更改ProposerPriority。 如果验证器为空,报错

func (*Validator) String

func (v *Validator) String() string

func (*Validator) ToProto

func (v *Validator) ToProto() (*tmproto.Validator, error)

ToProto 转换validator为protobuf

type ValidatorInfo

type ValidatorInfo struct {
	Address Address `json:"address"`
	Index   int     `json:"index"`
}

type ValidatorParams

type ValidatorParams struct {
	PubKeyTypes []string `json:"pub_key_types"`
}

ValidatorParams 限制验证者可以使用的公钥类型. NOTE: uses ABCI pubkey naming, not Amino names.

func DefaultValidatorParams

func DefaultValidatorParams() ValidatorParams

DefaultValidatorParams returns a default ValidatorParams, which allows only ed25519 pubkeys.

func (*ValidatorParams) IsValidPubkeyType

func (params *ValidatorParams) IsValidPubkeyType(pubkeyType string) bool

type ValidatorSet

type ValidatorSet struct {
	// NOTE: persisted via reflect, must be exported.
	Validators []*Validator `json:"validators"`
	Proposer   *Validator   `json:"proposer"`
	// contains filtered or unexported fields
}

ValidatorSet 代表给定高度的一组*Validator。 验证器可以通过地址或索引获取。 索引按.Address顺序,因此对于给定区块链高度的所有回合,索引都是固定的。 即,验证者使用它们的地址排序。 另一方面,在调用 IncrementProposerPriority()时, 每个验证器的 ProposerPriority和集合中指定的 GetProposer()都会每轮更改。 NOTE: Not goroutine-safe. NOTE: All get/set to validators should copy the value for safety.

func NewValidatorSet

func NewValidatorSet(valz []*Validator) *ValidatorSet

NewValidatorSet initializes a ValidatorSet by copying over the values from `valz`, a list of Validators. If valz is nil or empty, the new ValidatorSet will have an empty list of Validators. The addresses of validators in `valz` must be unique otherwise the function panics. Note the validator set size has an implied limit equal to that of the MaxVotesCount - commits by a validator set larger than this will fail validation.

func ValidatorSetFromProto

func ValidatorSetFromProto(vp *tmproto.ValidatorSet) (*ValidatorSet, error)

ValidatorSetFromProto sets a protobuf ValidatorSet to the given pointer. It returns an error if any of the validators from the set or the proposer is invalid

func (*ValidatorSet) Copy

func (vals *ValidatorSet) Copy() *ValidatorSet

Copy each validator into a new ValidatorSet.

func (*ValidatorSet) CopyIncrementProposerPriority

func (vals *ValidatorSet) CopyIncrementProposerPriority(times int) *ValidatorSet

CopyIncrementProposerPriority 递增ProposerPriority并更新副本中的提议者,然后将其返回。

func (*ValidatorSet) GetByAddress

func (vals *ValidatorSet) GetByAddress(address []byte) (index int, val *Validator)

GetByAddress returns an index of the validator with address and validator itself if found. Otherwise, -1 and nil are returned.

func (*ValidatorSet) GetByIndex

func (vals *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator)

GetByIndex returns the validator's address and validator itself by index. It returns nil values if index is less than 0 or greater or equal to len(ValidatorSet.Validators).

func (*ValidatorSet) GetProposer

func (vals *ValidatorSet) GetProposer() (proposer *Validator)

GetProposer 返回当前的proposer。如果当前验证者集合为空,返回nil

func (*ValidatorSet) HasAddress

func (vals *ValidatorSet) HasAddress(address []byte) bool

HasAddress returns true if address given is in the validator set, false - otherwise.

func (*ValidatorSet) Hash

func (vals *ValidatorSet) Hash() []byte

Hash 将所有的验证器序列化并生成默克尔树根哈希

func (*ValidatorSet) IncrementProposerPriority

func (vals *ValidatorSet) IncrementProposerPriority(times int)

IncrementProposerPriority increments ProposerPriority of each validator and updates the proposer. Panics if validator set is empty. `times` must be positive.

func (*ValidatorSet) IsNilOrEmpty

func (vals *ValidatorSet) IsNilOrEmpty() bool

IsNilOrEmpty 如果验证者集合为nil或空,返回true

func (*ValidatorSet) Iterate

func (vals *ValidatorSet) Iterate(fn func(index int, val *Validator) bool)

Iterate 用自己传入的方法来遍历

func (*ValidatorSet) RescalePriorities

func (vals *ValidatorSet) RescalePriorities(diffMax int64)

RescalePriorities 重新调整优先级,使最大值和最小值之间的距离小于`diffMax`。

func (*ValidatorSet) Size

func (vals *ValidatorSet) Size() int

Size 返回验证者集合的长度

func (*ValidatorSet) String

func (vals *ValidatorSet) String() string

func (*ValidatorSet) StringIndented

func (vals *ValidatorSet) StringIndented(indent string) string

StringIndented returns an intended string representation of ValidatorSet.

func (*ValidatorSet) ToProto

func (vals *ValidatorSet) ToProto() (*tmproto.ValidatorSet, error)

ToProto converts ValidatorSet to protobuf

func (*ValidatorSet) TotalVotingPower

func (vals *ValidatorSet) TotalVotingPower() int64

TotalVotingPower 返回所有验证者的投票权之和. 如果需要,它将重新计算总投票权。

func (*ValidatorSet) UpdateWithChangeSet

func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error

UpdateWithChangeSet attempts to update the validator set with 'changes'. It performs the following steps:

  • validates the changes making sure there are no duplicates and splits them in updates and deletes
  • verifies that applying the changes will not result in errors
  • computes the total voting power BEFORE removals to ensure that in the next steps the priorities across old and newly added validators are fair
  • computes the priorities of new validators against the final set
  • applies the updates against the validator set
  • applies the removals against the validator set
  • performs scaling and centering of priority values

If an error is detected during verification steps, it is returned and the validator set is not changed.

func (*ValidatorSet) VerifyCommit

func (vals *ValidatorSet) VerifyCommit(chainID string, blockID BlockID,
	height int64, commit *Commit) error

VerifyCommit verifies +2/3 of the set had signed the given commit.

It checks all the signatures! While it's safe to exit as soon as we have 2/3+ signatures, doing so would impact incentivization logic in the ABCI application that depends on the LastCommitInfo sent in BeginBlock, which includes which validators signed. For instance, Gaia incentivizes proposers with a bonus for including more than +2/3 of the signatures.

func (*ValidatorSet) VerifyCommitLight

func (vals *ValidatorSet) VerifyCommitLight(chainID string, blockID BlockID,
	height int64, commit *Commit) error

VerifyCommitLight verifies +2/3 of the set had signed the given commit.

This method is primarily used by the light client and does not check all the signatures.

func (*ValidatorSet) VerifyCommitLightTrusting

func (vals *ValidatorSet) VerifyCommitLightTrusting(chainID string, blockID BlockID,
	height int64, commit *Commit, trustLevel tmmath.Fraction) error

VerifyCommitLightTrusting verifies that trustLevel of the validator set signed this commit.

This method is primarily used by the light client and does not check all the signatures.

NOTE the given validators do not necessarily correspond to the validator set for this commit, but there may be some intersection.

Panics if trustLevel is invalid.

func (*ValidatorSet) VerifyFutureCommit

func (vals *ValidatorSet) VerifyFutureCommit(newSet *ValidatorSet, chainID string,
	blockID BlockID, height int64, commit *Commit) error

VerifyFutureCommit will check to see if the set would be valid with a different validator set.

vals is the old validator set that we know. Over 2/3 of the power in old signed this block.

In Tendermint, 1/3 of the voting power can halt or fork the chain, but 1/3 can't make arbitrary state transitions. You still need > 2/3 Byzantine to make arbitrary state transitions.

To preserve this property in the light client, we also require > 2/3 of the old vals to sign the future commit at H, that way we preserve the property that if they weren't being truthful about the validator set at H (block hash -> vals hash) or about the app state (block hash -> app hash) we can slash > 2/3. Otherwise, the lite client isn't providing the same security guarantees.

Even if we added a slashing condition that if you sign a block header with the wrong validator set, then we would only need > 1/3 of signatures from the old vals on the new commit, it wouldn't be sufficient because the new vals can be arbitrary and commit some arbitrary app hash.

newSet is the validator set that signed this block. Only votes from new are sufficient for 2/3 majority in the new set as well, for it to be a valid commit.

NOTE: This doesn't check whether the commit is a future commit, because the current height isn't part of the ValidatorSet. Caller must check that the commit height is greater than the height for this validator set.

type ValidatorsByAddress

type ValidatorsByAddress []*Validator

ValidatorsByAddress implements the sort of validators by address.

func (ValidatorsByAddress) Len

func (valz ValidatorsByAddress) Len() int

func (ValidatorsByAddress) Less

func (valz ValidatorsByAddress) Less(i, j int) bool

func (ValidatorsByAddress) Swap

func (valz ValidatorsByAddress) Swap(i, j int)

type Vote

type Vote struct {
	Type             SignedMsgType `json:"type"`
	Height           int64         `json:"height"`
	Round            int           `json:"round"`
	BlockID          BlockID       `json:"block_id"` // zero if vote is nil.
	Timestamp        time.Time     `json:"timestamp"`
	ValidatorAddress Address       `json:"validator_address"`
	ValidatorIndex   int           `json:"validator_index"`
	Signature        []byte        `json:"signature"`
}

Vote 代表了来自验证者的一个用于共识prevote,precommit,或者commit的投票。

func MakeVote

func MakeVote(
	height int64,
	blockID BlockID,
	valSet *ValidatorSet,
	privVal PrivValidator,
	chainID string,
	now time.Time,
) (*Vote, error)

func VoteFromProto

func VoteFromProto(pv *tmproto.Vote) (*Vote, error)

FromProto 将proto类型的vote转为普通类型vote

func (*Vote) CommitSig

func (vote *Vote) CommitSig() CommitSig

CommitSig 将vote转为commitSig

func (*Vote) Copy

func (vote *Vote) Copy() *Vote

func (*Vote) SignBytes

func (vote *Vote) SignBytes(chainID string) []byte

func (*Vote) String

func (vote *Vote) String() string

func (*Vote) ToProto

func (vote *Vote) ToProto() *tmproto.Vote

ToProto 将普通vote类型转为proto的vote类型

func (*Vote) ValidateBasic

func (vote *Vote) ValidateBasic() error

ValidateBasic 执行基础验证

func (*Vote) Verify

func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error

type VoteSet

type VoteSet struct {
	// contains filtered or unexported fields
}
	VoteSet有助于在预定义的投票类型的每个height和round处从验证者收集签名。

	当验证者进行双重签名时,我们需要VoteSet能够跟踪冲突的投票。但是,我们无法跟踪所有看到的投票,
	因为这可能是DoS攻击的载体。

	有两个存放投票的区域。
	1. voteSet.votes
	2. voteSet.votesByBlock

	`.votes`是投票的“规范”列表。 如果已经看到验证者的一票,它总是至少有一票。
 	通常,它会跟踪看到的第一次投票,但是当找到2/3的多数票时,该票将获得优先权并从`.votesByBlock`复制过来。

	`.votesByBlock`跟踪特定块的投票列表。在`.votesByBlock`中创建&blockVotes{}的方式有两种。
	1. 验证者所看到的第一票是针对特定区块的。
	2. 一个peer声称在看到了该特定区块的2/3多数投票。

	Since the first vote from a validator will always get added in `.votesByBlock`
	, all votes in `.votes` will have a corresponding entry in `.votesByBlock`.

	When a &blockVotes{} in `.votesByBlock` reaches a 2/3 majority quorum, its
	votes are copied into `.votes`.

	所有这些都是内存有限的,因为只有当一个peer告诉我们跟踪该块时,才会添加冲突的投票,每个peer只能告诉我们1个这样的块,
	并且,peer的数量有限。

	注意:假定投票权的总和不超过Max uint64。

func CommitToVoteSet

func CommitToVoteSet(chainID string, commit *Commit, vals *ValidatorSet) *VoteSet

CommitToVoteSet constructs a VoteSet from the Commit and validator set. Panics if signatures from the commit can't be added to the voteset. Inverse of VoteSet.MakeCommit().

func NewVoteSet

func NewVoteSet(chainID string, height int64, round int, signedMsgType SignedMsgType, valSet *ValidatorSet) *VoteSet

Constructs a new VoteSet struct used to accumulate votes for given height/round.

func (*VoteSet) AddVote

func (voteSet *VoteSet) AddVote(vote *Vote) (added bool, err error)

Returns added=true if vote is valid and new. Otherwise returns err=ErrVote[

UnexpectedStep | InvalidIndex | InvalidAddress |
InvalidSignature | InvalidBlockHash | ConflictingVotes ]

Duplicate votes return added=false, err=nil. Conflicting votes return added=*, err=ErrVoteConflictingVotes. NOTE: vote should not be mutated after adding. NOTE: VoteSet must not be nil NOTE: Vote must not be nil

func (*VoteSet) BitArray

func (voteSet *VoteSet) BitArray() *bits.BitArray

Implements VoteSetReader.

func (*VoteSet) BitArrayByBlockID

func (voteSet *VoteSet) BitArrayByBlockID(blockID BlockID) *bits.BitArray

func (*VoteSet) BitArrayString

func (voteSet *VoteSet) BitArrayString() string

Return the bit-array of votes including the fraction of power that has voted like: "BA{29:xx__x__x_x___x__x_______xxx__} 856/1304 = 0.66"

func (*VoteSet) ChainID

func (voteSet *VoteSet) ChainID() string

func (*VoteSet) GetByAddress

func (voteSet *VoteSet) GetByAddress(address []byte) *Vote

func (*VoteSet) GetByIndex

func (voteSet *VoteSet) GetByIndex(valIndex int) *Vote

NOTE: if validator has conflicting votes, returns "canonical" vote Implements VoteSetReader.

func (*VoteSet) GetHeight

func (voteSet *VoteSet) GetHeight() int64

Implements VoteSetReader.

func (*VoteSet) GetRound

func (voteSet *VoteSet) GetRound() int

Implements VoteSetReader.

func (*VoteSet) HasAll

func (voteSet *VoteSet) HasAll() bool

func (*VoteSet) HasTwoThirdsAny

func (voteSet *VoteSet) HasTwoThirdsAny() bool

func (*VoteSet) HasTwoThirdsMajority

func (voteSet *VoteSet) HasTwoThirdsMajority() bool

func (*VoteSet) IsCommit

func (voteSet *VoteSet) IsCommit() bool

Implements VoteSetReader.

func (*VoteSet) MakeCommit

func (voteSet *VoteSet) MakeCommit() *Commit

MakeCommit constructs a Commit from the VoteSet. It only includes precommits for the block, which has 2/3+ majority, and nil.

Panics if the vote type is not PrecommitType or if there's no +2/3 votes for a single block.

func (*VoteSet) MarshalJSON

func (voteSet *VoteSet) MarshalJSON() ([]byte, error)

Marshal the VoteSet to JSON. Same as String(), just in JSON, and without the height/round/signedMsgType (since its already included in the votes).

func (*VoteSet) SetPeerMaj23

func (voteSet *VoteSet) SetPeerMaj23(peerID P2PID, blockID BlockID) error

如果一个peer声明它拥有给定blockKey的+2/3投票,调用这个函数 注意: 如果有太多的peer, 或者太多的peer调用(churn),可能会发生内存问题。 TODO: implement ability to remove peers too NOTE: VoteSet must not be nil

func (*VoteSet) Size

func (voteSet *VoteSet) Size() int

Implements VoteSetReader.

func (*VoteSet) String

func (voteSet *VoteSet) String() string

func (*VoteSet) StringIndented

func (voteSet *VoteSet) StringIndented(indent string) string

func (*VoteSet) StringShort

func (voteSet *VoteSet) StringShort() string

func (*VoteSet) TwoThirdsMajority

func (voteSet *VoteSet) TwoThirdsMajority() (blockID BlockID, ok bool)

If there was a +2/3 majority for blockID, return blockID and true. Else, return the empty BlockID{} and false.

func (*VoteSet) Type

func (voteSet *VoteSet) Type() byte

Implements VoteSetReader.

func (*VoteSet) VoteStrings

func (voteSet *VoteSet) VoteStrings() []string

Returns a list of votes compressed to more readable strings.

type VoteSetJSON

type VoteSetJSON struct {
	Votes         []string          `json:"votes"`
	VotesBitArray string            `json:"votes_bit_array"`
	PeerMaj23s    map[P2PID]BlockID `json:"peer_maj_23s"`
}

More human readable JSON of the vote set NOTE: insufficient for unmarshalling from (compressed votes) TODO: make the peerMaj23s nicer to read (eg just the block hash)

type VoteSetReader

type VoteSetReader interface {
	GetHeight() int64
	GetRound() int
	Type() byte
	Size() int
	BitArray() *bits.BitArray
	GetByIndex(int) *Vote
	IsCommit() bool
}

Common interface between *consensus.VoteSet and types.Commit

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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