You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
685 lines
22 KiB
685 lines
22 KiB
8 months ago
|
package wiki
|
||
4 years ago
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"math/big"
|
||
|
"sync"
|
||
|
|
||
|
"github.com/ethereum/go-ethereum/common"
|
||
8 months ago
|
"github.com/woop-chain/woop/block"
|
||
|
"github.com/woop-chain/woop/consensus/quorum"
|
||
|
"github.com/woop-chain/woop/core/rawdb"
|
||
|
"github.com/woop-chain/woop/core/state"
|
||
|
"github.com/woop-chain/woop/core/types"
|
||
|
"github.com/woop-chain/woop/eth/rpc"
|
||
|
"github.com/woop-chain/woop/internal/chain"
|
||
|
internalCommon "github.com/woop-chain/woop/internal/common"
|
||
|
"github.com/woop-chain/woop/numeric"
|
||
|
commonRPC "github.com/woop-chain/woop/rpc/common"
|
||
|
"github.com/woop-chain/woop/shard"
|
||
|
"github.com/woop-chain/woop/shard/committee"
|
||
|
"github.com/woop-chain/woop/staking/availability"
|
||
|
"github.com/woop-chain/woop/staking/effective"
|
||
|
staking "github.com/woop-chain/woop/staking/types"
|
||
4 years ago
|
"github.com/pkg/errors"
|
||
|
)
|
||
|
|
||
|
var (
|
||
4 years ago
|
zero = numeric.ZeroDec()
|
||
|
bigZero = big.NewInt(0)
|
||
4 years ago
|
)
|
||
|
|
||
8 months ago
|
func (wiki *Woop) readAndUpdateRawStakes(
|
||
4 years ago
|
epoch *big.Int,
|
||
|
decider quorum.Decider,
|
||
|
comm shard.Committee,
|
||
|
rawStakes []effective.SlotPurchase,
|
||
|
validatorSpreads map[common.Address]numeric.Dec,
|
||
|
) []effective.SlotPurchase {
|
||
|
for i := range comm.Slots {
|
||
|
slot := comm.Slots[i]
|
||
|
slotAddr := slot.EcdsaAddress
|
||
|
slotKey := slot.BLSPublicKey
|
||
|
spread, ok := validatorSpreads[slotAddr]
|
||
|
if !ok {
|
||
8 months ago
|
snapshot, err := wiki.BlockChain.ReadValidatorSnapshotAtEpoch(epoch, slotAddr)
|
||
4 years ago
|
if err != nil {
|
||
|
continue
|
||
|
}
|
||
3 years ago
|
spread = snapshot.RawStakePerSlot()
|
||
4 years ago
|
validatorSpreads[slotAddr] = spread
|
||
|
}
|
||
|
|
||
|
commonRPC.SetRawStake(decider, slotKey, spread)
|
||
|
// add entry to array for median calculation
|
||
|
rawStakes = append(rawStakes, effective.SlotPurchase{
|
||
|
Addr: slotAddr,
|
||
|
Key: slotKey,
|
||
|
RawStake: spread,
|
||
|
EPoSStake: spread,
|
||
|
})
|
||
|
}
|
||
|
return rawStakes
|
||
|
}
|
||
|
|
||
8 months ago
|
func (wiki *Woop) getSuperCommittees() (*quorum.Transition, error) {
|
||
|
nowE := wiki.BlockChain.CurrentHeader().Epoch()
|
||
4 years ago
|
|
||
8 months ago
|
if wiki.BlockChain.CurrentHeader().IsLastBlockInEpoch() {
|
||
4 years ago
|
// current epoch is current header epoch + 1 if the header was last block of prev epoch
|
||
|
nowE = new(big.Int).Add(nowE, common.Big1)
|
||
|
}
|
||
4 years ago
|
thenE := new(big.Int).Sub(nowE, common.Big1)
|
||
|
|
||
|
var (
|
||
|
nowCommittee, prevCommittee *shard.State
|
||
|
err error
|
||
|
)
|
||
8 months ago
|
nowCommittee, err = wiki.BlockChain.ReadShardState(nowE)
|
||
4 years ago
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
8 months ago
|
prevCommittee, err = wiki.BlockChain.ReadShardState(thenE)
|
||
4 years ago
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
stakedSlotsNow, stakedSlotsThen :=
|
||
|
shard.ExternalSlotsAvailableForEpoch(nowE),
|
||
|
shard.ExternalSlotsAvailableForEpoch(thenE)
|
||
|
|
||
|
then, now :=
|
||
4 years ago
|
quorum.NewRegistry(stakedSlotsThen, int(thenE.Int64())),
|
||
|
quorum.NewRegistry(stakedSlotsNow, int(nowE.Int64()))
|
||
4 years ago
|
|
||
|
rawStakes := []effective.SlotPurchase{}
|
||
|
validatorSpreads := map[common.Address]numeric.Dec{}
|
||
|
for _, comm := range prevCommittee.Shards {
|
||
|
decider := quorum.NewDecider(quorum.SuperMajorityStake, comm.ShardID)
|
||
|
// before staking skip computing
|
||
8 months ago
|
if wiki.BlockChain.Config().IsStaking(prevCommittee.Epoch) {
|
||
4 years ago
|
if _, err := decider.SetVoters(&comm, prevCommittee.Epoch); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
}
|
||
8 months ago
|
rawStakes = wiki.readAndUpdateRawStakes(thenE, decider, comm, rawStakes, validatorSpreads)
|
||
4 years ago
|
then.Deciders[fmt.Sprintf("shard-%d", comm.ShardID)] = decider
|
||
|
}
|
||
|
then.MedianStake = effective.Median(rawStakes)
|
||
|
|
||
|
rawStakes = []effective.SlotPurchase{}
|
||
|
validatorSpreads = map[common.Address]numeric.Dec{}
|
||
|
for _, comm := range nowCommittee.Shards {
|
||
|
decider := quorum.NewDecider(quorum.SuperMajorityStake, comm.ShardID)
|
||
|
if _, err := decider.SetVoters(&comm, nowCommittee.Epoch); err != nil {
|
||
|
return nil, errors.Wrapf(
|
||
|
err,
|
||
|
"committee is only available from staking epoch: %v, current epoch: %v",
|
||
8 months ago
|
wiki.BlockChain.Config().StakingEpoch,
|
||
|
wiki.BlockChain.CurrentHeader().Epoch(),
|
||
4 years ago
|
)
|
||
|
}
|
||
8 months ago
|
rawStakes = wiki.readAndUpdateRawStakes(nowE, decider, comm, rawStakes, validatorSpreads)
|
||
4 years ago
|
now.Deciders[fmt.Sprintf("shard-%d", comm.ShardID)] = decider
|
||
|
}
|
||
|
now.MedianStake = effective.Median(rawStakes)
|
||
|
|
||
|
return &quorum.Transition{Previous: then, Current: now}, nil
|
||
|
}
|
||
|
|
||
|
// IsStakingEpoch ...
|
||
8 months ago
|
func (wiki *Woop) IsStakingEpoch(epoch *big.Int) bool {
|
||
|
return wiki.BlockChain.Config().IsStaking(epoch)
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// IsPreStakingEpoch ...
|
||
8 months ago
|
func (wiki *Woop) IsPreStakingEpoch(epoch *big.Int) bool {
|
||
|
return wiki.BlockChain.Config().IsPreStaking(epoch)
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// IsNoEarlyUnlockEpoch ...
|
||
8 months ago
|
func (wiki *Woop) IsNoEarlyUnlockEpoch(epoch *big.Int) bool {
|
||
|
return wiki.BlockChain.Config().IsNoEarlyUnlock(epoch)
|
||
4 years ago
|
}
|
||
|
|
||
11 months ago
|
// IsMaxRate ...
|
||
8 months ago
|
func (wiki *Woop) IsMaxRate(epoch *big.Int) bool {
|
||
|
return wiki.BlockChain.Config().IsMaxRate(epoch)
|
||
11 months ago
|
}
|
||
|
|
||
4 years ago
|
// IsCommitteeSelectionBlock checks if the given block is the committee selection block
|
||
8 months ago
|
func (wiki *Woop) IsCommitteeSelectionBlock(header *block.Header) bool {
|
||
|
return chain.IsCommitteeSelectionBlock(wiki.BlockChain, header)
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// GetDelegationLockingPeriodInEpoch ...
|
||
8 months ago
|
func (wiki *Woop) GetDelegationLockingPeriodInEpoch(epoch *big.Int) int {
|
||
|
return chain.GetLockPeriodInEpoch(wiki.BlockChain, epoch)
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// SendStakingTx adds a staking transaction
|
||
8 months ago
|
func (wiki *Woop) SendStakingTx(ctx context.Context, signedStakingTx *staking.StakingTransaction) error {
|
||
|
stx, _, _, _ := rawdb.ReadStakingTransaction(wiki.chainDb, signedStakingTx.Hash())
|
||
4 years ago
|
if stx == nil {
|
||
8 months ago
|
return wiki.NodeAPI.AddPendingStakingTransaction(signedStakingTx)
|
||
4 years ago
|
}
|
||
|
return ErrFinalizedTransaction
|
||
|
}
|
||
|
|
||
|
// GetStakingTransactionsHistory returns list of staking transactions hashes of address.
|
||
8 months ago
|
func (wiki *Woop) GetStakingTransactionsHistory(address, txType, order string) ([]common.Hash, error) {
|
||
|
return wiki.NodeAPI.GetStakingTransactionsHistory(address, txType, order)
|
||
4 years ago
|
}
|
||
|
|
||
|
// GetStakingTransactionsCount returns the number of staking transactions of address.
|
||
8 months ago
|
func (wiki *Woop) GetStakingTransactionsCount(address, txType string) (uint64, error) {
|
||
|
return wiki.NodeAPI.GetStakingTransactionsCount(address, txType)
|
||
4 years ago
|
}
|
||
|
|
||
|
// GetSuperCommittees ..
|
||
8 months ago
|
func (wiki *Woop) GetSuperCommittees() (*quorum.Transition, error) {
|
||
|
nowE := wiki.BlockChain.CurrentHeader().Epoch()
|
||
4 years ago
|
key := fmt.Sprintf("sc-%s", nowE.String())
|
||
|
|
||
8 months ago
|
res, err := wiki.SingleFlightRequest(
|
||
4 years ago
|
key, func() (interface{}, error) {
|
||
|
thenE := new(big.Int).Sub(nowE, common.Big1)
|
||
|
thenKey := fmt.Sprintf("sc-%s", thenE.String())
|
||
8 months ago
|
wiki.group.Forget(thenKey)
|
||
|
return wiki.getSuperCommittees()
|
||
4 years ago
|
})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return res.(*quorum.Transition), err
|
||
|
}
|
||
|
|
||
|
// GetValidators returns validators for a particular epoch.
|
||
8 months ago
|
func (wiki *Woop) GetValidators(epoch *big.Int) (*shard.Committee, error) {
|
||
|
state, err := wiki.BlockChain.ReadShardState(epoch)
|
||
4 years ago
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
for _, cmt := range state.Shards {
|
||
8 months ago
|
if cmt.ShardID == wiki.ShardID {
|
||
4 years ago
|
return &cmt, nil
|
||
|
}
|
||
|
}
|
||
|
return nil, nil
|
||
|
}
|
||
|
|
||
|
// GetValidatorSelfDelegation returns the amount of staking after applying all delegated stakes
|
||
8 months ago
|
func (wiki *Woop) GetValidatorSelfDelegation(addr common.Address) *big.Int {
|
||
|
wrapper, err := wiki.BlockChain.ReadValidatorInformation(addr)
|
||
4 years ago
|
if err != nil || wrapper == nil {
|
||
|
return nil
|
||
|
}
|
||
|
if len(wrapper.Delegations) == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
return wrapper.Delegations[0].Amount
|
||
|
}
|
||
|
|
||
|
// GetElectedValidatorAddresses returns the address of elected validators for current epoch
|
||
8 months ago
|
func (wiki *Woop) GetElectedValidatorAddresses() []common.Address {
|
||
|
list, _ := wiki.BlockChain.ReadShardState(wiki.BlockChain.CurrentBlock().Epoch())
|
||
4 years ago
|
return list.StakedValidators().Addrs
|
||
|
}
|
||
|
|
||
|
// GetAllValidatorAddresses returns the up to date validator candidates for next epoch
|
||
8 months ago
|
func (wiki *Woop) GetAllValidatorAddresses() []common.Address {
|
||
|
return wiki.BlockChain.ValidatorCandidates()
|
||
4 years ago
|
}
|
||
|
|
||
8 months ago
|
func (wiki *Woop) GetValidatorsStakeByBlockNumber(
|
||
2 years ago
|
block *types.Block,
|
||
2 years ago
|
) (map[string]*big.Int, error) {
|
||
8 months ago
|
if cachedReward, ok := wiki.stakeByBlockNumberCache.Get(block.Hash()); ok {
|
||
2 years ago
|
return cachedReward.(map[string]*big.Int), nil
|
||
2 years ago
|
}
|
||
8 months ago
|
validatorAddresses := wiki.GetAllValidatorAddresses()
|
||
2 years ago
|
stakes := make(map[string]*big.Int, len(validatorAddresses))
|
||
2 years ago
|
for _, validatorAddress := range validatorAddresses {
|
||
8 months ago
|
wrapper, err := wiki.BlockChain.ReadValidatorInformationAtRoot(validatorAddress, block.Root())
|
||
2 years ago
|
if err != nil {
|
||
|
if errors.Cause(err) != state.ErrAddressNotPresent {
|
||
|
return nil, errors.Errorf(
|
||
|
"cannot fetch information for validator %s at block %d due to %s",
|
||
|
validatorAddress.Hex(),
|
||
|
block.Number(),
|
||
|
err,
|
||
|
)
|
||
|
} else {
|
||
|
// `validatorAddress` was not a validator back then
|
||
|
continue
|
||
|
}
|
||
|
}
|
||
2 years ago
|
stakes[validatorAddress.Hex()] = wrapper.TotalDelegation()
|
||
2 years ago
|
}
|
||
8 months ago
|
wiki.stakeByBlockNumberCache.Add(block.Hash(), stakes)
|
||
2 years ago
|
return stakes, nil
|
||
|
}
|
||
|
|
||
4 years ago
|
var (
|
||
|
epochBlocksMap = map[common.Address]map[uint64]staking.EpochSigningEntry{}
|
||
4 years ago
|
mapLock = sync.Mutex{}
|
||
4 years ago
|
)
|
||
|
|
||
8 months ago
|
func (wiki *Woop) getEpochSigning(epoch *big.Int, addr common.Address) (staking.EpochSigningEntry, error) {
|
||
4 years ago
|
entry := staking.EpochSigningEntry{}
|
||
4 years ago
|
mapLock.Lock()
|
||
|
defer mapLock.Unlock()
|
||
4 years ago
|
if validatorMap, ok := epochBlocksMap[addr]; ok {
|
||
|
if val, ok := validatorMap[epoch.Uint64()]; ok {
|
||
|
return val, nil
|
||
|
}
|
||
|
}
|
||
|
|
||
8 months ago
|
snapshot, err := wiki.BlockChain.ReadValidatorSnapshotAtEpoch(epoch, addr)
|
||
4 years ago
|
if err != nil {
|
||
|
return entry, err
|
||
|
}
|
||
|
|
||
|
// the signing information is for the previous epoch
|
||
|
prevEpoch := big.NewInt(0).Sub(epoch, common.Big1)
|
||
|
entry.Epoch = prevEpoch
|
||
|
entry.Blocks = snapshot.Validator.Counters
|
||
|
|
||
|
// subtract previous epoch counters if exists
|
||
8 months ago
|
prevEpochSnap, err := wiki.BlockChain.ReadValidatorSnapshotAtEpoch(prevEpoch, addr)
|
||
4 years ago
|
if err == nil {
|
||
|
entry.Blocks.NumBlocksSigned.Sub(
|
||
|
entry.Blocks.NumBlocksSigned,
|
||
|
prevEpochSnap.Validator.Counters.NumBlocksSigned,
|
||
|
)
|
||
|
entry.Blocks.NumBlocksToSign.Sub(
|
||
|
entry.Blocks.NumBlocksToSign,
|
||
|
prevEpochSnap.Validator.Counters.NumBlocksToSign,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
// update map when adding new entry, also remove an entry beyond last 30
|
||
|
if _, ok := epochBlocksMap[addr]; !ok {
|
||
|
epochBlocksMap[addr] = map[uint64]staking.EpochSigningEntry{}
|
||
|
}
|
||
|
epochBlocksMap[addr][epoch.Uint64()] = entry
|
||
|
epochMinus30 := big.NewInt(0).Sub(epoch, big.NewInt(staking.SigningHistoryLength))
|
||
|
delete(epochBlocksMap[addr], epochMinus30.Uint64())
|
||
|
|
||
|
return entry, nil
|
||
|
}
|
||
|
|
||
4 years ago
|
// GetValidatorInformation returns the information of validator
|
||
8 months ago
|
func (wiki *Woop) GetValidatorInformation(
|
||
4 years ago
|
addr common.Address, block *types.Block,
|
||
|
) (*staking.ValidatorRPCEnhanced, error) {
|
||
8 months ago
|
bc := wiki.BlockChain
|
||
4 years ago
|
wrapper, err := bc.ReadValidatorInformationAtRoot(addr, block.Root())
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
s, _ := internalCommon.AddressToBech32(addr)
|
||
4 years ago
|
return nil, errors.Wrapf(err, "not found address in current state %s", s)
|
||
|
}
|
||
|
|
||
|
now := block.Epoch()
|
||
|
// At the last block of epoch, block epoch is e while val.LastEpochInCommittee
|
||
|
// is already updated to e+1. So need the >= check rather than ==
|
||
|
inCommittee := wrapper.LastEpochInCommittee.Cmp(now) >= 0
|
||
|
defaultReply := &staking.ValidatorRPCEnhanced{
|
||
|
CurrentlyInCommittee: inCommittee,
|
||
|
Wrapper: *wrapper,
|
||
|
Performance: nil,
|
||
|
ComputedMetrics: nil,
|
||
|
TotalDelegated: wrapper.TotalDelegation(),
|
||
|
EPoSStatus: effective.ValidatorStatus(
|
||
|
inCommittee, wrapper.Status,
|
||
|
).String(),
|
||
|
EPoSWinningStake: nil,
|
||
|
BootedStatus: nil,
|
||
|
ActiveStatus: wrapper.Validator.Status.String(),
|
||
|
Lifetime: &staking.AccumulatedOverLifetime{
|
||
|
BlockReward: wrapper.BlockReward,
|
||
|
Signing: wrapper.Counters,
|
||
|
APR: zero,
|
||
|
},
|
||
|
}
|
||
|
|
||
|
snapshot, err := bc.ReadValidatorSnapshotAtEpoch(
|
||
|
now, addr,
|
||
|
)
|
||
|
|
||
|
if err != nil {
|
||
|
return defaultReply, nil
|
||
|
}
|
||
|
|
||
|
computed := availability.ComputeCurrentSigning(
|
||
|
snapshot.Validator, wrapper,
|
||
|
)
|
||
4 years ago
|
|
||
8 months ago
|
lastBlockOfEpoch := shard.Schedule.EpochLastBlock(wiki.BeaconChain.CurrentBlock().Header().Epoch().Uint64())
|
||
4 years ago
|
|
||
8 months ago
|
computed.BlocksLeftInEpoch = lastBlockOfEpoch - wiki.BeaconChain.CurrentBlock().Header().Number().Uint64()
|
||
4 years ago
|
|
||
|
if defaultReply.CurrentlyInCommittee {
|
||
|
defaultReply.Performance = &staking.CurrentEpochPerformance{
|
||
|
CurrentSigningPercentage: *computed,
|
||
8 months ago
|
Epoch: wiki.BeaconChain.CurrentBlock().Header().Epoch().Uint64(),
|
||
|
Block: wiki.BeaconChain.CurrentBlock().Header().Number().Uint64(),
|
||
4 years ago
|
}
|
||
|
}
|
||
|
|
||
|
stats, err := bc.ReadValidatorStats(addr)
|
||
|
if err != nil {
|
||
|
// when validator has no stats, default boot-status to not booted
|
||
|
notBooted := effective.NotBooted.String()
|
||
|
defaultReply.BootedStatus = ¬Booted
|
||
|
return defaultReply, nil
|
||
|
}
|
||
|
|
||
|
latestAPR := numeric.ZeroDec()
|
||
|
l := len(stats.APRs)
|
||
|
if l > 0 {
|
||
|
latestAPR = stats.APRs[l-1].Value
|
||
|
}
|
||
|
defaultReply.Lifetime.APR = latestAPR
|
||
|
defaultReply.Lifetime.EpochAPRs = stats.APRs
|
||
|
|
||
|
// average apr cache keys
|
||
|
// key := fmt.Sprintf("apr-%s-%d", addr.Hex(), now.Uint64())
|
||
|
// prevKey := fmt.Sprintf("apr-%s-%d", addr.Hex(), now.Uint64()-1)
|
||
|
|
||
|
// delete entry for previous epoch
|
||
|
// b.apiCache.Forget(prevKey)
|
||
|
|
||
|
// calculate last APRHistoryLength epochs for averaging APR
|
||
3 years ago
|
// epochFrom := bc.GasPriceConfig().StakingEpoch
|
||
4 years ago
|
// nowMinus := big.NewInt(0).Sub(now, big.NewInt(staking.APRHistoryLength))
|
||
|
// if nowMinus.Cmp(epochFrom) > 0 {
|
||
|
// epochFrom = nowMinus
|
||
|
// }
|
||
|
|
||
|
// if len(stats.APRs) > 0 && stats.APRs[0].Epoch.Cmp(epochFrom) > 0 {
|
||
|
// epochFrom = stats.APRs[0].Epoch
|
||
|
// }
|
||
|
|
||
|
// epochToAPRs := map[int64]numeric.Dec{}
|
||
|
// for i := 0; i < len(stats.APRs); i++ {
|
||
|
// entry := stats.APRs[i]
|
||
|
// epochToAPRs[entry.Epoch.Int64()] = entry.Value
|
||
|
// }
|
||
|
|
||
|
// at this point, validator is active and has apr's for the recent 100 epochs
|
||
|
// compute average apr over history
|
||
|
// if avgAPR, err := b.SingleFlightRequest(
|
||
|
// key, func() (interface{}, error) {
|
||
|
// total := numeric.ZeroDec()
|
||
|
// count := 0
|
||
|
// for i := epochFrom.Int64(); i < now.Int64(); i++ {
|
||
|
// if apr, ok := epochToAPRs[i]; ok {
|
||
|
// total = total.Add(apr)
|
||
|
// }
|
||
|
// count++
|
||
|
// }
|
||
|
// if count == 0 {
|
||
|
// return nil, errors.New("no apr snapshots available")
|
||
|
// }
|
||
|
// return total.QuoInt64(int64(count)), nil
|
||
|
// },
|
||
|
// ); err != nil {
|
||
|
// // could not compute average apr from snapshot
|
||
|
// // assign the latest apr available from stats
|
||
|
// defaultReply.Lifetime.APR = numeric.ZeroDec()
|
||
|
// } else {
|
||
|
// defaultReply.Lifetime.APR = avgAPR.(numeric.Dec)
|
||
|
// }
|
||
|
|
||
4 years ago
|
epochBlocks := []staking.EpochSigningEntry{}
|
||
|
epochFrom := bc.Config().StakingEpoch
|
||
|
nowMinus := big.NewInt(0).Sub(now, big.NewInt(staking.SigningHistoryLength))
|
||
|
if nowMinus.Cmp(epochFrom) > 0 {
|
||
|
epochFrom = nowMinus
|
||
|
}
|
||
|
for i := now.Int64(); i > epochFrom.Int64(); i-- {
|
||
|
epoch := big.NewInt(i)
|
||
8 months ago
|
entry, err := wiki.getEpochSigning(epoch, addr)
|
||
4 years ago
|
if err != nil {
|
||
|
break
|
||
|
}
|
||
|
epochBlocks = append(epochBlocks, entry)
|
||
|
}
|
||
|
defaultReply.Lifetime.EpochBlocks = epochBlocks
|
||
|
|
||
4 years ago
|
if defaultReply.CurrentlyInCommittee {
|
||
|
defaultReply.ComputedMetrics = stats
|
||
|
defaultReply.EPoSWinningStake = &stats.TotalEffectiveStake
|
||
|
}
|
||
|
|
||
|
if !defaultReply.CurrentlyInCommittee {
|
||
|
reason := stats.BootedStatus.String()
|
||
|
defaultReply.BootedStatus = &reason
|
||
|
}
|
||
|
|
||
|
return defaultReply, nil
|
||
|
}
|
||
|
|
||
|
// GetMedianRawStakeSnapshot ..
|
||
8 months ago
|
func (wiki *Woop) GetMedianRawStakeSnapshot() (
|
||
4 years ago
|
*committee.CompletedEPoSRound, error,
|
||
|
) {
|
||
8 months ago
|
blockNum := wiki.CurrentBlock().NumberU64()
|
||
4 years ago
|
key := fmt.Sprintf("median-%d", blockNum)
|
||
|
|
||
|
// delete cache for previous block
|
||
|
prevKey := fmt.Sprintf("median-%d", blockNum-1)
|
||
8 months ago
|
wiki.group.Forget(prevKey)
|
||
4 years ago
|
|
||
8 months ago
|
res, err := wiki.SingleFlightRequest(
|
||
4 years ago
|
key,
|
||
|
func() (interface{}, error) {
|
||
|
// Compute for next epoch
|
||
8 months ago
|
epoch := big.NewInt(0).Add(wiki.CurrentBlock().Epoch(), big.NewInt(1))
|
||
3 years ago
|
instance := shard.Schedule.InstanceForEpoch(epoch)
|
||
8 months ago
|
return committee.NewEPoSRound(epoch, wiki.BlockChain, wiki.BlockChain.Config().IsEPoSBound35(epoch), instance.SlotsLimit(), int(instance.NumShards()))
|
||
4 years ago
|
},
|
||
|
)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return res.(*committee.CompletedEPoSRound), nil
|
||
|
}
|
||
|
|
||
|
// GetDelegationsByValidator returns all delegation information of a validator
|
||
8 months ago
|
func (wiki *Woop) GetDelegationsByValidator(validator common.Address) []staking.Delegation {
|
||
|
wrapper, err := wiki.BlockChain.ReadValidatorInformation(validator)
|
||
4 years ago
|
if err != nil || wrapper == nil {
|
||
|
return nil
|
||
|
}
|
||
3 years ago
|
return wrapper.Delegations
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// GetDelegationsByValidatorAtBlock returns all delegation information of a validator at the given block
|
||
8 months ago
|
func (wiki *Woop) GetDelegationsByValidatorAtBlock(
|
||
4 years ago
|
validator common.Address, block *types.Block,
|
||
3 years ago
|
) []staking.Delegation {
|
||
8 months ago
|
wrapper, err := wiki.BlockChain.ReadValidatorInformationAtRoot(validator, block.Root())
|
||
4 years ago
|
if err != nil || wrapper == nil {
|
||
|
return nil
|
||
|
}
|
||
3 years ago
|
return wrapper.Delegations
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
// GetDelegationsByDelegator returns all delegation information of a delegator
|
||
8 months ago
|
func (wiki *Woop) GetDelegationsByDelegator(
|
||
4 years ago
|
delegator common.Address,
|
||
|
) ([]common.Address, []*staking.Delegation) {
|
||
8 months ago
|
block := wiki.BlockChain.CurrentBlock()
|
||
|
return wiki.GetDelegationsByDelegatorByBlock(delegator, block)
|
||
4 years ago
|
}
|
||
|
|
||
|
// GetDelegationsByDelegatorByBlock returns all delegation information of a delegator
|
||
8 months ago
|
func (wiki *Woop) GetDelegationsByDelegatorByBlock(
|
||
4 years ago
|
delegator common.Address, block *types.Block,
|
||
|
) ([]common.Address, []*staking.Delegation) {
|
||
8 months ago
|
delegationIndexes, err := wiki.BlockChain.
|
||
4 years ago
|
ReadDelegationsByDelegatorAt(delegator, block.Number())
|
||
|
if err != nil {
|
||
|
return nil, nil
|
||
|
}
|
||
|
|
||
3 years ago
|
addresses := make([]common.Address, 0, len(delegationIndexes))
|
||
|
delegations := make([]*staking.Delegation, 0, len(delegationIndexes))
|
||
|
|
||
4 years ago
|
for i := range delegationIndexes {
|
||
8 months ago
|
wrapper, err := wiki.BlockChain.ReadValidatorInformationAtRoot(
|
||
4 years ago
|
delegationIndexes[i].ValidatorAddress, block.Root(),
|
||
|
)
|
||
|
if err != nil || wrapper == nil {
|
||
|
return nil, nil
|
||
|
}
|
||
|
|
||
|
if uint64(len(wrapper.Delegations)) > delegationIndexes[i].Index {
|
||
|
delegations = append(delegations, &wrapper.Delegations[delegationIndexes[i].Index])
|
||
|
} else {
|
||
|
delegations = append(delegations, nil)
|
||
|
}
|
||
|
addresses = append(addresses, delegationIndexes[i].ValidatorAddress)
|
||
|
}
|
||
|
return addresses, delegations
|
||
|
}
|
||
|
|
||
4 years ago
|
// UndelegationPayouts ..
|
||
4 years ago
|
type UndelegationPayouts struct {
|
||
|
Data map[common.Address]map[common.Address]*big.Int
|
||
|
}
|
||
|
|
||
|
func NewUndelegationPayouts() *UndelegationPayouts {
|
||
|
return &UndelegationPayouts{
|
||
|
Data: make(map[common.Address]map[common.Address]*big.Int),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (u *UndelegationPayouts) SetPayoutByDelegatorAddrAndValidatorAddr(
|
||
|
delegator, validator common.Address, amount *big.Int,
|
||
|
) {
|
||
|
if u.Data[delegator] == nil {
|
||
|
u.Data[delegator] = make(map[common.Address]*big.Int)
|
||
|
}
|
||
|
|
||
|
if totalPayout, ok := u.Data[delegator][validator]; ok {
|
||
|
u.Data[delegator][validator] = new(big.Int).Add(totalPayout, amount)
|
||
|
} else {
|
||
|
u.Data[delegator][validator] = amount
|
||
|
}
|
||
|
}
|
||
4 years ago
|
|
||
4 years ago
|
// GetUndelegationPayouts returns the undelegation payouts for each delegator
|
||
|
//
|
||
|
// Due to in-memory caching, it is possible to get undelegation payouts for a state / epoch
|
||
|
// that has been pruned but have it be lost (and unable to recompute) after the node restarts.
|
||
|
// This not a problem if a full (archival) DB is used.
|
||
8 months ago
|
func (wiki *Woop) GetUndelegationPayouts(
|
||
4 years ago
|
ctx context.Context, epoch *big.Int,
|
||
4 years ago
|
) (*UndelegationPayouts, error) {
|
||
8 months ago
|
if !wiki.IsPreStakingEpoch(epoch) {
|
||
4 years ago
|
return nil, fmt.Errorf("not pre-staking epoch or later")
|
||
|
}
|
||
|
|
||
8 months ago
|
payouts, ok := wiki.undelegationPayoutsCache.Get(epoch.Uint64())
|
||
4 years ago
|
if ok {
|
||
4 years ago
|
return payouts.(*UndelegationPayouts), nil
|
||
4 years ago
|
}
|
||
4 years ago
|
undelegationPayouts := NewUndelegationPayouts()
|
||
4 years ago
|
// require second to last block as saved undelegations are AFTER undelegations are payed out
|
||
|
blockNumber := shard.Schedule.EpochLastBlock(epoch.Uint64()) - 1
|
||
8 months ago
|
undelegationPayoutBlock, err := wiki.BlockByNumber(ctx, rpc.BlockNumber(blockNumber))
|
||
4 years ago
|
if err != nil || undelegationPayoutBlock == nil {
|
||
|
// Block not found, so no undelegationPayouts (not an error)
|
||
|
return undelegationPayouts, nil
|
||
|
}
|
||
|
|
||
8 months ago
|
isMaxRate := wiki.IsMaxRate(epoch)
|
||
|
lockingPeriod := wiki.GetDelegationLockingPeriodInEpoch(undelegationPayoutBlock.Epoch())
|
||
|
for _, validator := range wiki.GetAllValidatorAddresses() {
|
||
|
wrapper, err := wiki.BlockChain.ReadValidatorInformationAtRoot(validator, undelegationPayoutBlock.Root())
|
||
4 years ago
|
if err != nil || wrapper == nil {
|
||
|
continue // Not a validator at this epoch or unable to fetch validator info because of pruned state.
|
||
|
}
|
||
8 months ago
|
noEarlyUnlock := wiki.IsNoEarlyUnlockEpoch(epoch)
|
||
4 years ago
|
for _, delegation := range wrapper.Delegations {
|
||
11 months ago
|
withdraw := delegation.RemoveUnlockedUndelegations(epoch, wrapper.LastEpochInCommittee, lockingPeriod, noEarlyUnlock, isMaxRate)
|
||
4 years ago
|
if withdraw.Cmp(bigZero) == 1 {
|
||
4 years ago
|
undelegationPayouts.SetPayoutByDelegatorAddrAndValidatorAddr(validator, delegation.DelegatorAddress, withdraw)
|
||
4 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
8 months ago
|
wiki.undelegationPayoutsCache.Add(epoch.Uint64(), undelegationPayouts)
|
||
4 years ago
|
return undelegationPayouts, nil
|
||
|
}
|
||
|
|
||
4 years ago
|
// GetTotalStakingSnapshot ..
|
||
8 months ago
|
func (wiki *Woop) GetTotalStakingSnapshot() *big.Int {
|
||
|
if stake := wiki.totalStakeCache.pop(wiki.CurrentBlock().NumberU64()); stake != nil {
|
||
4 years ago
|
return stake
|
||
|
}
|
||
8 months ago
|
currHeight := wiki.CurrentBlock().NumberU64()
|
||
|
candidates := wiki.BlockChain.ValidatorCandidates()
|
||
4 years ago
|
if len(candidates) == 0 {
|
||
|
stake := big.NewInt(0)
|
||
8 months ago
|
wiki.totalStakeCache.push(currHeight, stake)
|
||
4 years ago
|
return stake
|
||
|
}
|
||
|
stakes := big.NewInt(0)
|
||
|
for i := range candidates {
|
||
8 months ago
|
snapshot, _ := wiki.BlockChain.ReadValidatorSnapshot(candidates[i])
|
||
|
validator, _ := wiki.BlockChain.ReadValidatorInformation(candidates[i])
|
||
4 years ago
|
if !committee.IsEligibleForEPoSAuction(
|
||
|
snapshot, validator,
|
||
|
) {
|
||
|
continue
|
||
|
}
|
||
|
for i := range validator.Delegations {
|
||
|
stakes.Add(stakes, validator.Delegations[i].Amount)
|
||
|
}
|
||
|
}
|
||
8 months ago
|
wiki.totalStakeCache.push(currHeight, stakes)
|
||
4 years ago
|
return stakes
|
||
|
}
|
||
|
|
||
|
// GetCurrentStakingErrorSink ..
|
||
8 months ago
|
func (wiki *Woop) GetCurrentStakingErrorSink() types.TransactionErrorReports {
|
||
|
return wiki.NodeAPI.ReportStakingErrorSink()
|
||
4 years ago
|
}
|
||
|
|
||
|
// totalStakeCache ..
|
||
|
type totalStakeCache struct {
|
||
|
sync.Mutex
|
||
|
cachedBlockHeight uint64
|
||
|
stake *big.Int
|
||
|
// duration is in blocks
|
||
|
duration uint64
|
||
|
}
|
||
|
|
||
|
// newTotalStakeCache ..
|
||
|
func newTotalStakeCache(duration uint64) *totalStakeCache {
|
||
|
return &totalStakeCache{
|
||
|
cachedBlockHeight: 0,
|
||
|
stake: nil,
|
||
|
duration: duration,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (c *totalStakeCache) push(currBlockHeight uint64, stake *big.Int) {
|
||
|
c.Lock()
|
||
|
defer c.Unlock()
|
||
|
c.cachedBlockHeight = currBlockHeight
|
||
|
c.stake = stake
|
||
|
}
|
||
|
|
||
|
func (c *totalStakeCache) pop(currBlockHeight uint64) *big.Int {
|
||
|
if currBlockHeight > c.cachedBlockHeight+c.duration {
|
||
|
return nil
|
||
|
}
|
||
|
return c.stake
|
||
|
}
|