dpos

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2020 License: Apache-2.0 Imports: 25 Imported by: 5

Documentation

Index

Constants

View Source
const (

	// MaxValidatorSize indicates that the max number of validators in dpos consensus
	MaxValidatorSize = 21

	// SafeSize indicates that the least number of validators in dpos consensus
	SafeSize = MaxValidatorSize*2/3 + 1

	// ConsensusSize indicates that a confirmed block needs the least number of validators to approve
	ConsensusSize = MaxValidatorSize*2/3 + 1

	// RewardRatioDenominator is the max value of reward ratio
	RewardRatioDenominator uint64 = 100

	// ThawingEpochDuration defines that if user cancel candidates or vote, the deposit will be thawed after 4 epochs
	ThawingEpochDuration = 4

	// BlockInterval indicates that a block will be produced every 8 seconds
	BlockInterval = int64(8)

	// EpochInterval indicates that a new epoch will be elected every a day
	EpochInterval = int64(86400)

	// MaxVoteCount is the maximum number of candidates that a vote transaction could
	// include
	MaxVoteCount = 30

	// DonationRatio is the value of donation ratio for every new block reward
	DonationRatio = uint64(5)

	// PercentageDenominator is used to calculate percentage
	PercentageDenominator = uint64(100)

	// BlockCountFirstYear is the count of blocks produced per year
	BlockCountPerYear = uint64(3942000)
)

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

	// ErrWaitForPrevBlock is returned if the last block has not arrived and it is not
	// time for producing the next block.
	ErrWaitForPrevBlock = errors.New("wait for last block arrived")

	// ErrMinedFutureBlock is returned if the block is expected to be mined in the future
	ErrMinedFutureBlock = errors.New("mined the future block")

	// ErrMismatchSignerAndValidator is returned if the signer and validator is not matched
	ErrMismatchSignerAndValidator = errors.New("mismatch block signer and validator")

	// ErrInvalidBlockValidator is returned if the validator is not valid for a block
	ErrInvalidBlockValidator = errors.New("invalid block validator")

	// ErrNilBlockHeader is returned if returning a nil block header in api functions
	ErrNilBlockHeader = errors.New("nil block header returned")
)
View Source
var (
	// KeyVoteDeposit is the key of vote deposit
	KeyVoteDeposit = common.BytesToHash([]byte("vote-deposit"))

	// KeyCandidateDeposit is the key of candidates deposit
	KeyCandidateDeposit = common.BytesToHash([]byte("candidates-deposit"))

	// KeyRewardRatioNumerator is the key of block reward ration numerator indicates the percent of share validator with its delegators
	KeyRewardRatioNumerator = common.BytesToHash([]byte("reward-ratio-numerator"))

	// KeyRewardRatioNumeratorLastEpoch is the key for storing the reward ratio in
	// the last epoch.
	KeyRewardRatioNumeratorLastEpoch = common.BytesToHash([]byte("reward-ratio-last-epoch"))

	// KeyVoteLastEpoch is the vote deposit in the last epoch
	KeyVoteLastEpoch = common.BytesToHash([]byte("vote-last-epoch"))

	// KeyTotalVote is the key of total vote for each candidates
	KeyTotalVote = common.BytesToHash([]byte("total-vote"))

	// KeyFrozenAssets is the key for frozen assets for in an account
	KeyFrozenAssets = common.BytesToHash([]byte("frozen-assets"))

	// PrefixThawingAssets is the prefix recording the amount to be thawed in a specified epoch
	PrefixThawingAssets = []byte("thawing-assets")

	// KeyPreEpochSnapshotDelegateTrieRoot is the key of block number where snapshot delegate trie
	KeyPreEpochSnapshotDelegateTrieRoot = common.BytesToHash([]byte("pre-epoch-dtr"))

	// KeyValueCommonAddress is the address for some common key-value storage
	KeyValueCommonAddress = common.BigToAddress(big.NewInt(0))

	// KeySumAllocatedReward is the key of sum allocated block reward until now
	KeySumAllocatedReward = common.BytesToHash([]byte("sum-allocated-reward"))
)
View Source
var (
	// PrefixThawingAddr is the prefix thawing string of frozen account
	PrefixThawingAddr = "thawing_"
)

Functions

func AddFrozenAssets

func AddFrozenAssets(state stateDB, addr common.Address, diff common.BigInt)

AddFrozenAssets add the diff to the frozen assets of the address

func AddThawingAssets

func AddThawingAssets(state stateDB, addr common.Address, epoch int64, diff common.BigInt)

AddThawingAssets add the thawing assets of diff in the epoch field for the addr in state

func CalcCandidateTotalVotes

func CalcCandidateTotalVotes(candidateAddr common.Address, state stateDB, delegateTrie *trie.Trie) common.BigInt

CalcCandidateTotalVotes calculate the total votes for the candidates. It returns the total votes.

func CalculateEpochID

func CalculateEpochID(blockTime int64) int64

CalculateEpochID calculate the epoch ID given the block time

func CandidateTxDataValidation

func CandidateTxDataValidation(state stateDB, data types.AddCandidateTxData, candidateAddress common.Address) error

CandidateTxDataValidation will validate the candidate apply transaction before sending it

func GetAvailableBalance

func GetAvailableBalance(state stateDB, addr common.Address) common.BigInt

GetAvailableBalance get the available balance, which is the result of balance minus frozen assets.

func GetBalance

func GetBalance(state stateDB, addr common.Address) common.BigInt

GetBalance returns the balance of the address. This is simply an adapter function to convert the type from *big.Int to common.BigInt

func GetCandidateDeposit

func GetCandidateDeposit(state stateDB, addr common.Address) common.BigInt

GetCandidateDeposit get the candidates deposit of the addr from the state

func GetFrozenAssets

func GetFrozenAssets(state stateDB, addr common.Address) common.BigInt

GetFrozenAssets returns the frozen assets for an addr

func GetPreEpochSnapshotDelegateTrieRoot

func GetPreEpochSnapshotDelegateTrieRoot(state stateDB, genesis *types.Header) common.Hash

GetPreEpochSnapshotDelegateTrieRoot get the block number of snapshot delegate trie

func GetRewardRatioNumerator

func GetRewardRatioNumerator(state stateDB, addr common.Address) uint64

GetRewardRatioNumerator get the reward ratio for a candidates for the addr in state. The value is used in calculating block reward for miner and his delegator

func GetRewardRatioNumeratorLastEpoch

func GetRewardRatioNumeratorLastEpoch(state stateDB, addr common.Address) uint64

GetRewardRatioNumeratorLastEpoch get the rewardRatio for the validator in the last epoch

func GetThawingAssets

func GetThawingAssets(state stateDB, addr common.Address, epoch int64) common.BigInt

GetThawingAssets return the thawing asset amount of the address in a certain epoch

func GetVoteDeposit

func GetVoteDeposit(state stateDB, addr common.Address) common.BigInt

GetVoteDeposit get the vote deposit of the addr from the state

func GetVoteLastEpoch

func GetVoteLastEpoch(state stateDB, addr common.Address) common.BigInt

GetVoteLastEpoch get the vote deposit in the last epoch

func HasVoted

func HasVoted(delegatorAddress common.Address, header *types.Header, diskDB ethdb.Database) bool

HasVoted will check whether the provided delegator address is voted

func IsCandidate

func IsCandidate(candidateAddress common.Address, header *types.Header, diskDB ethdb.Database) bool

IsCandidate will check whether or not the given address is a candidate address

func NextSlot

func NextSlot(now int64) int64

NextSlot calculate the next block time

func PrevSlot

func PrevSlot(now int64) int64

PrevSlot calculate the last block time

func ProcessAddCandidate

func ProcessAddCandidate(state stateDB, ctx *types.DposContext, addr common.Address, deposit common.BigInt,
	rewardRatio uint64) error

ProcessAddCandidate adds a candidates to the DposContext and updated the related fields in stateDB

func ProcessCancelCandidate

func ProcessCancelCandidate(state stateDB, ctx *types.DposContext, addr common.Address, time int64) error

ProcessCancelCandidate cancel the addr being an candidates

func ProcessCancelVote

func ProcessCancelVote(state stateDB, ctx *types.DposContext, addr common.Address, time int64) error

ProcessCancelVote process the cancel vote request for state and dpos context

func ProcessVote

func ProcessVote(state stateDB, ctx *types.DposContext, addr common.Address, deposit common.BigInt,
	candidates []common.Address, time int64) (int, error)

ProcessVote process the process request for state and dpos context

func SetCandidateDeposit

func SetCandidateDeposit(state stateDB, addr common.Address, deposit common.BigInt)

SetCandidateDeposit set the candidates deposit of the addr in the state

func SetFrozenAssets

func SetFrozenAssets(state stateDB, addr common.Address, value common.BigInt)

SetFrozenAssets set the frozen assets for an addr

func SetRewardRatioNumerator

func SetRewardRatioNumerator(state stateDB, addr common.Address, value uint64)

SetRewardRatioNumerator set the CandidateRewardRatioNumerator for the addr in state

func SetRewardRatioNumeratorLastEpoch

func SetRewardRatioNumeratorLastEpoch(state stateDB, addr common.Address, value uint64)

SetRewardRatioNumeratorLastEpoch set the rewardRatio for the validator in the last epoch

func SetThawingAssets

func SetThawingAssets(state stateDB, addr common.Address, epoch int64, value common.BigInt)

SetThawingAssets set the thawing assets in the epoch field for the addr in state

func SetVoteDeposit

func SetVoteDeposit(state stateDB, addr common.Address, deposit common.BigInt)

SetVoteDeposit set the vote deposit of the addr in the state

func SetVoteLastEpoch

func SetVoteLastEpoch(state stateDB, addr common.Address, value common.BigInt)

SetVoteLastEpoch set the vote epoch in the last epoch

func SubFrozenAssets

func SubFrozenAssets(state stateDB, addr common.Address, diff common.BigInt) error

SubFrozenAssets sub the diff from the frozen assets of the address

func VoteTxDepositValidation

func VoteTxDepositValidation(state stateDB, delegatorAddress common.Address, voteData types.VoteTxData) error

VoteTxDepositValidation will validate the vote transaction before sending it

Types

type API

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

API is a user facing RPC API to allow controlling the delegate and voting mechanisms of the delegated-proof-of-stake

func (*API) GetConfirmedBlockNumber

func (api *API) GetConfirmedBlockNumber() (*big.Int, error)

GetConfirmedBlockNumber retrieves the latest irreversible block

type APIHelper

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

APIHelper is the api helper for dpos related api commands

func NewAPIHelper

func NewAPIHelper(bc BlockChain) *APIHelper

NewAPIHelper creates a new api helper

func (*APIHelper) CalcValidatorDistributionInRange

func (ah *APIHelper) CalcValidatorDistributionInRange(validator common.Address, endHeader *types.Header, size uint64) ([]ValueEntry, error)

CalcValidatorDistributionInRange calculate the validator reward distribution to delegators within a range. Ending with endHash and covers number of (size) blocks

  1. Split the full interval by elect blocks.
  2. For each interval 2.1 calculate validator rewards 2.2 calculate validator vote stats (in the last epoch) 2.3 find reward ratio of validator (in the last epoch) 2.4 split shared rewards among delegators and add to result
  3. return result

func (*APIHelper) CandidateInfo

func (ah *APIHelper) CandidateInfo(addr common.Address, header *types.Header) (CandidateInfo, error)

CandidateInfo return the candidate info of a given address Return an error if the given addr is not a candidate

func (*APIHelper) CandidateVoteStat

func (ah *APIHelper) CandidateVoteStat(addr common.Address, header *types.Header) ([]ValueEntry, error)

CandidateVoteStat return the vote stat for a candidate. The result is a list of structure of address and vote value, which is sorted in descending votes. Return an error if the given address is not a candidate.

func (*APIHelper) GetCandidateDeposit

func (ah *APIHelper) GetCandidateDeposit(addr common.Address, header *types.Header) (common.BigInt, error)

GetCandidateDeposit return the candidate deposit of the address in the given header. Return an error if the given address is not a candidate.

func (*APIHelper) GetCandidates

func (ah *APIHelper) GetCandidates(header *types.Header) ([]common.Address, error)

GetCandidates return the candidate list based on the block header provided.

func (*APIHelper) GetValidatorInfo

func (ah *APIHelper) GetValidatorInfo(addr common.Address, header *types.Header) (ValidatorInfo, error)

GetValidatorInfo returns the validator info for an address with a given header. If the given addr is not a validator, return an error.

func (*APIHelper) GetValidatorTotalVotes

func (ah *APIHelper) GetValidatorTotalVotes(addr common.Address, header *types.Header) (common.BigInt, error)

GetValidatorTotalVotes returns the total votes for a validator in the last epoch. The votes include the deposit from himself and votes from delegator. If the given address is not a validator, return an error.

func (*APIHelper) GetValidators

func (ah *APIHelper) GetValidators(header *types.Header) ([]common.Address, error)

GetValidators return the validator list based on the block header provided

func (*APIHelper) GetVoteDeposit

func (ah *APIHelper) GetVoteDeposit(addr common.Address, header *types.Header) (common.BigInt, error)

GetVoteDeposit return the vote deposit of a given delegator address

func (*APIHelper) GetVotedCandidates

func (ah *APIHelper) GetVotedCandidates(addr common.Address, header *types.Header) ([]common.Address, error)

GetVotedCandidates return the voted candidates for an address in the specified header

func (*APIHelper) ValidatorRewardInRange

func (ah *APIHelper) ValidatorRewardInRange(validator common.Address, endHeader *types.Header, size uint64) (common.BigInt, error)

ValidatorRewardInRange return the validator reward within range start and end. The donation has already been subtracted from the rewards

func (*APIHelper) ValidatorVoteStat

func (ah *APIHelper) ValidatorVoteStat(addr common.Address, header *types.Header) ([]ValueEntry, error)

ValidatorVoteStat return the vote stat for a validator in last epoch. First identify whether the given address is a validator, and then call validatorVoteStat to obtain the vote stat from last elect block.

type BlockChain

type BlockChain interface {
	GetHeaderByNumber(bn uint64) *types.Header
	GetHeaderByHash(hash common.Hash) *types.Header
	GetHeader(hash common.Hash, bn uint64) *types.Header
	StateAt(hash common.Hash) (*state.StateDB, error)
	DposCtxAt(root *types.DposContextRoot) (*types.DposContext, error)
}

BlockChain is the interface for the blockchain backend for api helper

type CandidateInfo

type CandidateInfo struct {
	Deposit     common.BigInt
	TotalVotes  common.BigInt
	RewardRatio uint64
}

CandidateInfo is the structure for candidate information

type Dpos

type Dpos struct {
	Mode Mode
	// contains filtered or unexported fields
}

Dpos consensus engine

func New

func New(config *params.DposConfig, db ethdb.Database) *Dpos

New creates a dpos consensus engine

func NewDposFaker

func NewDposFaker() *Dpos

NewDposFaker create fake dpos for test

func (*Dpos) APIs

func (d *Dpos) APIs(chain consensus.ChainReader) []rpc.API

APIs implemented Engine interface which includes DPOS API

func (*Dpos) Author

func (d *Dpos) Author(header *types.Header) (common.Address, error)

Author return the address who produced the block

func (*Dpos) Authorize

func (d *Dpos) Authorize(signer common.Address, signFn SignerFn)

Authorize register the miner address and signature func when node start

func (*Dpos) CalcDifficulty

func (d *Dpos) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int

CalcDifficulty return a constant value for dpos consensus engine

func (*Dpos) CheckValidator

func (d *Dpos) CheckValidator(lastBlock *types.Block, now int64) error

CheckValidator check the given block whether has a right validator to produce

func (*Dpos) Close

func (d *Dpos) Close() error

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

func (*Dpos) Coinbase

func (d *Dpos) Coinbase(header *types.Header) (common.Address, error)

Coinbase return the address who should receive the award

func (*Dpos) Finalize

func (d *Dpos) Finalize(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction,
	uncles []*types.Header, receipts []*types.Receipt, dposContext *types.DposContext) (*types.Block, error)

Finalize implements consensus.Engine, commit state、calculate block award and update some context

func (*Dpos) Prepare

func (d *Dpos) Prepare(chain consensus.ChainReader, header *types.Header) error

Prepare implements consensus.Engine, assembly some basic fields into header

func (*Dpos) Seal

func (d *Dpos) Seal(chain consensus.ChainReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

Seal implements consensus.Engine, sign the given block and return it

func (*Dpos) SealHash

func (d *Dpos) SealHash(header *types.Header) common.Hash

SealHash implements consensus.Engine, returns the hash of a block prior to it being sealed.

func (*Dpos) VerifyHeader

func (d *Dpos) VerifyHeader(chain consensus.ChainReader, header *types.Header, seal bool) error

VerifyHeader check the given header whether it's fit for dpos engine

func (*Dpos) VerifyHeaders

func (d *Dpos) VerifyHeaders(chain consensus.ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

VerifyHeaders verify a batch of headers

func (*Dpos) VerifySeal

func (d *Dpos) VerifySeal(chain consensus.ChainReader, header *types.Header) error

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

func (*Dpos) VerifyUncles

func (d *Dpos) VerifyUncles(chain consensus.ChainReader, block *types.Block) error

VerifyUncles implements consensus.Engine, returning an error if the block has uncles, because dpos engine doesn't support uncles.

type EpochContext

type EpochContext struct {
	TimeStamp   int64
	DposContext *types.DposContext
	// contains filtered or unexported fields
}

EpochContext define current epoch context for dpos consensus

type Mode

type Mode uint

Mode is dpos consensus engine work mode

const (
	// ModeNormal is the default work mode
	ModeNormal Mode = iota

	// ModeFake is fake mode skipping verify(Header/Uncle/DposState) logic
	ModeFake
)

type SignerFn

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

SignerFn is the function for signature

type ValidatorInfo

type ValidatorInfo struct {
	TotalVotes  common.BigInt
	RewardRatio uint64
	MinedCount  int64
	EpochID     int64
}

ValidatorInfo is the structure for validator information. Note that in this structure, reward ratio and votes are stats from the last epoch.

type ValueEntry

type ValueEntry struct {
	Addr  common.Address
	Value common.BigInt
}

ValueEntry is an entry for a a certain value for an address

Jump to

Keyboard shortcuts

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