types

package
v0.0.0-sei-fork Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2024 License: Apache-2.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxHeaderBytes is a maximum header size.
	// NOTE: Because app hash can be of arbitrary size, the header is therefore not
	// capped in size and thus this number should be seen as a soft max
	MaxHeaderBytes int64 = 626

	// MaxOverheadForBlock - maximum 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.
	//
	// Uvarint length of MaxBlockSizeBytes: 4 bytes
	// 2 fields (2 embedded):               2 bytes
	// Uvarint length of Data.Txs:          4 bytes
	// Data.Txs field:                      1 byte
	MaxOverheadForBlock int64 = 11
)
View Source
const (
	// Max size of commit without any commitSigs -> 82 for BlockID, 8 for Height, 4 for Round.
	MaxCommitOverheadBytes int64 = 94
	// Commit sig size is made up of 64 bytes for the signature, 20 bytes for the address,
	// 1 byte for the flag and 14 bytes for the timestamp
	MaxCommitSigBytes int64 = 109
)
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.
	EventNewBlockValue            = "NewBlock"
	EventNewBlockHeaderValue      = "NewBlockHeader"
	EventNewEvidenceValue         = "NewEvidence"
	EventTxValue                  = "Tx"
	EventValidatorSetUpdatesValue = "ValidatorSetUpdates"

	// Internal consensus events.
	// These are used for testing the consensus state machine.
	// They can also be used to build real-time consensus visualizers.
	EventCompleteProposalValue = "CompleteProposal"
	// The BlockSyncStatus event will be emitted when the node switching
	// state sync mechanism between the consensus reactor and the blocksync reactor.
	EventBlockSyncStatusValue = "BlockSyncStatus"
	EventLockValue            = "Lock"
	EventNewRoundValue        = "NewRound"
	EventNewRoundStepValue    = "NewRoundStep"
	EventPolkaValue           = "Polka"
	EventRelockValue          = "Relock"
	EventStateSyncStatusValue = "StateSyncStatus"
	EventTimeoutProposeValue  = "TimeoutPropose"
	EventTimeoutWaitValue     = "TimeoutWait"
	EventValidBlockValue      = "ValidBlock"
	EventVoteValue            = "Vote"

	// Events emitted by the evidence reactor when evidence is validated
	// and before it is committed
	EventEvidenceValidatedValue = "EvidenceValidated"
)

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"

	// BlockHeightKey is a reserved key used for indexing FinalizeBlock events.
	BlockHeightKey = "block.height"
)
View Source
const (
	// MaxBlockSizeBytes is the maximum permitted size of the blocks.
	MaxBlockSizeBytes = 104857600 // 100MB

	// BlockPartSizeBytes is the size of one block part.
	BlockPartSizeBytes uint32 = 1048576 // 1MB

	// MaxBlockPartsCount is the maximum number of block parts.
	MaxBlockPartsCount = (MaxBlockSizeBytes / BlockPartSizeBytes) + 1

	ABCIPubKeyTypeEd25519   = ed25519.KeyType
	ABCIPubKeyTypeSecp256k1 = secp256k1.KeyType
	ABCIPubKeyTypeSr25519   = sr25519.KeyType
)
View Source
const (
	MockSignerClient      = PrivValidatorType(0x00) // mock signer
	FileSignerClient      = PrivValidatorType(0x01) // signer client via file
	RetrySignerClient     = PrivValidatorType(0x02) // signer client with retry via socket
	SignerSocketClient    = PrivValidatorType(0x03) // signer client via socket
	ErrorMockSignerClient = PrivValidatorType(0x04) // error mock signer
	SignerGRPCClient      = PrivValidatorType(0x05) // signer client via gRPC
)
View Source
const (
	// MaxTotalVotingPower - the maximum allowed total voting power.
	// It needs to be sufficiently small to, in all cases:
	// 1. prevent clipping in incrementProposerPriority()
	// 2. let (diff+diffMax-1) not overflow in IncrementProposerPriority()
	// (Proof of 1 is tricky, left to the reader).
	// It could be higher, but this is sufficiently large for our purposes,
	// and leaves room for defensive purposes.
	MaxTotalVotingPower = int64(math.MaxInt64) / 8

	// PriorityWindowSizeFactor - is a constant that when multiplied with the
	// total voting power gives the maximum allowed distance between validator
	// priorities.
	PriorityWindowSizeFactor = 2
)
View Source
const (
	// MaxChainIDLen is a maximum length of the chain ID.
	MaxChainIDLen = 50
)
View Source
const (

	// The maximum supported number of bytes in a vote extension.
	MaxVoteExtensionSize int = 1024 * 1024
)
View Source
const (
	// MaxVotesCount is the maximum number of votes in a set. Used in ValidateBasic funcs for
	// protection against DOS attacks. Note this implies a corresponding equal limit to
	// the number of validators.
	MaxVotesCount = 10000
)
View Source
const NodeIDByteLength = crypto.AddressSize

NodeIDByteLength is the length of a crypto.Address. Currently only 20. FIXME: support other length addresses?

View Source
const TimeFormat = time.RFC3339Nano

TimeFormat is used for generating the sigs

Variables

View Source
var (
	EventNewBlock = abci.Event{
		Type: strings.Split(EventTypeKey, ".")[0],
		Attributes: []abci.EventAttribute{
			{
				Key:   []byte(strings.Split(EventTypeKey, ".")[1]),
				Value: []byte(EventNewBlockValue),
			},
		},
	}

	EventNewBlockHeader = abci.Event{
		Type: strings.Split(EventTypeKey, ".")[0],
		Attributes: []abci.EventAttribute{
			{
				Key:   []byte(strings.Split(EventTypeKey, ".")[1]),
				Value: []byte(EventNewBlockHeaderValue),
			},
		},
	}

	EventNewEvidence = abci.Event{
		Type: strings.Split(EventTypeKey, ".")[0],
		Attributes: []abci.EventAttribute{
			{
				Key:   []byte(strings.Split(EventTypeKey, ".")[1]),
				Value: []byte(EventNewEvidenceValue),
			},
		},
	}

	EventTx = abci.Event{
		Type: strings.Split(EventTypeKey, ".")[0],
		Attributes: []abci.EventAttribute{
			{
				Key:   []byte(strings.Split(EventTypeKey, ".")[1]),
				Value: []byte(EventTxValue),
			},
		},
	}
)

Pre-populated ABCI Tendermint-reserved events

View Source
var (
	EventQueryCompleteProposal    = QueryForEvent(EventCompleteProposalValue)
	EventQueryLock                = QueryForEvent(EventLockValue)
	EventQueryNewBlock            = QueryForEvent(EventNewBlockValue)
	EventQueryNewBlockHeader      = QueryForEvent(EventNewBlockHeaderValue)
	EventQueryNewEvidence         = QueryForEvent(EventNewEvidenceValue)
	EventQueryNewRound            = QueryForEvent(EventNewRoundValue)
	EventQueryNewRoundStep        = QueryForEvent(EventNewRoundStepValue)
	EventQueryPolka               = QueryForEvent(EventPolkaValue)
	EventQueryRelock              = QueryForEvent(EventRelockValue)
	EventQueryTimeoutPropose      = QueryForEvent(EventTimeoutProposeValue)
	EventQueryTimeoutWait         = QueryForEvent(EventTimeoutWaitValue)
	EventQueryTx                  = QueryForEvent(EventTxValue)
	EventQueryValidatorSetUpdates = QueryForEvent(EventValidatorSetUpdatesValue)
	EventQueryValidBlock          = QueryForEvent(EventValidBlockValue)
	EventQueryVote                = QueryForEvent(EventVoteValue)
	EventQueryBlockSyncStatus     = QueryForEvent(EventBlockSyncStatusValue)
	EventQueryStateSyncStatus     = QueryForEvent(EventStateSyncStatusValue)
	EventQueryEvidenceValidated   = QueryForEvent(EventEvidenceValidatedValue)
)
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")
	ErrVoteExtensionAbsent           = errors.New("vote extension absent")
)
View Source
var ErrTotalVotingPowerOverflow = fmt.Errorf("total voting power of resulting valset exceeds max %d",
	MaxTotalVotingPower)

ErrTotalVotingPowerOverflow is returned if the total voting power of the resulting validator set exceeds MaxTotalVotingPower.

View Source
var ErrTxInCache = errors.New("tx already exists in cache")

ErrTxInCache is returned to the client if we saw tx earlier

View Source
var ErroringMockPVErr = errors.New("erroringMockPV always returns an error")
View Source
var (
	// MaxSignatureSize is a maximum allowed signature size for the Proposal
	// and Vote.
	// XXX: secp256k1 does not have Size nor MaxSize defined.
	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 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 CanonicalizeBlockID

func CanonicalizeBlockID(bid tmproto.BlockID) *tmproto.CanonicalBlockID

func CanonicalizePartSetHeader

func CanonicalizePartSetHeader(psh tmproto.PartSetHeader) tmproto.CanonicalPartSetHeader

CanonicalizeVote transforms the given PartSetHeader to a CanonicalPartSetHeader.

func CanonicalizeProposal

func CanonicalizeProposal(chainID string, proposal *tmproto.Proposal) tmproto.CanonicalProposal

CanonicalizeVote transforms the given Proposal to a CanonicalProposal.

func CanonicalizeVote

func CanonicalizeVote(chainID string, vote *tmproto.Vote) tmproto.CanonicalVote

CanonicalizeVote transforms the given Vote to a CanonicalVote, which does not contain ValidatorIndex and ValidatorAddress fields, or any fields relating to vote extensions.

func CanonicalizeVoteExtension

func CanonicalizeVoteExtension(chainID string, vote *tmproto.Vote) tmproto.CanonicalVoteExtension

CanonicalizeVoteExtension extracts the vote extension from the given vote and constructs a CanonicalizeVoteExtension struct, whose representation in bytes is what is signed in order to produce the vote extension's signature.

func ComputeProtoSizeForTxs

func ComputeProtoSizeForTxs(txs []Tx) int64

ComputeProtoSizeForTxs wraps the transactions in tmproto.Data{} and calculates the size. https://developers.google.com/protocol-buffers/docs/encoding

func EventQueryTxFor

func EventQueryTxFor(tx Tx) *tmquery.Query

func EvidenceToProto

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

EvidenceToProto is a generalized function for encoding evidence that conforms to the evidence interface to protobuf

func IsErrNotEnoughVotingPowerSigned

func IsErrNotEnoughVotingPowerSigned(err error) bool

IsErrNotEnoughVotingPowerSigned returns true if err is ErrNotEnoughVotingPowerSigned.

func IsPreCheckError

func IsPreCheckError(err error) bool

IsPreCheckError returns true if err is due to pre check failure.

func IsVoteTypeValid

func IsVoteTypeValid(t tmproto.SignedMsgType) bool

IsVoteTypeValid returns true if t is a valid vote type.

func MaxCommitBytes

func MaxCommitBytes(valCount int) int64

func MaxDataBytes

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

MaxDataBytes returns the maximum size of block's data.

XXX: Panics on negative result.

func MaxDataBytesNoEvidence

func MaxDataBytesNoEvidence(maxBytes int64, valsCount int) int64

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

func MaxNodeInfoSize() int

Max size of the NodeInfo struct

func ParseAddressString

func ParseAddressString(addr string) (net.IP, uint16, error)

ParseAddressString reads an address string, and returns the IP address and port information, returning an error for any validation errors.

func ProposalSignBytes

func ProposalSignBytes(chainID string, p *tmproto.Proposal) []byte

ProposalSignBytes returns the proto-encoding of the canonicalized Proposal, for signing. Panics if the marshaling fails.

The encoded Protobuf message is varint length-prefixed (using MarshalDelimited) for backwards-compatibility with the Amino encoding, due to e.g. hardware devices that rely on this encoding.

See CanonicalizeProposal

func ProtoBlockIDIsNil

func ProtoBlockIDIsNil(bID *tmproto.BlockID) bool

ProtoBlockIDIsNil is similar to the IsNil function on BlockID, but for the Protobuf representation.

func ProtoPartSetHeaderIsZero

func ProtoPartSetHeaderIsZero(ppsh *tmproto.PartSetHeader) bool

ProtoPartSetHeaderIsZero is similar to the IsZero function for PartSetHeader, but for the Protobuf representation.

func QueryForEvent

func QueryForEvent(eventValue string) *tmquery.Query

func RandValidator

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

RandValidator returns a randomized validator, useful for testing. UNSTABLE

func RandValidatorSet

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

RandValidatorSet returns a randomized validator set (size: +numValidators+), where each validator has a voting power of +votingPower+.

EXPOSED FOR TESTING.

func ValidateHash

func ValidateHash(h []byte) error

ValidateHash returns an error if the hash is not empty, but its size != crypto.HashSize.

func ValidatorListString

func ValidatorListString(vals []*Validator) string

ValidatorListString returns a prettified validator list for logging purposes.

func VerifyCommit

func VerifyCommit(chainID string, vals *ValidatorSet, 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 FinalizeBlock, which includes which validators signed. For instance, Gaia incentivizes proposers with a bonus for including more than +2/3 of the signatures.

func VerifyCommitLight

func VerifyCommitLight(chainID string, vals *ValidatorSet, 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 VerifyCommitLightTrusting

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

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

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

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

func VoteExtensionSignBytes

func VoteExtensionSignBytes(chainID string, vote *tmproto.Vote) []byte

VoteExtensionSignBytes returns the proto-encoding of the canonicalized vote extension for signing. Panics if the marshaling fails.

Similar to VoteSignBytes, the encoded Protobuf message is varint length-prefixed for backwards-compatibility with the Amino encoding.

func VoteSignBytes

func VoteSignBytes(chainID string, vote *tmproto.Vote) []byte

VoteSignBytes returns the proto-encoding of the canonicalized Vote, for signing. Panics if the marshaling fails.

The encoded Protobuf message is varint length-prefixed (using MarshalDelimited) for backwards-compatibility with the Amino encoding, due to e.g. hardware devices that rely on this encoding.

See CanonicalizeVote

func VotesToProto

func VotesToProto(votes []*Vote) []*tmproto.Vote

Types

type ABCIParams

type ABCIParams struct {
	VoteExtensionsEnableHeight int64 `json:"vote_extensions_enable_height"`
	RecheckTx                  bool  `json:"recheck_tx"`
}

ABCIParams configure ABCI functionality specific to the Application Blockchain Interface.

func DefaultABCIParams

func DefaultABCIParams() ABCIParams

func (ABCIParams) VoteExtensionsEnabled

func (a ABCIParams) VoteExtensionsEnabled(h int64) bool

VoteExtensionsEnabled returns true if vote extensions are enabled at height h and false otherwise.

type ABCIResults

type ABCIResults []*abci.ResponseDeliverTx

ABCIResults wraps the deliver tx results to return a proof.

func NewResults

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

NewResults strips non-deterministic fields from ResponseDeliverTx responses and returns ABCIResults.

func (ABCIResults) Hash

func (a ABCIResults) Hash() []byte

func (ABCIResults) ProveResult

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

type Address

type Address = crypto.Address

Address is hex bytes.

type Block

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

Block defines the atomic unit of a Tendermint blockchain.

func BlockFromProto

func BlockFromProto(bp *tmproto.Block) (*Block, error)

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

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

func (b *Block) GetTxKeys() []TxKey

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 uint32) (*PartSet, error)

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

See StringIndented.

func (*Block) StringIndented

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

StringIndented returns an indented String.

Header Data Evidence LastCommit Hash

func (*Block) StringShort

func (b *Block) StringShort() string

StringShort returns a shortened string representation of the block.

func (*Block) ToProto

func (b *Block) ToProto() (*tmproto.Block, error)

ToProto converts Block to protobuf

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(EventDataNewBlock) error
	PublishEventNewBlockHeader(EventDataNewBlockHeader) error
	PublishEventNewEvidence(EventDataNewEvidence) error
	PublishEventTx(EventDataTx) error
	PublishEventValidatorSetUpdates(EventDataValidatorSetUpdates) error
}

BlockEventPublisher publishes all block related events

type BlockID

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

BlockID

func BlockIDFromProto

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

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

func (BlockID) Equals

func (blockID BlockID) Equals(other BlockID) bool

Equals returns true if the BlockID matches the given BlockID

func (BlockID) IsComplete

func (blockID BlockID) IsComplete() bool

IsComplete returns true if this is a valid BlockID of a non-nil block.

func (BlockID) IsNil

func (blockID BlockID) IsNil() bool

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

func (BlockID) Key

func (blockID BlockID) Key() string

Key returns a machine-readable string representation of the BlockID

func (BlockID) String

func (blockID BlockID) String() string

String returns a human readable string representation of the BlockID.

1. hash 2. part set header

See PartSetHeader#String

func (*BlockID) ToProto

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

ToProto converts BlockID to 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 - no vote was received from a validator.
	BlockIDFlagAbsent BlockIDFlag = iota + 1
	// BlockIDFlagCommit - voted for the Commit.BlockID.
	BlockIDFlagCommit
	// BlockIDFlagNil - voted for nil.
	BlockIDFlagNil
)

type BlockMeta

type BlockMeta struct {
	BlockID   BlockID `json:"block_id"`
	BlockSize int     `json:"block_size,string"`
	Header    Header  `json:"header"`
	NumTxs    int     `json:"num_txs,string"`
}

BlockMeta contains meta information.

func BlockMetaFromProto

func BlockMetaFromProto(pb *tmproto.BlockMeta) (*BlockMeta, error)

func NewBlockMeta

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

NewBlockMeta returns a new BlockMeta.

func (*BlockMeta) ToProto

func (bm *BlockMeta) ToProto() *tmproto.BlockMeta

func (*BlockMeta) ValidateBasic

func (bm *BlockMeta) ValidateBasic() error

ValidateBasic performs basic validation.

type BlockParams

type BlockParams struct {
	MaxBytes int64 `json:"max_bytes,string"`
	MaxGas   int64 `json:"max_gas,string"`
}

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

func DefaultBlockParams

func DefaultBlockParams() BlockParams

DefaultBlockParams returns a default BlockParams.

type Commit

type Commit struct {
	// NOTE: The signatures are in order of address to preserve the bonded
	// ValidatorSet order.
	// Any peer with a block can gossip signatures by index with a peer without
	// recalculating the active ValidatorSet.
	Height     int64       `json:"height,string"`
	Round      int32       `json:"round"`
	BlockID    BlockID     `json:"block_id"`
	Signatures []CommitSig `json:"signatures"`
	// contains filtered or unexported fields
}

Commit contains the evidence that a block was committed by a set of validators. NOTE: Commit is empty for height 1, but never 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 (*Commit) GetVote

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

GetVote converts the CommitSig for the given valIdx to a Vote. Commits do not contain vote extensions, so the vote extension and vote extension signature will not be present in the returned 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) Size

func (commit *Commit) Size() int

Size returns the number of signatures in the commit.

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

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

ToVoteSet 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 (*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 int32) []byte

VoteSignBytes returns the bytes of the Vote corresponding to valIdx for signing.

The only unique part is the Timestamp - all other fields signed over are otherwise the same for all validators.

Panics if valIdx >= commit.Size().

See VoteSignBytes

func (*Commit) WrappedExtendedCommit

func (commit *Commit) WrappedExtendedCommit() *ExtendedCommit

WrappedExtendedCommit wraps a commit as an ExtendedCommit. The VoteExtension fields of the resulting value will by nil. Wrapping a Commit as an ExtendedCommit is useful when an API requires an ExtendedCommit wire type but does not need the VoteExtension data.

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 is a part of the Vote included in a Commit.

func NewCommitSigAbsent

func NewCommitSigAbsent() CommitSig

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

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

CommitSig returns a string representation of CommitSig.

1. first 6 bytes of signature 2. first 6 bytes of validator address 3. block ID flag 4. timestamp

func (*CommitSig) ToProto

func (cs *CommitSig) ToProto() *tmproto.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"`
	Version   VersionParams   `json:"version"`
	Synchrony SynchronyParams `json:"synchrony"`
	Timeout   TimeoutParams   `json:"timeout"`
	ABCI      ABCIParams      `json:"abci"`
}

ConsensusParams contains consensus critical parameters that determine the validity of blocks.

func ConsensusParamsFromProto

func ConsensusParamsFromProto(pbParams tmproto.ConsensusParams) ConsensusParams

func DefaultConsensusParams

func DefaultConsensusParams() *ConsensusParams

DefaultConsensusParams returns a default ConsensusParams.

func (*ConsensusParams) Complete

func (params *ConsensusParams) Complete()

func (*ConsensusParams) Equals

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

func (ConsensusParams) HashConsensusParams

func (params ConsensusParams) HashConsensusParams() []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. TODO: We should hash the other parameters as well

func (*ConsensusParams) ToProto

func (params *ConsensusParams) ToProto() tmproto.ConsensusParams

func (ConsensusParams) UpdateConsensusParams

func (params ConsensusParams) UpdateConsensusParams(params2 *tmproto.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) ValidateConsensusParams

func (params ConsensusParams) ValidateConsensusParams() error

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

func (ConsensusParams) ValidateUpdate

func (params ConsensusParams) ValidateUpdate(updated *tmproto.ConsensusParams, h int64) 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 DataFromProto

func DataFromProto(dp *tmproto.Data) (Data, error)

DataFromProto takes a protobuf representation of Data & returns the native type.

func (*Data) Hash

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

Hash returns the hash of the data

func (*Data) StringIndented

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

StringIndented returns an indented string representation of the transactions.

func (*Data) ToProto

func (data *Data) ToProto() tmproto.Data

ToProto converts Data to protobuf

type DuplicateVoteEvidence

type DuplicateVoteEvidence struct {
	VoteA *Vote `json:"vote_a"`
	VoteB *Vote `json:"vote_b"`

	// abci specific information
	TotalVotingPower int64 `json:",string"`
	ValidatorPower   int64 `json:",string"`
	Timestamp        time.Time
}

DuplicateVoteEvidence contains evidence of a single validator signing two conflicting votes.

func DuplicateVoteEvidenceFromProto

func DuplicateVoteEvidenceFromProto(pb *tmproto.DuplicateVoteEvidence) (*DuplicateVoteEvidence, error)

DuplicateVoteEvidenceFromProto decodes protobuf into DuplicateVoteEvidence

func NewDuplicateVoteEvidence

func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet,
) (*DuplicateVoteEvidence, error)

NewDuplicateVoteEvidence creates DuplicateVoteEvidence with right ordering given two conflicting votes. If either of the votes is nil, the val set is nil or the voter is not in the val set, an error is returned

func NewMockDuplicateVoteEvidence

func NewMockDuplicateVoteEvidence(ctx context.Context, height int64, time time.Time, chainID string) (*DuplicateVoteEvidence, error)

assumes the round to be 0 and the validator index to be 0

func NewMockDuplicateVoteEvidenceWithValidator

func NewMockDuplicateVoteEvidenceWithValidator(ctx context.Context, height int64, time time.Time, pv PrivValidator, chainID string) (*DuplicateVoteEvidence, error)

assumes voting power to be 10 and validator to be the only one in the set

func (*DuplicateVoteEvidence) ABCI

func (dve *DuplicateVoteEvidence) ABCI() []abci.Misbehavior

ABCI returns the application relevant representation of the evidence

func (*DuplicateVoteEvidence) Bytes

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

Bytes returns the proto-encoded evidence as a byte array.

func (*DuplicateVoteEvidence) GenerateABCI

func (dve *DuplicateVoteEvidence) GenerateABCI(
	val *Validator,
	valSet *ValidatorSet,
	evidenceTime time.Time,
)

GenerateABCI populates the ABCI component of the evidence. This includes the validator power, timestamp and total voting power.

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 of the infraction

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 returns the time of the infraction

func (*DuplicateVoteEvidence) ToProto

ToProto encodes DuplicateVoteEvidence to protobuf

func (*DuplicateVoteEvidence) TypeTag

func (*DuplicateVoteEvidence) TypeTag() string

TypeTag implements the jsontypes.Tagged interface.

func (*DuplicateVoteEvidence) ValidateABCI

func (dve *DuplicateVoteEvidence) ValidateABCI(
	val *Validator,
	valSet *ValidatorSet,
	evidenceTime time.Time,
) error

ValidateABCI validates the ABCI component of the evidence by checking the timestamp, validator power and total voting power.

func (*DuplicateVoteEvidence) ValidateBasic

func (dve *DuplicateVoteEvidence) ValidateBasic() error

ValidateBasic performs basic validation.

type ErrEvidenceOverflow

type ErrEvidenceOverflow struct {
	Max int64
	Got int64
}

ErrEvidenceOverflow is for when there the amount of evidence exceeds the max bytes.

func NewErrEvidenceOverflow

func NewErrEvidenceOverflow(max, got int64) *ErrEvidenceOverflow

NewErrEvidenceOverflow returns a new ErrEvidenceOverflow where got > max.

func (*ErrEvidenceOverflow) Error

func (err *ErrEvidenceOverflow) Error() string

Error returns a string representation of the 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 ErrInvalidEvidence

type ErrInvalidEvidence struct {
	Evidence Evidence
	Reason   error
}

ErrInvalidEvidence wraps a piece of evidence and the error denoting how or why it is invalid.

func NewErrInvalidEvidence

func NewErrInvalidEvidence(ev Evidence, err error) *ErrInvalidEvidence

NewErrInvalidEvidence returns a new EvidenceInvalid with the given err.

func (*ErrInvalidEvidence) Error

func (err *ErrInvalidEvidence) Error() string

Error returns a string representation of the error.

type ErrMempoolIsFull

type ErrMempoolIsFull struct {
	NumTxs      int
	MaxTxs      int
	TxsBytes    int64
	MaxTxsBytes int64
}

ErrMempoolIsFull defines an error where Tendermint and the application cannot handle that much load.

func (ErrMempoolIsFull) Error

func (e ErrMempoolIsFull) Error() string

type ErrNetAddressInvalid

type ErrNetAddressInvalid struct {
	Addr string
	Err  error
}

func (ErrNetAddressInvalid) Error

func (e ErrNetAddressInvalid) Error() string

type ErrNetAddressLookup

type ErrNetAddressLookup struct {
	Addr string
	Err  error
}

func (ErrNetAddressLookup) Error

func (e ErrNetAddressLookup) Error() string

type ErrNetAddressNoID

type ErrNetAddressNoID struct {
	Addr string
}

func (ErrNetAddressNoID) Error

func (e ErrNetAddressNoID) Error() string

type ErrNotEnoughVotingPowerSigned

type ErrNotEnoughVotingPowerSigned struct {
	Got    int64
	Needed int64
}

ErrNotEnoughVotingPowerSigned is returned when not enough validators signed a commit.

func (ErrNotEnoughVotingPowerSigned) Error

type ErrPreCheck

type ErrPreCheck struct {
	Reason error
}

ErrPreCheck defines an error where a transaction fails a pre-check.

func (ErrPreCheck) Error

func (e ErrPreCheck) Error() string

type ErrTxTooLarge

type ErrTxTooLarge struct {
	Max    int
	Actual int
}

ErrTxTooLarge defines an error when a transaction is too big to be sent in a message to other peers.

func (ErrTxTooLarge) Error

func (e ErrTxTooLarge) Error() string

type ErrVoteConflictingVotes

type ErrVoteConflictingVotes struct {
	VoteA *Vote
	VoteB *Vote
}

func NewConflictingVoteError

func NewConflictingVoteError(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) GetPubKey

func (pv *ErroringMockPV) GetPubKey(ctx context.Context) (crypto.PubKey, error)

Implements PrivValidator.

func (*ErroringMockPV) SignProposal

func (pv *ErroringMockPV) SignProposal(ctx context.Context, chainID string, proposal *tmproto.Proposal) error

Implements PrivValidator.

func (*ErroringMockPV) SignVote

func (pv *ErroringMockPV) SignVote(ctx context.Context, chainID string, vote *tmproto.Vote) error

Implements PrivValidator.

type EventData

type EventData interface {
	// The value must support encoding as a type-tagged JSON object.
	jsontypes.Tagged
	ToLegacy() LegacyEventData
}

EventData is satisfied by types that can be published as event data.

Implementations of this interface that contain ABCI event metadata should also implement the eventlog.ABCIEventer extension interface to expose those metadata to the event log machinery. Event data that do not contain ABCI metadata can safely omit this.

func TryUnmarshalEventData

func TryUnmarshalEventData(data json.RawMessage) (EventData, error)

type EventDataBlockSyncStatus

type EventDataBlockSyncStatus struct {
	Complete bool  `json:"complete"`
	Height   int64 `json:"height,string"`
}

EventDataBlockSyncStatus shows the fastsync status and the height when the node state sync mechanism changes.

func (EventDataBlockSyncStatus) ToLegacy

func (EventDataBlockSyncStatus) TypeTag

func (EventDataBlockSyncStatus) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataCompleteProposal

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

	BlockID BlockID `json:"block_id"`
}

func (EventDataCompleteProposal) ToLegacy

func (EventDataCompleteProposal) TypeTag

TypeTag implements the required method of jsontypes.Tagged.

type EventDataEvidenceValidated

type EventDataEvidenceValidated struct {
	Evidence Evidence `json:"evidence"`

	Height int64 `json:"height,string"`
}

func (EventDataEvidenceValidated) ToLegacy

func (EventDataEvidenceValidated) TypeTag

TypeTag implements the required method of jsontypes.Tagged.

type EventDataNewBlock

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

	ResultFinalizeBlock abci.ResponseFinalizeBlock `json:"result_finalize_block"`
}

func (EventDataNewBlock) ABCIEvents

func (e EventDataNewBlock) ABCIEvents() []abci.Event

ABCIEvents implements the eventlog.ABCIEventer interface.

func (EventDataNewBlock) ToLegacy

func (e EventDataNewBlock) ToLegacy() LegacyEventData

func (EventDataNewBlock) TypeTag

func (EventDataNewBlock) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataNewBlockHeader

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

	NumTxs              int64                      `json:"num_txs,string"` // Number of txs in a block
	ResultFinalizeBlock abci.ResponseFinalizeBlock `json:"result_finalize_block"`
}

func (EventDataNewBlockHeader) ABCIEvents

func (e EventDataNewBlockHeader) ABCIEvents() []abci.Event

ABCIEvents implements the eventlog.ABCIEventer interface.

func (EventDataNewBlockHeader) ToLegacy

func (EventDataNewBlockHeader) TypeTag

func (EventDataNewBlockHeader) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataNewEvidence

type EventDataNewEvidence struct {
	Evidence Evidence `json:"evidence"`

	Height int64 `json:"height,string"`
}

func (EventDataNewEvidence) ToLegacy

func (EventDataNewEvidence) TypeTag

func (EventDataNewEvidence) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataNewRound

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

	Proposer ValidatorInfo `json:"proposer"`
}

func (EventDataNewRound) ToLegacy

func (e EventDataNewRound) ToLegacy() LegacyEventData

func (EventDataNewRound) TypeTag

func (EventDataNewRound) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataRoundState

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

NOTE: This goes into the replay WAL

func (EventDataRoundState) ToLegacy

func (e EventDataRoundState) ToLegacy() LegacyEventData

func (EventDataRoundState) TypeTag

func (EventDataRoundState) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataStateSyncStatus

type EventDataStateSyncStatus struct {
	Complete bool  `json:"complete"`
	Height   int64 `json:"height,string"`
}

EventDataStateSyncStatus shows the statesync status and the height when the node state sync mechanism changes.

func (EventDataStateSyncStatus) ToLegacy

func (EventDataStateSyncStatus) TypeTag

func (EventDataStateSyncStatus) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataString

type EventDataString string

func (EventDataString) ToLegacy

func (e EventDataString) ToLegacy() LegacyEventData

func (EventDataString) TypeTag

func (EventDataString) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataTx

type EventDataTx struct {
	abci.TxResult
}

All txs fire EventDataTx

func (EventDataTx) ABCIEvents

func (e EventDataTx) ABCIEvents() []abci.Event

ABCIEvents implements the eventlog.ABCIEventer interface.

func (EventDataTx) ToLegacy

func (e EventDataTx) ToLegacy() LegacyEventData

func (EventDataTx) TypeTag

func (EventDataTx) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type EventDataValidatorSetUpdates

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

func (EventDataValidatorSetUpdates) ToLegacy

func (EventDataValidatorSetUpdates) TypeTag

TypeTag implements the required method of jsontypes.Tagged.

type EventDataVote

type EventDataVote struct {
	Vote *Vote
}

func (EventDataVote) ToLegacy

func (e EventDataVote) ToLegacy() LegacyEventData

func (EventDataVote) TypeTag

func (EventDataVote) TypeTag() string

TypeTag implements the required method of jsontypes.Tagged.

type Evidence

type Evidence interface {
	ABCI() []abci.Misbehavior // forms individual evidence to be sent to the application
	Bytes() []byte            // bytes which comprise the evidence
	Hash() []byte             // hash of the evidence
	Height() int64            // height of the infraction
	String() string           // string format of the evidence
	Time() time.Time          // time of the infraction
	ValidateBasic() error     // basic consistency check

	// Implementations must support tagged encoding in JSON.
	jsontypes.Tagged
}

Evidence represents any provable malicious activity by a validator. Verification logic for each evidence is part of the evidence module.

func EvidenceFromProto

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

EvidenceFromProto is a generalized function for decoding protobuf into the evidence interface

type EvidenceList

type EvidenceList []Evidence

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

func (EvidenceList) ByteSize

func (evl EvidenceList) ByteSize() int64

ByteSize returns the total byte size of all the evidence

func (*EvidenceList) FromProto

func (evl *EvidenceList) FromProto(eviList *tmproto.EvidenceList) error

FromProto sets a protobuf EvidenceList to the given pointer.

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

func (evl EvidenceList) MarshalJSON() ([]byte, error)

func (EvidenceList) String

func (evl EvidenceList) String() string

func (EvidenceList) StringIndented

func (evl EvidenceList) StringIndented(indent string) string

StringIndented returns a string representation of the evidence.

func (EvidenceList) ToABCI

func (evl EvidenceList) ToABCI() []abci.Misbehavior

ToABCI converts the evidence list to a slice of the ABCI protobuf messages for use when communicating the evidence to an application.

func (*EvidenceList) ToProto

func (evl *EvidenceList) ToProto() (*tmproto.EvidenceList, error)

ToProto converts EvidenceList to protobuf

func (*EvidenceList) UnmarshalJSON

func (evl *EvidenceList) UnmarshalJSON(data []byte) error

type EvidenceParams

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

EvidenceParams determine how we handle evidence of malfeasance.

func DefaultEvidenceParams

func DefaultEvidenceParams() EvidenceParams

DefaultEvidenceParams returns a default EvidenceParams.

type ExtendedCommit

type ExtendedCommit struct {
	Height             int64
	Round              int32
	BlockID            BlockID
	ExtendedSignatures []ExtendedCommitSig
	// contains filtered or unexported fields
}

ExtendedCommit is similar to Commit, except that its signatures also retain their corresponding vote extensions and vote extension signatures.

func ExtendedCommitFromProto

func ExtendedCommitFromProto(ecp *tmproto.ExtendedCommit) (*ExtendedCommit, error)

ExtendedCommitFromProto constructs an ExtendedCommit from the given Protobuf representation. It returns an error if the extended commit is invalid.

func (*ExtendedCommit) BitArray

func (ec *ExtendedCommit) BitArray() *bits.BitArray

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

func (*ExtendedCommit) Clone

func (ec *ExtendedCommit) Clone() *ExtendedCommit

Clone creates a deep copy of this extended commit.

func (*ExtendedCommit) EnsureExtensions

func (ec *ExtendedCommit) EnsureExtensions() error

EnsureExtensions validates that a vote extensions signature is present for every ExtendedCommitSig in the ExtendedCommit.

func (*ExtendedCommit) GetByIndex

func (ec *ExtendedCommit) GetByIndex(valIdx int32) *Vote

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

func (*ExtendedCommit) GetExtendedVote

func (ec *ExtendedCommit) GetExtendedVote(valIndex int32) *Vote

GetExtendedVote converts the ExtendedCommitSig for the given validator index to a Vote with a vote extensions. It panics if valIndex is out of range.

func (*ExtendedCommit) GetHeight

func (ec *ExtendedCommit) GetHeight() int64

GetHeight returns height of the extended commit. Implements VoteSetReader.

func (*ExtendedCommit) GetRound

func (ec *ExtendedCommit) GetRound() int32

GetRound returns height of the extended commit. Implements VoteSetReader.

func (*ExtendedCommit) IsCommit

func (ec *ExtendedCommit) IsCommit() bool

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

func (*ExtendedCommit) Size

func (ec *ExtendedCommit) Size() int

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

func (*ExtendedCommit) StripExtensions

func (ec *ExtendedCommit) StripExtensions() bool

StripExtensions removes all VoteExtension data from an ExtendedCommit. This is useful when dealing with an ExendedCommit but vote extension data is expected to be absent.

func (*ExtendedCommit) ToCommit

func (ec *ExtendedCommit) ToCommit() *Commit

ToCommit converts an ExtendedCommit to a Commit by removing all vote extension-related fields.

func (*ExtendedCommit) ToExtendedVoteSet

func (ec *ExtendedCommit) ToExtendedVoteSet(chainID string, vals *ValidatorSet) *VoteSet

ToExtendedVoteSet constructs a VoteSet from the Commit and validator set. Panics if signatures from the ExtendedCommit can't be added to the voteset. Panics if any of the votes have invalid or absent vote extension data. Inverse of VoteSet.MakeExtendedCommit().

func (*ExtendedCommit) ToProto

func (ec *ExtendedCommit) ToProto() *tmproto.ExtendedCommit

ToProto converts ExtendedCommit to protobuf

func (*ExtendedCommit) ToVoteSet

func (ec *ExtendedCommit) ToVoteSet(chainID string, vals *ValidatorSet) *VoteSet

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

func (*ExtendedCommit) Type

func (ec *ExtendedCommit) Type() byte

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

func (*ExtendedCommit) ValidateBasic

func (ec *ExtendedCommit) ValidateBasic() error

ValidateBasic checks whether the extended commit is well-formed. Does not actually check the cryptographic signatures.

type ExtendedCommitSig

type ExtendedCommitSig struct {
	CommitSig                 // Commit signature
	Extension          []byte // Vote extension
	ExtensionSignature []byte // Vote extension signature
}

ExtendedCommitSig contains a commit signature along with its corresponding vote extension and vote extension signature.

func NewExtendedCommitSigAbsent

func NewExtendedCommitSigAbsent() ExtendedCommitSig

NewExtendedCommitSigAbsent returns new ExtendedCommitSig with BlockIDFlagAbsent. Other fields are all empty.

func (ExtendedCommitSig) EnsureExtension

func (ecs ExtendedCommitSig) EnsureExtension() error

EnsureExtensions validates that a vote extensions signature is present for this ExtendedCommitSig.

func (*ExtendedCommitSig) FromProto

func (ecs *ExtendedCommitSig) FromProto(ecsp tmproto.ExtendedCommitSig) error

FromProto populates the ExtendedCommitSig with values from the given Protobuf representation. Returns an error if the ExtendedCommitSig is invalid.

func (ExtendedCommitSig) String

func (ecs ExtendedCommitSig) String() string

String returns a string representation of an ExtendedCommitSig.

1. commit sig 2. first 6 bytes of vote extension 3. first 6 bytes of vote extension signature

func (*ExtendedCommitSig) ToProto

ToProto converts the ExtendedCommitSig to its Protobuf representation.

func (ExtendedCommitSig) ValidateBasic

func (ecs ExtendedCommitSig) ValidateBasic() error

ValidateBasic checks whether the structure is well-formed.

type GenesisDoc

type GenesisDoc struct {
	GenesisTime     time.Time          `json:"genesis_time"`
	ChainID         string             `json:"chain_id"`
	InitialHeight   int64              `json:"initial_height,string"`
	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 tendermint 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
	PubKey  crypto.PubKey
	Power   int64
	Name    string
}

GenesisValidator is an initial validator.

func (GenesisValidator) MarshalJSON

func (g GenesisValidator) MarshalJSON() ([]byte, error)

func (*GenesisValidator) UnmarshalJSON

func (g *GenesisValidator) UnmarshalJSON(data []byte) error

type HashedParams

type HashedParams struct {
	BlockMaxBytes int64
	BlockMaxGas   int64
}

HashedParams is a subset of ConsensusParams. It is amino encoded and hashed into the Header.ConsensusHash.

type Header struct {
	// basic block info
	Version version.Consensus `json:"version"`
	ChainID string            `json:"chain_id"`
	Height  int64             `json:"height,string"`
	Time    time.Time         `json:"time"`

	// prev block info
	LastBlockID BlockID `json:"last_block_id"`

	// hashes of block data
	LastCommitHash tmbytes.HexBytes `json:"last_commit_hash"` // commit from validators from the last block
	DataHash       tmbytes.HexBytes `json:"data_hash"`        // transactions

	// 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
	// see `deterministicResponseDeliverTx` to understand which parts of a tx is hashed into here
	LastResultsHash tmbytes.HexBytes `json:"last_results_hash"`

	// consensus info
	EvidenceHash    tmbytes.HexBytes `json:"evidence_hash"`    // evidence included in the block
	ProposerAddress Address          `json:"proposer_address"` // original proposer of the block
}

Header defines the structure of a Tendermint block header. NOTE: changes to the Header should be duplicated in: - header.Hash() - abci.Header - https://github.com/tendermint/tendermint/blob/master/spec/core/data_structures.md

func HeaderFromProto

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

FromProto 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 returns the hash of the header. 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 the Header with state-derived data. Call this after MakeBlock to complete the Header.

func (*Header) StringIndented

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

StringIndented returns an indented string representation of the header.

func (*Header) ToProto

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

ToProto converts Header to protobuf

func (Header) ValidateBasic

func (h Header) ValidateBasic() error

ValidateBasic performs stateless validation on a Header returning an error if any validation fails.

NOTE: Timestamp validation is subtle and handled elsewhere.

type LegacyBlock

type LegacyBlock struct {
	Header     `json:"header"`
	Data       `json:"data"`
	Evidence   LegacyEvidence `json:"evidence"`
	LastCommit *Commit        `json:"last_commit"`
}

type LegacyBlockParams

type LegacyBlockParams struct {
	MaxBytes string `json:"max_bytes,omitempty"`
	MaxGas   string `json:"max_gas,omitempty"`
}

type LegacyConsensusParams

type LegacyConsensusParams struct {
	Block     *LegacyBlockParams     `json:"block,omitempty"`
	Evidence  *LegacyEvidenceParams  `json:"evidence,omitempty"`
	Validator *types.ValidatorParams `json:"validator,omitempty"`
	Version   *LegacyVersionParams   `json:"version,omitempty"`
}

type LegacyEventData

type LegacyEventData interface {
	jsontypes.Tagged
}

type LegacyEventDataNewBlock

type LegacyEventDataNewBlock struct {
	Block            *LegacyBlock            `json:"block"`
	ResultBeginBlock abci.ResponseBeginBlock `json:"result_begin_block"`
	ResultEndBlock   LegacyResponseEndBlock  `json:"result_end_block"`
}

func (LegacyEventDataNewBlock) TypeTag

func (LegacyEventDataNewBlock) TypeTag() string

type LegacyEventDataTx

type LegacyEventDataTx struct {
	TxResult LegacyTxResult `json:"TxResult"`
}

func (LegacyEventDataTx) TypeTag

func (LegacyEventDataTx) TypeTag() string

type LegacyEvidence

type LegacyEvidence struct {
	Evidence EvidenceList `json:"evidence"`
}

type LegacyEvidenceParams

type LegacyEvidenceParams struct {
	MaxAgeNumBlocks string `json:"max_age_num_blocks,omitempty"`
	MaxAgeDuration  string `json:"max_age_duration"`
	MaxBytes        string `json:"max_bytes,omitempty"`
}

type LegacyResponseEndBlock

type LegacyResponseEndBlock struct {
	ValidatorUpdates      []abci.ValidatorUpdate `json:"validator_updates"`
	ConsensusParamUpdates *LegacyConsensusParams `json:"consensus_param_updates,omitempty"`
	Events                []abci.Event           `json:"events,omitempty"`
}

type LegacyResult

type LegacyResult struct {
	Log       string       `json:"log,omitempty"`
	GasWanted string       `json:"gas_wanted,omitempty"`
	GasUsed   string       `json:"gas_used,omitempty"`
	Events    []abci.Event `json:"events,omitempty"`
}

type LegacyTxResult

type LegacyTxResult struct {
	Height string       `json:"height,omitempty"`
	Index  uint32       `json:"index,omitempty"`
	Tx     []byte       `json:"tx,omitempty"`
	Result LegacyResult `json:"result"`
}

type LegacyVersionParams

type LegacyVersionParams struct {
	AppVersion string `json:"app_version,omitempty"`
}

type LightBlock

type LightBlock struct {
	*SignedHeader `json:"signed_header"`
	ValidatorSet  *ValidatorSet `json:"validator_set"`
}

LightBlock is a SignedHeader and a ValidatorSet. It is the basis of the light client

func LightBlockFromProto

func LightBlockFromProto(pb *tmproto.LightBlock) (*LightBlock, error)

LightBlockFromProto converts from protobuf back into the Lightblock. An error is returned if either the validator set or signed header are invalid

func (LightBlock) String

func (lb LightBlock) String() string

String returns a string representation of the LightBlock

func (LightBlock) StringIndented

func (lb LightBlock) StringIndented(indent string) string

StringIndented returns an indented string representation of the LightBlock

SignedHeader ValidatorSet

func (*LightBlock) ToProto

func (lb *LightBlock) ToProto() (*tmproto.LightBlock, error)

ToProto converts the LightBlock to protobuf

func (LightBlock) ValidateBasic

func (lb LightBlock) ValidateBasic(chainID string) error

ValidateBasic checks that the data is correct and consistent

This does no verification of the signatures

type LightClientAttackEvidence

type LightClientAttackEvidence struct {
	ConflictingBlock *LightBlock
	CommonHeight     int64 `json:",string"`

	// abci specific information
	ByzantineValidators []*Validator // validators in the validator set that misbehaved in creating the conflicting block
	TotalVotingPower    int64        `json:",string"` // total voting power of the validator set at the common height
	Timestamp           time.Time    // timestamp of the block at the common height
}

LightClientAttackEvidence is a generalized evidence that captures all forms of known attacks on a light client such that a full node can verify, propose and commit the evidence on-chain for punishment of the malicious validators. There are three forms of attacks: Lunatic, Equivocation and Amnesia. These attacks are exhaustive. You can find a more detailed overview of this at tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md

CommonHeight is used to indicate the type of attack. If the height is different to the conflicting block height, then nodes will treat this as of the Lunatic form, else it is of the Equivocation form.

func LightClientAttackEvidenceFromProto

func LightClientAttackEvidenceFromProto(lpb *tmproto.LightClientAttackEvidence) (*LightClientAttackEvidence, error)

LightClientAttackEvidenceFromProto decodes protobuf

func (*LightClientAttackEvidence) ABCI

ABCI forms an array of abci.Misbehavior for each byzantine validator

func (*LightClientAttackEvidence) Bytes

func (l *LightClientAttackEvidence) Bytes() []byte

Bytes returns the proto-encoded evidence as a byte array

func (*LightClientAttackEvidence) ConflictingHeaderIsInvalid

func (l *LightClientAttackEvidence) ConflictingHeaderIsInvalid(trustedHeader *Header) bool

ConflictingHeaderIsInvalid takes a trusted header and matches it againt a conflicting header to determine whether the conflicting header was the product of a valid state transition or not. If it is then all the deterministic fields of the header should be the same. If not, it is an invalid header and constitutes a lunatic attack.

func (*LightClientAttackEvidence) GenerateABCI

func (l *LightClientAttackEvidence) GenerateABCI(
	commonVals *ValidatorSet,
	trustedHeader *SignedHeader,
	evidenceTime time.Time,
)

GenerateABCI populates the ABCI component of the evidence: the timestamp, total voting power and byantine validators

func (*LightClientAttackEvidence) GetByzantineValidators

func (l *LightClientAttackEvidence) GetByzantineValidators(commonVals *ValidatorSet,
	trusted *SignedHeader) []*Validator

GetByzantineValidators finds out what style of attack LightClientAttackEvidence was and then works out who the malicious validators were and returns them. This is used both for forming the ByzantineValidators field and for validating that it is correct. Validators are ordered based on validator power

func (*LightClientAttackEvidence) Hash

func (l *LightClientAttackEvidence) Hash() []byte

Hash returns the hash of the header and the commonHeight. This is designed to cause hash collisions with evidence that have the same conflicting header and common height but different permutations of validator commit signatures. The reason for this is that we don't want to allow several permutations of the same evidence to be committed on chain. Ideally we commit the header with the most commit signatures (captures the most byzantine validators) but anything greater than 1/3 is sufficient. TODO: We should change the hash to include the commit, header, total voting power, byzantine validators and timestamp

func (*LightClientAttackEvidence) Height

func (l *LightClientAttackEvidence) Height() int64

Height returns the last height at which the primary provider and witness provider had the same header. We use this as the height of the infraction rather than the actual conflicting header because we know that the malicious validators were bonded at this height which is important for evidence expiry

func (*LightClientAttackEvidence) String

func (l *LightClientAttackEvidence) String() string

String returns a string representation of LightClientAttackEvidence

func (*LightClientAttackEvidence) Time

Time returns the time of the common block where the infraction leveraged off.

func (*LightClientAttackEvidence) ToProto

ToProto encodes LightClientAttackEvidence to protobuf

func (*LightClientAttackEvidence) TypeTag

func (*LightClientAttackEvidence) TypeTag() string

TypeTag implements the jsontypes.Tagged interface.

func (*LightClientAttackEvidence) ValidateABCI

func (l *LightClientAttackEvidence) ValidateABCI(
	commonVals *ValidatorSet,
	trustedHeader *SignedHeader,
	evidenceTime time.Time,
) error

ValidateABCI validates the ABCI component of the evidence by checking the timestamp, byzantine validators and total voting power all match. ABCI components are validated separately because they can be re generated if invalid.

func (*LightClientAttackEvidence) ValidateBasic

func (l *LightClientAttackEvidence) ValidateBasic() error

ValidateBasic performs basic validation such that the evidence is consistent and can now be used for verification.

type LightClientInfo

type LightClientInfo struct {
	PrimaryID         string          `json:"primaryID"`
	WitnessesID       []string        `json:"witnessesID"`
	NumPeers          int             `json:"number_of_peers,string"`
	LastTrustedHeight int64           `json:"last_trusted_height,string"`
	LastTrustedHash   tbytes.HexBytes `json:"last_trusted_hash"`
	LatestBlockTime   time.Time       `json:"latest_block_time"`
	TrustingPeriod    string          `json:"trusting_period"`
	// Boolean that reflects whether LatestBlockTime + trusting period is before
	// time.Now() (time when /status is called)
	TrustedBlockExpired bool `json:"trusted_block_expired"`
}

Info about the status of the light client

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

func (pv MockPV) ExtractIntoValidator(ctx context.Context, votingPower int64) *Validator

func (MockPV) GetPubKey

func (pv MockPV) GetPubKey(ctx context.Context) (crypto.PubKey, error)

Implements PrivValidator.

func (MockPV) SignProposal

func (pv MockPV) SignProposal(ctx context.Context, chainID string, proposal *tmproto.Proposal) error

Implements PrivValidator.

func (MockPV) SignVote

func (pv MockPV) SignVote(ctx context.Context, chainID string, vote *tmproto.Vote) error

Implements PrivValidator.

func (MockPV) String

func (pv MockPV) String() string

String returns a string representation of the MockPV.

type NodeID

type NodeID string

NodeID is a hex-encoded crypto.Address. It must be lowercased (for uniqueness) and of length 2*NodeIDByteLength.

func NewNodeID

func NewNodeID(nodeID string) (NodeID, error)

NewNodeID returns a lowercased (normalized) NodeID, or errors if the node ID is invalid.

func NodeIDFromPubKey

func NodeIDFromPubKey(pubKey crypto.PubKey) NodeID

NodeIDFromPubKey creates a node ID from a given PubKey address.

func (NodeID) AddressString

func (id NodeID) AddressString(protocolHostPort string) string

IDAddressString returns id@hostPort. It strips the leading protocol from protocolHostPort if it exists.

func (NodeID) Bytes

func (id NodeID) Bytes() ([]byte, error)

Bytes converts the node ID to its binary byte representation.

func (NodeID) Validate

func (id NodeID) Validate() error

Validate validates the NodeID.

type NodeInfo

type NodeInfo struct {
	ProtocolVersion ProtocolVersion `json:"protocol_version"`

	// Authenticate
	NodeID     NodeID `json:"id"`          // authenticated identifier
	ListenAddr string `json:"listen_addr"` // accepting incoming

	// Check compatibility.
	// Channels are HexBytes so easier to read as JSON
	Network string `json:"network"` // network/chain ID
	Version string `json:"version"` // major.minor.revision
	// FIXME: This should be changed to uint16 to be consistent with the updated channel type
	Channels bytes.HexBytes `json:"channels"` // channels this node knows about

	// ASCIIText fields
	Moniker string        `json:"moniker"` // arbitrary moniker
	Other   NodeInfoOther `json:"other"`   // other application specific data
}

NodeInfo is the basic node information exchanged between two peers during the Tendermint P2P handshake.

func NodeInfoFromProto

func NodeInfoFromProto(pb *tmp2p.NodeInfo) (NodeInfo, error)

func (*NodeInfo) AddChannel

func (info *NodeInfo) AddChannel(channel uint16)

AddChannel is used by the router when a channel is opened to add it to the node info

func (NodeInfo) CompatibleWith

func (info NodeInfo) CompatibleWith(other NodeInfo) error

CompatibleWith checks if two NodeInfo are compatible with each other. CONTRACT: two nodes are compatible if the Block version and network match and they have at least one channel in common.

func (NodeInfo) Copy

func (info NodeInfo) Copy() NodeInfo

func (NodeInfo) ID

func (info NodeInfo) ID() NodeID

ID returns the node's peer ID.

func (NodeInfo) ToProto

func (info NodeInfo) ToProto() *tmp2p.NodeInfo

func (NodeInfo) Validate

func (info NodeInfo) Validate() error

Validate checks the self-reported NodeInfo is safe. It returns an error if there are too many Channels, if there are any duplicate Channels, if the ListenAddr is malformed, or if the ListenAddr is a host name that can not be resolved to some IP. TODO: constraints for Moniker/Other? Or is that for the UI ? JAE: It needs to be done on the client, but to prevent ambiguous unicode characters, maybe it's worth sanitizing it here. In the future we might want to validate these, once we have a name-resolution system up. International clients could then use punycode (or we could use url-encoding), and we just need to be careful with how we handle that in our clients. (e.g. off by default).

type NodeInfoOther

type NodeInfoOther struct {
	TxIndex    string `json:"tx_index"`
	RPCAddress string `json:"rpc_address"`
}

NodeInfoOther is the misc. applcation specific data

type NodeKey

type NodeKey struct {
	// Canonical ID - hex-encoded pubkey's address (IDByteLength bytes)
	ID NodeID
	// Private key
	PrivKey crypto.PrivKey
}

NodeKey is the persistent peer key. It contains the nodes private key for authentication.

func GenNodeKey

func GenNodeKey() NodeKey

GenNodeKey generates a new node key.

func LoadNodeKey

func LoadNodeKey(filePath string) (NodeKey, error)

LoadNodeKey loads NodeKey located in filePath.

func LoadOrGenNodeKey

func LoadOrGenNodeKey(filePath string) (NodeKey, error)

LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If the file does not exist, it generates and saves a new NodeKey.

func (NodeKey) MarshalJSON

func (nk NodeKey) MarshalJSON() ([]byte, error)

func (NodeKey) PubKey

func (nk NodeKey) PubKey() crypto.PubKey

PubKey returns the peer's PubKey

func (NodeKey) SaveAs

func (nk NodeKey) SaveAs(filePath string) error

SaveAs persists the NodeKey to filePath.

func (*NodeKey) UnmarshalJSON

func (nk *NodeKey) UnmarshalJSON(data []byte) error

type Part

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

func PartFromProto

func PartFromProto(pb *tmproto.Part) (*Part, error)

func (*Part) String

func (part *Part) String() string

String returns a string representation of Part.

See StringIndented.

func (*Part) StringIndented

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

StringIndented returns an indented Part.

See merkle.Proof#StringIndented

func (*Part) ToProto

func (part *Part) ToProto() (*tmproto.Part, error)

func (*Part) ValidateBasic

func (part *Part) ValidateBasic() error

ValidateBasic performs basic validation.

type PartSet

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

func NewPartSetFromData

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

Returns an immutable, full PartSet from the data bytes. The data bytes are split into "partSize" chunks, and merkle tree computed. CONTRACT: partSize is greater than zero.

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

func (ps *PartSet) ByteSize() int64

func (*PartSet) Count

func (ps *PartSet) Count() uint32

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

StringShort returns a short version of String.

(Count of Total)

func (*PartSet) Total

func (ps *PartSet) Total() uint32

type PartSetHeader

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

func PartSetHeaderFromProto

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

FromProto sets a protobuf PartSetHeader to the given pointer

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

String returns a string representation of PartSetHeader.

1. total number of parts 2. first 6 bytes of the hash

func (*PartSetHeader) ToProto

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

ToProto converts PartSetHeader to protobuf

func (PartSetHeader) ValidateBasic

func (psh PartSetHeader) ValidateBasic() error

ValidateBasic performs basic validation.

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(context.Context) (crypto.PubKey, error)

	SignVote(ctx context.Context, chainID string, vote *tmproto.Vote) error
	SignProposal(ctx context.Context, chainID string, proposal *tmproto.Proposal) error
}

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

type PrivValidatorType

type PrivValidatorType uint8

PrivValidatorType defines the implemtation types.

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            tmproto.SignedMsgType
	Height          int64     `json:"height,string"`
	Round           int32     `json:"round"`     // there can not be greater than 2_147_483_647 rounds
	POLRound        int32     `json:"pol_round"` // -1 if null.
	BlockID         BlockID   `json:"block_id"`
	Timestamp       time.Time `json:"timestamp"`
	Signature       []byte    `json:"signature"`
	TxKeys          []TxKey   `json:"tx_keys"`
	Header          `json:"header"`
	LastCommit      *Commit      `json:"last_commit"`
	Evidence        EvidenceList `json:"evidence"`
	ProposerAddress Address      `json:"proposer_address"` // original proposer of the block
}

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.

func NewProposal

func NewProposal(height int64, round int32, polRound int32, blockID BlockID, ts time.Time, txKeys []TxKey, header Header, lastCommit *Commit, evidenceList EvidenceList, proposerAddress Address) *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) IsTimely

func (p *Proposal) IsTimely(recvTime time.Time, sp SynchronyParams, round int32) bool

IsTimely validates that the block timestamp is 'timely' according to the proposer-based timestamp algorithm. To evaluate if a block is timely, its timestamp is compared to the local time of the validator along with the configured Precision and MsgDelay parameters. Specifically, a proposed block timestamp is considered timely if it is satisfies the following inequalities:

localtime >= proposedBlockTime - Precision localtime <= proposedBlockTime + MsgDelay + Precision

For more information on the meaning of 'timely', see the proposer-based timestamp specification: https://github.com/tendermint/tendermint/tree/master/spec/consensus/proposer-based-timestamp

func (*Proposal) String

func (p *Proposal) String() string

String returns a string representation of the Proposal.

1. height 2. round 3. block ID 4. POL round 5. first 6 bytes of signature 6. timestamp

See BlockID#String.

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 ProtocolVersion

type ProtocolVersion struct {
	P2P   uint64 `json:"p2p,string"`
	Block uint64 `json:"block,string"`
	App   uint64 `json:"app,string"`
}

ProtocolVersion contains the protocol versions for the software.

type SignedHeader

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

	Commit *Commit `json:"commit"`
}

SignedHeader is a header along with the commits that prove it.

func SignedHeaderFromProto

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

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

func (SignedHeader) String

func (sh SignedHeader) String() string

String returns a string representation of SignedHeader.

func (SignedHeader) StringIndented

func (sh SignedHeader) StringIndented(indent string) string

StringIndented returns an indented string representation of SignedHeader.

Header Commit

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 SynchronyParams

type SynchronyParams struct {
	Precision    time.Duration `json:"precision,string"`
	MessageDelay time.Duration `json:"message_delay,string"`
}

SynchronyParams influence the validity of block timestamps. For more information on the relationship of the synchrony parameters to block validity, see the Proposer-Based Timestamps specification: https://github.com/tendermint/tendermint/blob/master/spec/consensus/proposer-based-timestamp/README.md

func DefaultSynchronyParams

func DefaultSynchronyParams() SynchronyParams

func (SynchronyParams) SynchronyParamsOrDefaults

func (s SynchronyParams) SynchronyParamsOrDefaults() SynchronyParams

SynchronyParamsOrDefaults returns the SynchronyParams, filling in any zero values with the Tendermint defined default values.

type TimeoutParams

type TimeoutParams struct {
	Propose             time.Duration `json:"propose,string"`
	ProposeDelta        time.Duration `json:"propose_delta,string"`
	Vote                time.Duration `json:"vote,string"`
	VoteDelta           time.Duration `json:"vote_delta,string"`
	Commit              time.Duration `json:"commit,string"`
	BypassCommitTimeout bool          `json:"bypass_commit_timeout"`
}

TimeoutParams configure the timings of the steps of the Tendermint consensus algorithm.

func DefaultTimeoutParams

func DefaultTimeoutParams() TimeoutParams

func (TimeoutParams) CommitTime

func (t TimeoutParams) CommitTime(ti time.Time) time.Time

CommitTime accepts ti, the time at which the consensus engine received +2/3 precommits for a block and returns the point in time at which the consensus engine should begin consensus on the next block.

func (TimeoutParams) ProposeTimeout

func (t TimeoutParams) ProposeTimeout(round int32) time.Duration

ProposeTimeout returns the amount of time to wait for a proposal.

func (TimeoutParams) TimeoutParamsOrDefaults

func (t TimeoutParams) TimeoutParamsOrDefaults() TimeoutParams

TimeoutParamsOrDefaults returns the SynchronyParams, filling in any zero values with the Tendermint defined default values.

func (TimeoutParams) VoteTimeout

func (t TimeoutParams) VoteTimeout(round int32) time.Duration

VoteTimeout returns the amount of time to wait for remaining votes after receiving any +2/3 votes.

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

func (tx Tx) Key() TxKey

Key produces a fixed-length key for use in indexing.

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 TxKey

type TxKey [sha256.Size]byte

TxKey is the fixed length array key used as an index.

func TxKeyFromProto

func TxKeyFromProto(dp *tmproto.TxKey) (TxKey, error)

TxKeyFromProto takes a protobuf representation of TxKey & returns the native type.

func TxKeysListFromProto

func TxKeysListFromProto(dps []*tmproto.TxKey) ([]TxKey, error)

func (*TxKey) ToProto

func (txKey *TxKey) ToProto() *tmproto.TxKey

ToProto converts Data to protobuf

type TxProof

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

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

func TxProofFromProto

func TxProofFromProto(pb tmproto.TxProof) (TxProof, error)

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

func (tp TxProof) ToProto() tmproto.TxProof

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 TxRecordSet

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

TxRecordSet contains indexes into an underlying set of transactions. These indexes are useful for validating and working with a list of TxRecords from the PrepareProposal response.

Only one copy of the original data is referenced by all of the indexes but a transaction may appear in multiple indexes.

func NewTxRecordSet

func NewTxRecordSet(trs []*abci.TxRecord) TxRecordSet

NewTxRecordSet constructs a new set from the given transaction records. The contents of the input transactions are shared by the set, and must not be modified during the lifetime of the set.

func (TxRecordSet) IncludedTxs

func (t TxRecordSet) IncludedTxs() []Tx

IncludedTxs returns the transactions marked for inclusion in a block. This list maintains the order that the transactions were included in the list of TxRecords that were used to construct the TxRecordSet.

func (TxRecordSet) RemovedTxs

func (t TxRecordSet) RemovedTxs() []Tx

RemovedTxs returns the transactions marked for removal by the application.

func (TxRecordSet) Validate

func (t TxRecordSet) Validate(maxSizeBytes int64, otxs Txs) error

Validate checks that the record set was correctly constructed from the original list of transactions.

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

func (txs Txs) Len() int

Txs is a slice of transactions. Sorting a Txs value orders the transactions lexicographically.

func (Txs) Less

func (txs Txs) Less(i, j int) bool

func (Txs) Proof

func (txs Txs) Proof(i int) TxProof

func (Txs) Swap

func (txs Txs) Swap(i, j int)

func (Txs) ToSliceOfBytes

func (txs Txs) ToSliceOfBytes() [][]byte

ToSliceOfBytes converts a Txs to slice of byte slices.

type Validator

type Validator struct {
	Address          Address
	PubKey           crypto.PubKey
	VotingPower      int64
	ProposerPriority int64
}

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

NewValidator returns a new validator with the given pubkey and voting power.

func ValidatorFromProto

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

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

func (*Validator) Bytes

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

Bytes computes the unique encoding of a validator with a given voting power. These are the bytes that gets hashed in consensus. It excludes address as its redundant with the pubkey. This also excludes ProposerPriority which changes every round.

func (*Validator) CompareProposerPriority

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

Returns the one with higher ProposerPriority.

func (*Validator) Copy

func (v *Validator) Copy() *Validator

Creates a new copy of the validator so we can mutate ProposerPriority. Panics if the validator is nil.

func (Validator) MarshalJSON

func (v Validator) MarshalJSON() ([]byte, error)

func (*Validator) String

func (v *Validator) String() string

String returns a string representation of String.

1. address 2. public key 3. voting power 4. proposer priority

func (*Validator) ToProto

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

ToProto converts Valiator to protobuf

func (*Validator) UnmarshalJSON

func (v *Validator) UnmarshalJSON(data []byte) error

func (*Validator) ValidateBasic

func (v *Validator) ValidateBasic() error

ValidateBasic performs basic validation.

type ValidatorInfo

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

type ValidatorParams

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

ValidatorParams restrict the public key types validators can use. 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 (val *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 represent a set of *Validator at a given height.

The validators can be fetched by address or index. The index is in order of .VotingPower, so the indices are fixed for all rounds of a given blockchain height - ie. the validators are sorted by their voting power (descending). Secondary index - .Address (ascending).

On the other hand, the .ProposerPriority of each validator and the designated .GetProposer() of a set changes every round, upon calling .IncrementProposerPriority().

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 ValidatorSetFromExistingValidators

func ValidatorSetFromExistingValidators(valz []*Validator) (*ValidatorSet, error)

ValidatorSetFromExistingValidators takes an existing array of validators and rebuilds the exact same validator set that corresponds to it without changing the proposer priority or power if any of the validators fail validate basic then an empty set is returned.

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 int32) *ValidatorSet

CopyIncrementProposerPriority increments ProposerPriority and updates the proposer on a copy, and returns it.

func (*ValidatorSet) GetByAddress

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

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

func (*ValidatorSet) GetByIndex

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

GetByIndex returns the validator's address and validator itself (copy) 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 returns the current proposer. If the validator set is empty, nil is returned.

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 returns the Merkle root hash build using validators (as leaves) in the set.

func (*ValidatorSet) IncrementProposerPriority

func (vals *ValidatorSet) IncrementProposerPriority(times int32)

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 returns true if validator set is nil or empty.

func (*ValidatorSet) Iterate

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

Iterate will run the given function over the set.

func (*ValidatorSet) RescalePriorities

func (vals *ValidatorSet) RescalePriorities(diffMax int64)

RescalePriorities rescales the priorities such that the distance between the maximum and minimum is smaller than `diffMax`. Panics if validator set is empty.

func (*ValidatorSet) Size

func (vals *ValidatorSet) Size() int

Size returns the length of the validator set.

func (*ValidatorSet) String

func (vals *ValidatorSet) String() string

String returns a string representation of ValidatorSet.

See StringIndented.

func (*ValidatorSet) StringIndented

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

StringIndented returns an intended String.

See Validator#String.

func (*ValidatorSet) ToProto

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

ToProto converts ValidatorSet to protobuf

func (*ValidatorSet) TotalVotingPower

func (vals *ValidatorSet) TotalVotingPower() int64

TotalVotingPower returns the sum of the voting powers of all validators. It recomputes the total voting power if required.

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

func (vals *ValidatorSet) ValidateBasic() error

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 and all other signatures are valid

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.

func (*ValidatorSet) VerifyCommitLightTrusting

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

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

type ValidatorsByAddress

type ValidatorsByAddress []*Validator

ValidatorsByAddress implements sort.Interface for []*Validator based on the Address field.

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 ValidatorsByVotingPower

type ValidatorsByVotingPower []*Validator

ValidatorsByVotingPower implements sort.Interface for []*Validator based on the VotingPower and Address fields.

func (ValidatorsByVotingPower) Len

func (valz ValidatorsByVotingPower) Len() int

func (ValidatorsByVotingPower) Less

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

func (ValidatorsByVotingPower) Swap

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

type VersionParams

type VersionParams struct {
	AppVersion uint64 `json:"app_version,string"`
}

func DefaultVersionParams

func DefaultVersionParams() VersionParams

type Vote

type Vote struct {
	Type               tmproto.SignedMsgType `json:"type"`
	Height             int64                 `json:"height,string"`
	Round              int32                 `json:"round"`    // assume there will not be greater than 2_147_483_647 rounds
	BlockID            BlockID               `json:"block_id"` // zero if vote is nil.
	Timestamp          time.Time             `json:"timestamp"`
	ValidatorAddress   Address               `json:"validator_address"`
	ValidatorIndex     int32                 `json:"validator_index"`
	Signature          []byte                `json:"signature"`
	Extension          []byte                `json:"extension"`
	ExtensionSignature []byte                `json:"extension_signature"`
}

Vote represents a prevote, precommit, or commit vote from validators for consensus.

func VoteFromProto

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

VoteFromProto attempts to convert the given serialization (Protobuf) type to our Vote domain type. No validation is performed on the resulting vote - this is left up to the caller to decide whether to call ValidateBasic or ValidateWithExtension.

func (*Vote) CommitSig

func (vote *Vote) CommitSig() CommitSig

CommitSig converts the Vote to a CommitSig.

func (*Vote) Copy

func (vote *Vote) Copy() *Vote

func (*Vote) EnsureExtension

func (vote *Vote) EnsureExtension() error

EnsureExtension checks for the presence of extensions signature data on precommit vote types.

func (*Vote) ExtendedCommitSig

func (vote *Vote) ExtendedCommitSig() ExtendedCommitSig

ExtendedCommitSig attempts to construct an ExtendedCommitSig from this vote. Panics if either the vote extension signature is missing or if the block ID is not either empty or complete.

func (*Vote) String

func (vote *Vote) String() string

String returns a string representation of Vote.

1. validator index 2. first 6 bytes of validator address 3. height 4. round, 5. type byte 6. type string 7. first 6 bytes of block hash 8. first 6 bytes of signature 9. first 6 bytes of vote extension 10. timestamp

func (*Vote) StripExtension

func (vote *Vote) StripExtension() bool

StripExtension removes any extension data from the vote. Useful if the chain has not enabled vote extensions. Returns true if extension data was present before stripping and false otherwise.

func (*Vote) ToProto

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

ToProto converts the handwritten type to proto generated type return type, nil if everything converts safely, otherwise nil, error

func (*Vote) ValidateBasic

func (vote *Vote) ValidateBasic() error

ValidateBasic checks whether the vote is well-formed. It does not, however, check vote extensions - for vote validation with vote extension validation, use ValidateWithExtension.

func (*Vote) Verify

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

Verify checks whether the signature associated with this vote corresponds to the given chain ID and public key. This function does not validate vote extension signatures - to do so, use VerifyWithExtension instead.

func (*Vote) VerifyExtension

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

VerifyExtension checks whether the vote extension signature corresponds to the given chain ID and public key.

func (*Vote) VerifyVoteAndExtension

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

VerifyVoteAndExtension performs the same verification as Verify, but additionally checks whether the vote extension signature corresponds to the given chain ID and public key. We only verify vote extension signatures for precommits.

type VoteSet

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

VoteSet helps collect signatures from validators at each height+round for a predefined vote type.

We need VoteSet to be able to keep track of conflicting votes when validators double-sign. Yet, we can't keep track of *all* the votes seen, as that could be a DoS attack vector.

There are two storage areas for votes. 1. voteSet.votes 2. voteSet.votesByBlock

`.votes` is the "canonical" list of votes. It always has at least one vote, if a vote from a validator had been seen at all. Usually it keeps track of the first vote seen, but when a 2/3 majority is found, votes for that get priority and are copied over from `.votesByBlock`.

`.votesByBlock` keeps track of a list of votes for a particular block. There are two ways a &blockVotes{} gets created in `.votesByBlock`. 1. the first vote seen by a validator was for the particular block. 2. a peer claims to have seen 2/3 majority for the particular block.

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

All this is memory bounded because conflicting votes only get added if a peer told us to track that block, each peer only gets to tell us 1 such block, and, there's only a limited number of peers.

NOTE: Assumes that the sum total of voting power does not exceed MaxUInt64.

func NewExtendedVoteSet

func NewExtendedVoteSet(chainID string, height int64, round int32,
	signedMsgType tmproto.SignedMsgType, valSet *ValidatorSet) *VoteSet

NewExtendedVoteSet constructs a vote set with additional vote verification logic. The VoteSet constructed with NewExtendedVoteSet verifies the vote extension data for every vote added to the set.

func NewVoteSet

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

NewVoteSet instantiates all fields of a new vote set. This constructor requires that no vote extension data be present on the votes that are added to the set.

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 int32) *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() int32

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

func (voteSet *VoteSet) List() []Vote

List returns a copy of the list of votes stored by the VoteSet.

func (*VoteSet) LogString

func (voteSet *VoteSet) LogString() string

LogString produces a logging suitable string representation of the vote set.

func (*VoteSet) MakeExtendedCommit

func (voteSet *VoteSet) MakeExtendedCommit() *ExtendedCommit

MakeExtendedCommit 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 string, blockID BlockID) error

If a peer claims that it has 2/3 majority for given blockKey, call this. NOTE: if there are too many peers, or too much peer churn, this can cause memory issues. 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

String returns a string representation of VoteSet.

See StringIndented.

func (*VoteSet) StringIndented

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

StringIndented returns an indented String.

Height Round Type Votes Votes bit array 2/3+ majority

See Vote#String.

func (*VoteSet) StringShort

func (voteSet *VoteSet) StringShort() string

StringShort returns a short representation of VoteSet.

1. height 2. round 3. signed msg type 4. first 2/3+ majority 5. fraction of voted power 6. votes bit array 7. 2/3+ majority for each peer

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[string]BlockID `json:"peer_maj_23s"`
}

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

type VoteSetReader

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

Common interface between *consensus.VoteSet and types.Commit

Jump to

Keyboard shortcuts

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