bor

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2021 License: GPL-3.0 Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxTotalVotingPower      = int64(math.MaxInt64) / 8
	PriorityWindowSizeFactor = 2
)

Variables

View Source
var (

	// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
	// the previous block's timestamp + the minimum block period.
	ErrInvalidTimestamp = errors.New("invalid timestamp")
)

Various error messages to mark blocks invalid. These should be private to prevent engine specific errors from being referenced in the remainder of the codebase, inherently breaking if the engine is swapped out. Please put common error types into the consensus package.

View Source
var (
	// MaxCheckpointLength is the maximum number of blocks that can be requested for constructing a checkpoint root hash
	MaxCheckpointLength = uint64(math.Pow(2, 15))
)

Functions

func BorRLP

func BorRLP(header *types.Header) []byte

BorRLP returns the rlp bytes which needs to be signed for the bor sealing. The RLP to sign consists of the entire header apart from the 65 byte signature contained at the end of the extra data.

Note, the method requires the extra data to be at least 65 bytes, otherwise it panics. This is done to avoid accidentally using both forms (signature present or not), which could be abused to produce different hashes for the same header.

func CalcProducerDelay

func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64

CalcProducerDelay is the block delay algorithm based on block time, period, producerDelay and turn-ness of a signer

func IsErrTooMuchChange

func IsErrTooMuchChange(err error) bool

func SealHash

func SealHash(header *types.Header) (hash common.Hash)

SealHash returns the hash of a block prior to it being sealed.

func ValidatorListString

func ValidatorListString(vals []*Validator) string

ValidatorListString returns a prettified validator list for logging purposes.

Types

type API

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

API is a user facing RPC API to allow controlling the signer and voting mechanisms of the proof-of-authority scheme.

func (*API) GetAuthor added in v0.2.7

func (api *API) GetAuthor(number *rpc.BlockNumber) (*common.Address, error)

GetAuthor retrieves the author a block.

func (*API) GetCurrentProposer

func (api *API) GetCurrentProposer() (common.Address, error)

GetCurrentProposer gets the current proposer

func (*API) GetCurrentValidators

func (api *API) GetCurrentValidators() ([]*Validator, error)

GetCurrentValidators gets the current validators

func (*API) GetRootHash added in v0.2.7

func (api *API) GetRootHash(start uint64, end uint64) (string, error)

GetRootHash returns the merkle root of the start to end block headers

func (*API) GetSigners

func (api *API) GetSigners(number *rpc.BlockNumber) ([]common.Address, error)

GetSigners retrieves the list of authorized signers at the specified block.

func (*API) GetSignersAtHash

func (api *API) GetSignersAtHash(hash common.Hash) ([]common.Address, error)

GetSignersAtHash retrieves the list of authorized signers at the specified block.

func (*API) GetSnapshot

func (api *API) GetSnapshot(number *rpc.BlockNumber) (*Snapshot, error)

GetSnapshot retrieves the state snapshot at a given block.

func (*API) GetSnapshotAtHash

func (api *API) GetSnapshotAtHash(hash common.Hash) (*Snapshot, error)

GetSnapshotAtHash retrieves the state snapshot at a given block.

type BlockTooSoonError added in v0.2.7

type BlockTooSoonError struct {
	Number     uint64
	Succession int
}

func (*BlockTooSoonError) Error added in v0.2.7

func (e *BlockTooSoonError) Error() string

type Bor

type Bor struct {
	GenesisContractsClient *GenesisContractsClient

	HeimdallClient  IHeimdallClient
	WithoutHeimdall bool
	// contains filtered or unexported fields
}

Bor is the matic-bor consensus engine

func New

func New(
	chainConfig *params.ChainConfig,
	db ethdb.Database,
	ethAPI *ethapi.PublicBlockChainAPI,
	heimdallURL string,
	withoutHeimdall bool,
) *Bor

New creates a Matic Bor consensus engine.

func (*Bor) APIs

func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API

APIs implements consensus.Engine, returning the user facing RPC API to allow controlling the signer voting.

func (*Bor) Author

func (c *Bor) Author(header *types.Header) (common.Address, error)

Author implements consensus.Engine, returning the Ethereum address recovered from the signature in the header's extra-data section.

func (*Bor) Authorize

func (c *Bor) Authorize(signer common.Address, signFn SignerFn)

Authorize injects a private key into the consensus engine to mint new blocks with.

func (*Bor) CalcDifficulty

func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int

CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty that a new block should have based on the previous blocks in the chain and the current signer.

func (*Bor) Close

func (c *Bor) Close() error

Close implements consensus.Engine. It's a noop for bor as there are no background threads.

func (*Bor) CommitStates

func (c *Bor) CommitStates(
	state *state.StateDB,
	header *types.Header,
	chain chainContext,
) ([]*types.StateSyncData, error)

CommitStates commit states

func (*Bor) Finalize

func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header)

Finalize implements consensus.Engine, ensuring no uncles are set, nor block rewards given.

func (*Bor) FinalizeAndAssemble

func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)

FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, nor block rewards given, and returns the final block.

func (*Bor) GetCurrentSpan

func (c *Bor) GetCurrentSpan(headerHash common.Hash) (*Span, error)

GetCurrentSpan get current span from contract

func (*Bor) GetCurrentValidators

func (c *Bor) GetCurrentValidators(headerHash common.Hash, blockNumber uint64) ([]*Validator, error)

GetCurrentValidators get current validators

func (*Bor) GetPendingStateProposals

func (c *Bor) GetPendingStateProposals(snapshotNumber uint64) ([]*big.Int, error)

GetPendingStateProposals get pending state proposals

func (*Bor) Prepare

func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error

Prepare implements consensus.Engine, preparing all the consensus fields of the header for running the transactions on top.

func (*Bor) Seal

func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

Seal implements consensus.Engine, attempting to create a sealed block using the local signing credentials.

func (*Bor) SealHash

func (c *Bor) SealHash(header *types.Header) common.Hash

SealHash returns the hash of a block prior to it being sealed.

func (*Bor) SetHeimdallClient added in v0.2.7

func (c *Bor) SetHeimdallClient(h IHeimdallClient)

func (*Bor) VerifyHeader

func (c *Bor) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error

VerifyHeader checks whether a header conforms to the consensus rules.

func (*Bor) VerifyHeaders

func (c *Bor) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The method returns a quit channel to abort the operations and a results channel to retrieve the async verifications (the order is that of the input slice).

func (*Bor) VerifySeal

func (c *Bor) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error

VerifySeal implements consensus.Engine, checking whether the signature contained in the header satisfies the consensus protocol requirements.

func (*Bor) VerifyUncles

func (c *Bor) VerifyUncles(chain consensus.ChainReader, block *types.Block) error

VerifyUncles implements consensus.Engine, always returning an error for any uncles as this consensus mechanism doesn't permit uncles.

type EventRecord

type EventRecord struct {
	ID       uint64         `json:"id" yaml:"id"`
	Contract common.Address `json:"contract" yaml:"contract"`
	Data     hexutil.Bytes  `json:"data" yaml:"data"`
	TxHash   common.Hash    `json:"tx_hash" yaml:"tx_hash"`
	LogIndex uint64         `json:"log_index" yaml:"log_index"`
	ChainID  string         `json:"bor_chain_id" yaml:"bor_chain_id"`
}

EventRecord represents state record

type EventRecordWithTime added in v0.2.7

type EventRecordWithTime struct {
	EventRecord
	Time time.Time `json:"record_time" yaml:"record_time"`
}

func (*EventRecordWithTime) BuildEventRecord added in v0.2.7

func (e *EventRecordWithTime) BuildEventRecord() *EventRecord

func (*EventRecordWithTime) String added in v0.2.7

func (e *EventRecordWithTime) String() string

String returns the string representatin of span

type GenesisContractsClient added in v0.2.7

type GenesisContractsClient struct {
	ValidatorContract     string
	StateReceiverContract string
	// contains filtered or unexported fields
}

func NewGenesisContractsClient added in v0.2.7

func NewGenesisContractsClient(
	chainConfig *params.ChainConfig,
	validatorContract,
	stateReceiverContract string,
	ethAPI *ethapi.PublicBlockChainAPI,
) *GenesisContractsClient

func (*GenesisContractsClient) CommitState added in v0.2.7

func (gc *GenesisContractsClient) CommitState(
	event *EventRecordWithTime,
	state *state.StateDB,
	header *types.Header,
	chCtx chainContext,
) error

func (*GenesisContractsClient) LastStateId added in v0.2.7

func (gc *GenesisContractsClient) LastStateId(snapshotNumber uint64) (*big.Int, error)

type HeimdallClient added in v0.2.7

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

func NewHeimdallClient added in v0.2.7

func NewHeimdallClient(urlString string) (*HeimdallClient, error)

func (*HeimdallClient) Fetch added in v0.2.7

func (h *HeimdallClient) Fetch(rawPath string, rawQuery string) (*ResponseWithHeight, error)

Fetch fetches response from heimdall

func (*HeimdallClient) FetchStateSyncEvents added in v0.2.7

func (h *HeimdallClient) FetchStateSyncEvents(fromID uint64, to int64) ([]*EventRecordWithTime, error)

func (*HeimdallClient) FetchWithRetry added in v0.2.7

func (h *HeimdallClient) FetchWithRetry(rawPath string, rawQuery string) (*ResponseWithHeight, error)

FetchWithRetry returns data from heimdall with retry

type HeimdallSpan

type HeimdallSpan struct {
	Span
	ValidatorSet      ValidatorSet `json:"validator_set" yaml:"validator_set"`
	SelectedProducers []Validator  `json:"selected_producers" yaml:"selected_producers"`
	ChainID           string       `json:"bor_chain_id" yaml:"bor_chain_id"`
}

HeimdallSpan represents span from heimdall APIs

type IHeimdallClient added in v0.2.7

type IHeimdallClient interface {
	Fetch(path string, query string) (*ResponseWithHeight, error)
	FetchWithRetry(path string, query string) (*ResponseWithHeight, error)
	FetchStateSyncEvents(fromID uint64, to int64) ([]*EventRecordWithTime, error)
}

type InvalidStartEndBlockError added in v0.2.7

type InvalidStartEndBlockError struct {
	Start         uint64
	End           uint64
	CurrentHeader uint64
}

func (*InvalidStartEndBlockError) Error added in v0.2.7

func (e *InvalidStartEndBlockError) Error() string

type InvalidStateReceivedError added in v0.2.7

type InvalidStateReceivedError struct {
	Number      uint64
	LastStateID uint64
	To          *time.Time
	Event       *EventRecordWithTime
}

func (*InvalidStateReceivedError) Error added in v0.2.7

func (e *InvalidStateReceivedError) Error() string

type MaxCheckpointLengthExceededError added in v0.2.7

type MaxCheckpointLengthExceededError struct {
	Start uint64
	End   uint64
}

func (*MaxCheckpointLengthExceededError) Error added in v0.2.7

type MinimalVal

type MinimalVal struct {
	ID          uint64         `json:"ID"`
	VotingPower uint64         `json:"power"` // TODO add 10^-18 here so that we dont overflow easily
	Signer      common.Address `json:"signer"`
}

MinimalVal is the minimal validator representation Used to send validator information to bor validator contract

func SortMinimalValByAddress

func SortMinimalValByAddress(a []MinimalVal) []MinimalVal

SortMinimalValByAddress sorts validators

func ValidatorsToMinimalValidators

func ValidatorsToMinimalValidators(vals []Validator) (minVals []MinimalVal)

ValidatorsToMinimalValidators converts array of validators to minimal validators

type MismatchingValidatorsError added in v0.2.7

type MismatchingValidatorsError struct {
	Number             uint64
	ValidatorSetSnap   []byte
	ValidatorSetHeader []byte
}

MismatchingValidatorsError is returned if a last block in sprint contains a list of validators different from the one that local node calculated

func (*MismatchingValidatorsError) Error added in v0.2.7

type ResponseWithHeight

type ResponseWithHeight struct {
	Height string          `json:"height"`
	Result json.RawMessage `json:"result"`
}

ResponseWithHeight defines a response object type that wraps an original response with a height.

type SignerFn

type SignerFn func(accounts.Account, string, []byte) ([]byte, error)

SignerFn is a signer callback function to request a header to be signed by a backing account.

type Snapshot

type Snapshot struct {
	Number       uint64                    `json:"number"`       // Block number where the snapshot was created
	Hash         common.Hash               `json:"hash"`         // Block hash where the snapshot was created
	ValidatorSet *ValidatorSet             `json:"validatorSet"` // Validator set at this moment
	Recents      map[uint64]common.Address `json:"recents"`      // Set of recent signers for spam protections
	// contains filtered or unexported fields
}

Snapshot is the state of the authorization voting at a given point in time.

func (*Snapshot) Difficulty added in v0.2.7

func (s *Snapshot) Difficulty(signer common.Address) uint64

Difficulty returns the difficulty for a particular signer at the current snapshot number

func (*Snapshot) GetSignerSuccessionNumber added in v0.2.7

func (s *Snapshot) GetSignerSuccessionNumber(signer common.Address) (int, error)

GetSignerSuccessionNumber returns the relative position of signer in terms of the in-turn proposer

type Span

type Span struct {
	ID         uint64 `json:"span_id" yaml:"span_id"`
	StartBlock uint64 `json:"start_block" yaml:"start_block"`
	EndBlock   uint64 `json:"end_block" yaml:"end_block"`
}

Span represents a current bor span

type TotalVotingPowerExceededError added in v0.2.7

type TotalVotingPowerExceededError struct {
	Sum        int64
	Validators []*Validator
}

TotalVotingPowerExceededError is returned when the maximum allowed total voting power is exceeded

func (*TotalVotingPowerExceededError) Error added in v0.2.7

type UnauthorizedProposerError added in v0.2.7

type UnauthorizedProposerError struct {
	Number   uint64
	Proposer []byte
}

UnauthorizedProposerError is returned if a header is [being] signed by an unauthorized entity.

func (*UnauthorizedProposerError) Error added in v0.2.7

func (e *UnauthorizedProposerError) Error() string

type UnauthorizedSignerError added in v0.2.7

type UnauthorizedSignerError struct {
	Number uint64
	Signer []byte
}

UnauthorizedSignerError is returned if a header is [being] signed by an unauthorized entity.

func (*UnauthorizedSignerError) Error added in v0.2.7

func (e *UnauthorizedSignerError) Error() string

type Validator

type Validator struct {
	ID               uint64         `json:"ID"`
	Address          common.Address `json:"signer"`
	VotingPower      int64          `json:"power"`
	ProposerPriority int64          `json:"accum"`
}

Validator represets Volatile state for each Validator

func NewValidator

func NewValidator(address common.Address, votingPower int64) *Validator

NewValidator creates new validator

func ParseValidators

func ParseValidators(validatorsBytes []byte) ([]*Validator, error)

ParseValidators returns validator set bytes

func (*Validator) Cmp added in v0.2.7

func (v *Validator) Cmp(other *Validator) *Validator

Cmp returns the one validator with a higher ProposerPriority. If ProposerPriority is same, it returns the validator with lexicographically smaller address

func (*Validator) Copy

func (v *Validator) Copy() *Validator

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

func (*Validator) HeaderBytes

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

HeaderBytes return header bytes

func (*Validator) MinimalVal

func (v *Validator) MinimalVal() MinimalVal

MinimalVal returns block number of last validator update

func (*Validator) PowerBytes

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

PowerBytes return power bytes

func (*Validator) String

func (v *Validator) String() string

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 .Address, so the indices are fixed for all rounds of a given blockchain height - ie. the validators are sorted by their address. 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.

func (*ValidatorSet) Copy

func (vals *ValidatorSet) Copy() *ValidatorSet

Copy each validator into a new ValidatorSet.

func (*ValidatorSet) CopyIncrementProposerPriority

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

Increment ProposerPriority and update the proposer on a copy, and return it.

func (*ValidatorSet) GetByAddress

func (vals *ValidatorSet) GetByAddress(address common.Address) (index int, val *Validator)

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

func (*ValidatorSet) GetByIndex

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

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

func (*ValidatorSet) GetProposer

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

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

func (vals *ValidatorSet) IncrementProposerPriority(times int)

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

func (*ValidatorSet) IsNilOrEmpty

func (vals *ValidatorSet) IsNilOrEmpty() bool

Nil or empty validator sets are invalid.

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)

func (*ValidatorSet) Size

func (vals *ValidatorSet) Size() int

Size returns the length of the validator set.

func (*ValidatorSet) String

func (vals *ValidatorSet) String() string

func (*ValidatorSet) StringIndented

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

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.

type ValidatorsByAddress

type ValidatorsByAddress []*Validator

Sort validators by address.

func (ValidatorsByAddress) Len

func (valz ValidatorsByAddress) Len() int

func (ValidatorsByAddress) Less

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

func (ValidatorsByAddress) Swap

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

type WrongDifficultyError added in v0.2.7

type WrongDifficultyError struct {
	Number   uint64
	Expected uint64
	Actual   uint64
	Signer   []byte
}

WrongDifficultyError is returned if the difficulty of a block doesn't match the turn of the signer.

func (*WrongDifficultyError) Error added in v0.2.7

func (e *WrongDifficultyError) Error() string

Jump to

Keyboard shortcuts

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