Merge pull request #1834 from rlan35/staking_tx

Add validator snapshot in local db
pull/1840/head
Rongjian Lan 5 years ago committed by GitHub
commit 919e96b221
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 16
      api/service/explorer/service.go
  2. 8
      api/service/explorer/storage_test.go
  3. 2
      consensus/consensus_service.go
  4. 4
      consensus/engine/consensus_engine.go
  5. 205
      core/blockchain.go
  6. 2
      core/chain_makers.go
  7. 83
      core/rawdb/accessors_chain.go
  8. 14
      core/rawdb/schema.go
  9. 2
      core/state_transition.go
  10. 6
      hmy/api_backend.go
  11. 6
      internal/chain/engine.go
  12. 4
      internal/chain/reward.go
  13. 2
      internal/hmyapi/backend.go
  14. 14
      internal/hmyapi/blockchain.go
  15. 2
      node/node_cross_shard.go
  16. 2
      node/node_handler.go
  17. 6
      node/node_resharding.go
  18. 26
      shard/committee/assignment.go
  19. 42
      shard/shard_state.go
  20. 12
      shard/shard_state_test.go
  21. 3
      staking/types/validator.go

@ -282,8 +282,8 @@ func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {
curEpoch = int64(block.Epoch)
}
if withSigners {
pubkeys := make([]*bls.PublicKey, len(committee.NodeList))
for i, validator := range committee.NodeList {
pubkeys := make([]*bls.PublicKey, len(committee.Slots))
for i, validator := range committee.Slots {
pubkeys[i] = new(bls.PublicKey)
validator.BlsPublicKey.ToLibBLSPublicKey(pubkeys[i])
}
@ -291,7 +291,7 @@ func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {
if err == nil && accountBlocks[id+1] != nil {
err = mask.SetMask(accountBlocks[id+1].Header().LastCommitBitmap())
if err == nil {
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
oneAddress, err := common2.AddressToBech32(validator.EcdsaAddress)
if err != nil {
continue
@ -403,8 +403,8 @@ func (s *ServiceAPI) GetExplorerBlocks(ctx context.Context, from, to, page, offs
curEpoch = int64(block.Epoch)
}
if withSigners {
pubkeys := make([]*bls.PublicKey, len(committee.NodeList))
for i, validator := range committee.NodeList {
pubkeys := make([]*bls.PublicKey, len(committee.Slots))
for i, validator := range committee.Slots {
pubkeys[i] = new(bls.PublicKey)
validator.BlsPublicKey.ToLibBLSPublicKey(pubkeys[i])
}
@ -412,7 +412,7 @@ func (s *ServiceAPI) GetExplorerBlocks(ctx context.Context, from, to, page, offs
if err == nil && accountBlocks[id+1] != nil {
err = mask.SetMask(accountBlocks[id+1].Header().LastCommitBitmap())
if err == nil {
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
oneAddress, err := common2.AddressToBech32(validator.EcdsaAddress)
if err != nil {
continue
@ -592,7 +592,7 @@ func (s *Service) GetExplorerCommittee(w http.ResponseWriter, r *http.Request) {
return
}
validators := &Committee{}
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
validatorBalance := big.NewInt(0)
validatorBalance, err := s.GetAccountBalance(validator.EcdsaAddress)
if err != nil {
@ -645,7 +645,7 @@ func (s *ServiceAPI) GetExplorerCommittee(ctx context.Context, shardID uint32, e
return nil, err
}
validators := &Committee{}
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
validatorBalance := big.NewInt(0)
validatorBalance, err := s.Service.GetAccountBalance(validator.EcdsaAddress)
if err != nil {

@ -90,10 +90,10 @@ func TestDumpCommittee(t *testing.T) {
BlsPublicKey2 := new(shard.BlsPublicKey)
BlsPublicKey1.FromLibBLSPublicKey(blsPubKey1)
BlsPublicKey2.FromLibBLSPublicKey(blsPubKey2)
nodeID1 := shard.NodeID{EcdsaAddress: common.HexToAddress("52789f18a342da8023cc401e5d2b14a6b710fba9"), BlsPublicKey: *BlsPublicKey1}
nodeID2 := shard.NodeID{EcdsaAddress: common.HexToAddress("7c41e0668b551f4f902cfaec05b5bdca68b124ce"), BlsPublicKey: *BlsPublicKey2}
nodeIDList := []shard.NodeID{nodeID1, nodeID2}
committee := shard.Committee{ShardID: uint32(0), NodeList: nodeIDList}
nodeID1 := shard.Slot{EcdsaAddress: common.HexToAddress("52789f18a342da8023cc401e5d2b14a6b710fba9"), BlsPublicKey: *BlsPublicKey1}
nodeID2 := shard.Slot{EcdsaAddress: common.HexToAddress("7c41e0668b551f4f902cfaec05b5bdca68b124ce"), BlsPublicKey: *BlsPublicKey2}
nodeIDList := []shard.Slot{nodeID1, nodeID2}
committee := shard.Committee{ShardID: uint32(0), Slots: nodeIDList}
shardID := uint32(0)
epoch := uint64(0)
ins := GetStorageInstance("1.1.1.1", "3333", true)

@ -428,7 +428,7 @@ func (consensus *Consensus) getLeaderPubKeyFromCoinbase(header *block.Header) (*
)
}
committerKey := new(bls.PublicKey)
for _, member := range committee.NodeList {
for _, member := range committee.Slots {
if member.EcdsaAddress == header.Coinbase() {
err := member.BlsPublicKey.ToLibBLSPublicKey(committerKey)
if err != nil {

@ -40,8 +40,8 @@ type ChainReader interface {
// Thus, only should be used to read the shard state of the current chain.
ReadShardState(epoch *big.Int) (shard.State, error)
// CurrentValidatorAddresses retrieves the current list of validators
CurrentValidatorAddresses() []common.Address
// ActiveValidatorAddresses retrieves the list of active validators
ActiveValidatorAddresses() []common.Address
}
// Engine is an algorithm agnostic consensus engine.

@ -70,9 +70,9 @@ const (
commitsCacheLimit = 10
epochCacheLimit = 10
randomnessCacheLimit = 10
stakingCacheLimit = 256
validatorListCacheLimit = 2
validatorListByDelegatorCacheLimit = 256
validatorCacheLimit = 1024
validatorListCacheLimit = 10
validatorListByDelegatorCacheLimit = 1024
// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
BlockChainVersion = 3
@ -135,7 +135,7 @@ type BlockChain struct {
lastCommitsCache *lru.Cache
epochCache *lru.Cache // Cache epoch number → first block number
randomnessCache *lru.Cache // Cache for vrf/vdf
stakingCache *lru.Cache // Cache for staking validator
validatorCache *lru.Cache // Cache for staking validator
validatorListCache *lru.Cache // Cache of validator list
validatorListByDelegatorCache *lru.Cache // Cache of validator list by delegator
@ -174,7 +174,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
commitsCache, _ := lru.New(commitsCacheLimit)
epochCache, _ := lru.New(epochCacheLimit)
randomnessCache, _ := lru.New(randomnessCacheLimit)
stakingCache, _ := lru.New(stakingCacheLimit)
stakingCache, _ := lru.New(validatorCacheLimit)
validatorListCache, _ := lru.New(validatorListCacheLimit)
validatorListByDelegatorCache, _ := lru.New(validatorListByDelegatorCacheLimit)
@ -195,7 +195,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
lastCommitsCache: commitsCache,
epochCache: epochCache,
randomnessCache: randomnessCache,
stakingCache: stakingCache,
validatorCache: stakingCache,
validatorListCache: validatorListCache,
validatorListByDelegatorCache: validatorListByDelegatorCache,
engine: engine,
@ -1078,6 +1078,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
batch := bc.db.NewBatch()
rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
//// Cross-shard txns
epoch := block.Header().Epoch()
if bc.chainConfig.IsCrossTx(block.Epoch()) {
shardingConfig := shard.Schedule.InstanceForEpoch(epoch)
@ -1097,6 +1098,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
bc.WriteCXReceiptsProofSpent(block.IncomingReceipts())
}
//// VRF + VDF
//check non zero VRF field in header and add to local db
if len(block.Vrf()) > 0 {
vrfBlockNumbers, _ := bc.ReadEpochVrfBlockNums(block.Header().Epoch())
@ -1130,16 +1132,50 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
}
}
//// Shard State and Validator Update
header := block.Header()
if header.ShardStateHash() != (common.Hash{}) {
// Write shard state for the new epoch
epoch := new(big.Int).Add(header.Epoch(), common.Big1)
err = bc.WriteShardStateBytes(batch, epoch, header.ShardState())
shardState, err := bc.WriteShardStateBytes(batch, epoch, header.ShardState())
if err != nil {
header.Logger(utils.Logger()).Warn().Err(err).Msg("cannot store shard state")
return NonStatTy, err
}
// Find all the active validator addresses and do a snapshot
allActiveValidators := []common.Address{}
processed := make(map[common.Address]struct{})
for i := range *shardState {
shard := (*shardState)[i]
for j := range shard.Slots {
slot := shard.Slots[j]
if slot.StakeWithDelegationApplied != nil { // For external validator
_, ok := processed[slot.EcdsaAddress]
if !ok {
processed[slot.EcdsaAddress] = struct{}{}
allActiveValidators = append(allActiveValidators, shard.Slots[j].EcdsaAddress)
}
}
}
}
bc.UpdateActiveValidatorsSnapshot(allActiveValidators)
}
// Do bookkeeping for new staking txns
if bc.chainConfig.IsStaking(block.Epoch()) {
for _, tx := range block.StakingTransactions() {
err = bc.UpdateStakingMetaData(tx)
// keep offchain database consistency with onchain we need revert
// but it should not happend unless local database corrupted
if err != nil {
utils.Logger().Debug().Msgf("oops, UpdateStakingMetaData failed, err: %+v", err)
return NonStatTy, err
}
}
}
//// Cross-links
if len(header.CrossLinks()) > 0 {
crossLinks := &types.CrossLinks{}
err = rlp.DecodeBytes(header.CrossLinks(), crossLinks)
@ -1159,19 +1195,6 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
bc.WriteShardLastCrossLink(crossLink.ShardID(), crossLink)
}
}
if bc.chainConfig.IsStaking(block.Epoch()) {
for _, tx := range block.StakingTransactions() {
err = bc.UpdateStakingMetaData(tx)
// keep offchain database consistency with onchain we need revert
// but it should not happend unless local database corrupted
if err != nil {
utils.Logger().Debug().Msgf("oops, UpdateStakingMetaData failed, err: %+v", err)
return NonStatTy, err
}
}
}
/////////////////////////// END
// If the total difficulty is higher than our known, add it to the canonical chain
@ -1870,18 +1893,18 @@ func (bc *BlockChain) WriteShardState(
// WriteShardStateBytes saves the given sharding state under the given epoch number.
func (bc *BlockChain) WriteShardStateBytes(db rawdb.DatabaseWriter,
epoch *big.Int, shardState []byte,
) error {
) (*shard.State, error) {
decodeShardState := shard.State{}
if err := rlp.DecodeBytes(shardState, &decodeShardState); err != nil {
return err
return nil, err
}
err := rawdb.WriteShardStateBytes(db, epoch, shardState)
if err != nil {
return err
return nil, err
}
cacheKey := string(epoch.Bytes())
bc.shardStateCache.Add(cacheKey, decodeShardState)
return nil
return &decodeShardState, nil
}
// ReadLastCommits retrieves last commits.
@ -2276,9 +2299,9 @@ func (bc *BlockChain) ReadTxLookupEntry(txID common.Hash) (common.Hash, uint64,
return rawdb.ReadTxLookupEntry(bc.db, txID)
}
// ReadStakingValidator reads staking information of given validatorWrapper
func (bc *BlockChain) ReadStakingValidator(addr common.Address) (*staking.ValidatorWrapper, error) {
if cached, ok := bc.stakingCache.Get("staking-" + string(addr.Bytes())); ok {
// ReadValidatorData reads staking information of given validatorWrapper
func (bc *BlockChain) ReadValidatorData(addr common.Address) (*staking.ValidatorWrapper, error) {
if cached, ok := bc.validatorCache.Get("validator-" + string(addr.Bytes())); ok {
by := cached.([]byte)
v := staking.ValidatorWrapper{}
if err := rlp.DecodeBytes(by, &v); err != nil {
@ -2287,12 +2310,12 @@ func (bc *BlockChain) ReadStakingValidator(addr common.Address) (*staking.Valida
return &v, nil
}
return rawdb.ReadStakingValidator(bc.db, addr)
return rawdb.ReadValidatorData(bc.db, addr)
}
// WriteStakingValidator reads staking information of given validatorWrapper
func (bc *BlockChain) WriteStakingValidator(v *staking.ValidatorWrapper) error {
err := rawdb.WriteStakingValidator(bc.db, v)
// WriteValidatorData writes staking information of given validatorWrapper
func (bc *BlockChain) WriteValidatorData(v *staking.ValidatorWrapper) error {
err := rawdb.WriteValidatorData(bc.db, v)
if err != nil {
return err
}
@ -2300,7 +2323,89 @@ func (bc *BlockChain) WriteStakingValidator(v *staking.ValidatorWrapper) error {
if err != nil {
return err
}
bc.stakingCache.Add("staking-"+string(v.Address.Bytes()), by)
bc.validatorCache.Add("validator-"+string(v.Address.Bytes()), by)
return nil
}
// ReadValidatorSnapshot reads the snapshot staking information of given validator address
// TODO: put epoch number in to snapshot too.
func (bc *BlockChain) ReadValidatorSnapshot(addr common.Address) (*staking.ValidatorWrapper, error) {
if cached, ok := bc.validatorCache.Get("validator-snapshot-" + string(addr.Bytes())); ok {
by := cached.([]byte)
v := staking.ValidatorWrapper{}
if err := rlp.DecodeBytes(by, &v); err != nil {
return nil, err
}
return &v, nil
}
return rawdb.ReadValidatorSnapshot(bc.db, addr)
}
// WriteValidatorSnapshots writes the snapshot of provided list of validators
func (bc *BlockChain) WriteValidatorSnapshots(addrs []common.Address) error {
// Read all validator's current data
validators := []*staking.ValidatorWrapper{}
for _, addr := range addrs {
validator, err := bc.ReadValidatorData(addr)
if err != nil {
return err
}
validators = append(validators, validator)
}
// Batch write the current data as snapshot
batch := bc.db.NewBatch()
for i := range validators {
err := rawdb.WriteValidatorSnapshot(batch, validators[i])
if err != nil {
return err
}
}
if err := batch.Write(); err != nil {
return err
}
// Update cache
for i := range validators {
by, err := rlp.EncodeToBytes(validators[i])
if err == nil {
bc.validatorCache.Add("validator-snapshot-"+string(validators[i].Address.Bytes()), by)
}
}
return nil
}
// DeleteValidatorSnapshots deletes the snapshot staking information of given validator address
func (bc *BlockChain) DeleteValidatorSnapshots(addrs []common.Address) error {
batch := bc.db.NewBatch()
for i := range addrs {
rawdb.DeleteValidatorSnapshot(batch, addrs[i])
}
if err := batch.Write(); err != nil {
return err
}
for i := range addrs {
bc.validatorCache.Remove("validator-snapshot-" + string(addrs[i].Bytes()))
}
return nil
}
// UpdateActiveValidatorsSnapshot updates the list of active validators and updates the content snapshot of the active validators
func (bc *BlockChain) UpdateActiveValidatorsSnapshot(activeValidators []common.Address) error {
prevActiveValidators, err := bc.ReadActiveValidatorList()
if err != nil {
return err
}
err = bc.DeleteValidatorSnapshots(prevActiveValidators)
if err != nil {
return err
}
if err = bc.WriteValidatorSnapshots(activeValidators); err != nil {
return err
}
return nil
}
@ -2314,12 +2419,12 @@ func (bc *BlockChain) ReadValidatorList() ([]common.Address, error) {
}
return m, nil
}
return rawdb.ReadValidatorList(bc.db)
return rawdb.ReadValidatorList(bc.db, false)
}
// WriteValidatorList writes the list of validator addresses to database
func (bc *BlockChain) WriteValidatorList(addrs []common.Address) error {
err := rawdb.WriteValidatorList(bc.db, addrs)
err := rawdb.WriteValidatorList(bc.db, addrs, false)
if err != nil {
return err
}
@ -2330,6 +2435,32 @@ func (bc *BlockChain) WriteValidatorList(addrs []common.Address) error {
return nil
}
// ReadActiveValidatorList reads the addresses of active validators
func (bc *BlockChain) ReadActiveValidatorList() ([]common.Address, error) {
if cached, ok := bc.validatorListCache.Get("activeValidatorList"); ok {
by := cached.([]byte)
m := []common.Address{}
if err := rlp.DecodeBytes(by, &m); err != nil {
return nil, err
}
return m, nil
}
return rawdb.ReadValidatorList(bc.db, true)
}
// WriteActiveValidatorList writes the list of active validator addresses to database
func (bc *BlockChain) WriteActiveValidatorList(addrs []common.Address) error {
err := rawdb.WriteValidatorList(bc.db, addrs, true)
if err != nil {
return err
}
bytes, err := rlp.EncodeToBytes(addrs)
if err == nil {
bc.validatorListCache.Add("activeValidatorList", bytes)
}
return nil
}
// ReadValidatorListByDelegator reads the addresses of validators delegated by a delegator
func (bc *BlockChain) ReadValidatorListByDelegator(delegator common.Address) ([]common.Address, error) {
if cached, ok := bc.validatorListByDelegatorCache.Get(delegator.Bytes()); ok {
@ -2413,8 +2544,9 @@ func (bc *BlockChain) UpdateStakingMetaData(tx *staking.StakingTransaction) erro
return nil
}
// CurrentValidatorAddresses returns the address of active validators for current epoch
func (bc *BlockChain) CurrentValidatorAddresses() []common.Address {
// ActiveValidatorAddresses returns the address of active validators for current epoch
// TODO: should only return those that are selected by epos.
func (bc *BlockChain) ActiveValidatorAddresses() []common.Address {
list, err := bc.ReadValidatorList()
if err != nil {
return make([]common.Address, 0)
@ -2428,6 +2560,7 @@ func (bc *BlockChain) CurrentValidatorAddresses() []common.Address {
if err != nil {
continue
}
// TODO: double check this logic here.
epoch := shard.Schedule.CalcEpochNumber(val.CreationHeight.Uint64())
if epoch.Cmp(currentEpoch) >= 0 {
// wait for next epoch

@ -270,4 +270,4 @@ func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *block.Header
func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *block.Header { return nil }
func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }
func (cr *fakeChainReader) ReadShardState(epoch *big.Int) (shard.State, error) { return nil, nil }
func (cr *fakeChainReader) CurrentValidatorAddresses() []common.Address { return nil }
func (cr *fakeChainReader) ActiveValidatorAddresses() []common.Address { return nil }

@ -542,7 +542,7 @@ func WriteShardLastCrossLink(db DatabaseWriter, shardID uint32, data []byte) err
// ReadCXReceipts retrieves all the transactions of receipts given destination shardID, number and blockHash
func ReadCXReceipts(db DatabaseReader, shardID uint32, number uint64, hash common.Hash, temp bool) (types.CXReceipts, error) {
data, err := db.Get(cxReceiptKey(shardID, number, hash, temp))
if len(data) == 0 || err != nil {
if err != nil || len(data) == 0 {
utils.Logger().Info().Err(err).Uint64("number", number).Int("dataLen", len(data)).Msg("ReadCXReceipts")
return nil, err
}
@ -614,11 +614,40 @@ func WriteCXReceiptsProofUnspentCheckpoint(db DatabaseWriter, shardID uint32, bl
return db.Put(cxReceiptUnspentCheckpointKey(shardID), by)
}
// ReadStakingValidator retrieves staking validator by its address
func ReadStakingValidator(db DatabaseReader, addr common.Address) (*staking.ValidatorWrapper, error) {
data, err := db.Get(stakingKey(addr))
if len(data) == 0 || err != nil {
utils.Logger().Info().Err(err).Msg("ReadStakingValidator")
// ReadValidatorData retrieves staking validator by its address
func ReadValidatorData(db DatabaseReader, addr common.Address) (*staking.ValidatorWrapper, error) {
data, err := db.Get(validatorKey(addr))
if err != nil || len(data) == 0 {
utils.Logger().Info().Err(err).Msg("ReadValidatorData")
return nil, err
}
v := staking.ValidatorWrapper{}
if err := rlp.DecodeBytes(data, &v); err != nil {
utils.Logger().Error().Err(err).Str("address", addr.Hex()).Msg("Unable to Decode staking validator from database")
return nil, err
}
return &v, nil
}
// WriteValidatorData stores validator's information by its address
func WriteValidatorData(db DatabaseWriter, v *staking.ValidatorWrapper) error {
bytes, err := rlp.EncodeToBytes(v)
if err != nil {
utils.Logger().Error().Msg("[WriteValidatorData] Failed to encode")
return err
}
if err := db.Put(validatorKey(v.Address), bytes); err != nil {
utils.Logger().Error().Msg("[WriteValidatorData] Failed to store to database")
return err
}
return err
}
// ReadValidatorSnapshot retrieves validator's snapshot by its address
func ReadValidatorSnapshot(db DatabaseReader, addr common.Address) (*staking.ValidatorWrapper, error) {
data, err := db.Get(validatorSnapshotKey(addr))
if err != nil || len(data) == 0 {
utils.Logger().Info().Err(err).Msg("ReadValidatorSnapshot")
return nil, err
}
v := staking.ValidatorWrapper{}
@ -629,22 +658,36 @@ func ReadStakingValidator(db DatabaseReader, addr common.Address) (*staking.Vali
return &v, nil
}
// WriteStakingValidator stores staking validator's information by its address
func WriteStakingValidator(db DatabaseWriter, v *staking.ValidatorWrapper) error {
// WriteValidatorSnapshot stores validator's snapshot by its address
func WriteValidatorSnapshot(db DatabaseWriter, v *staking.ValidatorWrapper) error {
bytes, err := rlp.EncodeToBytes(v)
if err != nil {
utils.Logger().Error().Msg("[WriteStakingValidator] Failed to encode")
utils.Logger().Error().Msg("[WriteValidatorSnapshot] Failed to encode")
return err
}
if err := db.Put(stakingKey(v.Address), bytes); err != nil {
utils.Logger().Error().Msg("[WriteStakingValidator] Failed to store to database")
if err := db.Put(validatorSnapshotKey(v.Address), bytes); err != nil {
utils.Logger().Error().Msg("[WriteValidatorSnapshot] Failed to store to database")
return err
}
return err
}
// DeleteValidatorSnapshot removes the validator's snapshot by its address
func DeleteValidatorSnapshot(db DatabaseDeleter, addr common.Address) {
if err := db.Delete(validatorSnapshotKey(addr)); err != nil {
utils.Logger().Error().Msg("Failed to delete snapshot of a validator")
}
}
// ReadValidatorList retrieves staking validator by its address
func ReadValidatorList(db DatabaseReader) ([]common.Address, error) {
data, err := db.Get([]byte("validatorList"))
if len(data) == 0 || err != nil {
// Return only active validators if isActive==true, otherwise, return all validators
func ReadValidatorList(db DatabaseReader, isActive bool) ([]common.Address, error) {
key := validatorListKey
if isActive {
key = activeValidatorListKey
}
data, err := db.Get(key)
if err != nil || len(data) == 0 {
return []common.Address{}, nil
}
addrs := []common.Address{}
@ -656,12 +699,18 @@ func ReadValidatorList(db DatabaseReader) ([]common.Address, error) {
}
// WriteValidatorList stores staking validator's information by its address
func WriteValidatorList(db DatabaseWriter, addrs []common.Address) error {
// Writes only for active validators if isActive==true, otherwise, writes for all validators
func WriteValidatorList(db DatabaseWriter, addrs []common.Address, isActive bool) error {
key := validatorListKey
if isActive {
key = activeValidatorListKey
}
bytes, err := rlp.EncodeToBytes(addrs)
if err != nil {
utils.Logger().Error().Msg("[WriteValidatorList] Failed to encode")
}
if err := db.Put([]byte("validatorList"), bytes); err != nil {
if err := db.Put(key, bytes); err != nil {
utils.Logger().Error().Msg("[WriteValidatorList] Failed to store to database")
}
return err
@ -670,7 +719,7 @@ func WriteValidatorList(db DatabaseWriter, addrs []common.Address) error {
// ReadValidatorListByDelegator retrieves the list of validators delegated by a delegator
func ReadValidatorListByDelegator(db DatabaseReader, delegator common.Address) ([]common.Address, error) {
data, err := db.Get(delegatorValidatorListKey(delegator))
if len(data) == 0 || err != nil {
if err != nil || len(data) == 0 {
return []common.Address{}, nil
}
addrs := []common.Address{}

@ -74,7 +74,10 @@ var (
cxReceiptSpentPrefix = []byte("cxReceiptSpent") // prefix for indicator of unspent of cxReceiptsProof
cxReceiptUnspentCheckpointPrefix = []byte("cxReceiptUnspentCheckpoint") // prefix for cxReceiptsProof unspent checkpoint
stakingPrefix = []byte("staking") // prefix for staking validator information
validatorPrefix = []byte("validator-") // prefix for staking validator information
validatorSnapshotPrefix = []byte("validator-snapshot-") // prefix for staking validator's snapshot information
validatorListKey = []byte("validator-list") // key for all validators list
activeValidatorListKey = []byte("active-validator-list") // key for active validators list
// epochBlockNumberPrefix + epoch (big.Int.Bytes())
// -> epoch block number (big.Int.Bytes())
@ -237,7 +240,12 @@ func cxReceiptUnspentCheckpointKey(shardID uint32) []byte {
return append(prefix, sKey...)
}
func stakingKey(addr common.Address) []byte {
prefix := stakingPrefix
func validatorKey(addr common.Address) []byte {
prefix := validatorPrefix
return append(prefix, addr.Bytes()...)
}
func validatorSnapshotKey(addr common.Address) []byte {
prefix := validatorSnapshotPrefix
return append(prefix, addr.Bytes()...)
}

@ -354,7 +354,7 @@ func (st *StateTransition) applyCreateValidatorTx(createValidator *staking.Creat
delegations := []staking.Delegation{}
delegations = append(delegations, staking.NewDelegation(v.Address, createValidator.Amount))
wrapper := staking.ValidatorWrapper{*v, delegations, nil, nil}
wrapper := staking.ValidatorWrapper{*v, delegations}
if err := st.state.UpdateStakingInfo(v.Address, &wrapper); err != nil {
return err

@ -290,9 +290,9 @@ func (b *APIBackend) SendStakingTx(
return nil
}
// GetCurrentValidatorAddresses returns the address of active validators for current epoch
func (b *APIBackend) GetCurrentValidatorAddresses() []common.Address {
return b.hmy.BlockChain().CurrentValidatorAddresses()
// GetActiveValidatorAddresses returns the address of active validators for current epoch
func (b *APIBackend) GetActiveValidatorAddresses() []common.Address {
return b.hmy.BlockChain().ActiveValidatorAddresses()
}
// GetValidatorCandidates returns the up to date validator candidates for next epoch

@ -179,7 +179,7 @@ func (e *engineImpl) Finalize(
// Only do such at the last block of an epoch
if len(header.ShardState()) > 0 {
// TODO: make sure we are using the correct validator list
validators := chain.CurrentValidatorAddresses()
validators := chain.ActiveValidatorAddresses()
for _, validator := range validators {
wrapper := state.GetStakingInfo(validator)
if wrapper != nil {
@ -227,7 +227,7 @@ func QuorumForBlock(chain engine.ChainReader, h *block.Header, reCalculate bool)
return 0, errors.Errorf(
"cannot find shard %d in shard state", h.ShardID())
}
return (len(c.NodeList))*2/3 + 1, nil
return (len(c.Slots))*2/3 + 1, nil
}
// Similiar to VerifyHeader, which is only for verifying the block headers of one's own chain, this verification
@ -289,7 +289,7 @@ func GetPublicKeys(chain engine.ChainReader, header *block.Header, reCalculate b
)
}
var committerKeys []*bls.PublicKey
for _, member := range committee.NodeList {
for _, member := range committee.Slots {
committerKey := new(bls.PublicKey)
err := member.BlsPublicKey.ToLibBLSPublicKey(committerKey)
if err != nil {

@ -61,7 +61,7 @@ func AccumulateRewards(
)
}
var committerKeys []*bls.PublicKey
for _, member := range parentCommittee.NodeList {
for _, member := range parentCommittee.Slots {
committerKey := new(bls.PublicKey)
err := member.BlsPublicKey.ToLibBLSPublicKey(committerKey)
if err != nil {
@ -80,7 +80,7 @@ func AccumulateRewards(
accounts := []common.Address{}
for idx, member := range parentCommittee.NodeList {
for idx, member := range parentCommittee.Slots {
if signed, err := mask.IndexEnabled(idx); err != nil {
return ctxerror.New("cannot check for committer bit",
"committerIndex", idx,

@ -73,7 +73,7 @@ type Backend interface {
ResendCx(ctx context.Context, txID common.Hash) (uint64, bool)
IsLeader() bool
SendStakingTx(ctx context.Context, newStakingTx *staking.StakingTransaction) error
GetCurrentValidatorAddresses() []common.Address
GetActiveValidatorAddresses() []common.Address
GetValidatorCandidates() []common.Address
GetValidatorInformation(addr common.Address) *staking.Validator
GetDelegatorsInformation(addr common.Address) []*staking.Delegation

@ -153,7 +153,7 @@ func (s *PublicBlockChainAPI) GetValidators(ctx context.Context, epoch int64) (m
return nil, err
}
validators := make([]map[string]interface{}, 0)
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
validatorBalance := new(hexutil.Big)
validatorBalance, err = s.b.GetBalance(validator.EcdsaAddress)
if err != nil {
@ -193,8 +193,8 @@ func (s *PublicBlockChainAPI) GetBlockSigners(ctx context.Context, blockNr rpc.B
if err != nil {
return nil, err
}
pubkeys := make([]*bls.PublicKey, len(committee.NodeList))
for i, validator := range committee.NodeList {
pubkeys := make([]*bls.PublicKey, len(committee.Slots))
for i, validator := range committee.Slots {
pubkeys[i] = new(bls.PublicKey)
validator.BlsPublicKey.ToLibBLSPublicKey(pubkeys[i])
}
@ -210,7 +210,7 @@ func (s *PublicBlockChainAPI) GetBlockSigners(ctx context.Context, blockNr rpc.B
if err != nil {
return result, err
}
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
oneAddress, err := internal_common.AddressToBech32(validator.EcdsaAddress)
if err != nil {
return result, err
@ -241,8 +241,8 @@ func (s *PublicBlockChainAPI) IsBlockSigner(ctx context.Context, blockNr rpc.Blo
if err != nil {
return false, err
}
pubkeys := make([]*bls.PublicKey, len(committee.NodeList))
for i, validator := range committee.NodeList {
pubkeys := make([]*bls.PublicKey, len(committee.Slots))
for i, validator := range committee.Slots {
pubkeys[i] = new(bls.PublicKey)
validator.BlsPublicKey.ToLibBLSPublicKey(pubkeys[i])
}
@ -254,7 +254,7 @@ func (s *PublicBlockChainAPI) IsBlockSigner(ctx context.Context, blockNr rpc.Blo
if err != nil {
return false, err
}
for _, validator := range committee.NodeList {
for _, validator := range committee.Slots {
oneAddress, err := internal_common.AddressToBech32(validator.EcdsaAddress)
if err != nil {
return false, err

@ -298,7 +298,7 @@ func (node *Node) VerifyCrosslinkHeader(prevHeader, header *block.Header) error
var committerKeys []*bls.PublicKey
parseKeysSuccess := true
for _, member := range committee.NodeList {
for _, member := range committee.Slots {
committerKey := new(bls.PublicKey)
err = member.BlsPublicKey.ToLibBLSPublicKey(committerKey)
if err != nil {

@ -411,7 +411,7 @@ func (node *Node) AddNewBlock(newBlock *types.Block) error {
}
utils.Logger().Debug().Msgf("ValidatorInformation %v: %v", i, val)
}
currAddrs := node.Blockchain().CurrentValidatorAddresses()
currAddrs := node.Blockchain().ActiveValidatorAddresses()
utils.Logger().Debug().Msgf("CurrentValidators : %v", currAddrs)
candidates := node.Blockchain().ValidatorCandidates()
utils.Logger().Debug().Msgf("CandidateValidators : %v", candidates)

@ -201,7 +201,7 @@ func (node *Node) transitionIntoNextEpoch(shardState types.State) {
for _, c := range shardState {
utils.Logger().Debug().
Uint32("shardID", c.ShardID).
Str("nodeList", c.NodeList).
Str("nodeList", c.Slots).
Msg("new shard information")
}
myShardID, isNextLeader := findRoleInShardState(
@ -219,7 +219,7 @@ func (node *Node) transitionIntoNextEpoch(shardState types.State) {
// Update public keys
var publicKeys []*bls.PublicKey
for idx, nodeID := range myShardState.NodeList {
for idx, nodeID := range myShardState.Slots {
key := &bls.PublicKey{}
err := key.Deserialize(nodeID.BlsPublicKey[:])
if err != nil {
@ -249,7 +249,7 @@ func findRoleInShardState(
) (shardID uint32, isLeader bool) {
keyBytes := key.Serialize()
for idx, shard := range state {
for nodeIdx, nodeID := range shard.NodeList {
for nodeIdx, nodeID := range shard.Slots {
if bytes.Compare(nodeID.BlsPublicKey[:], keyBytes) == 0 {
return uint32(idx), nodeIdx == 0
}

@ -85,12 +85,12 @@ func preStakingEnabledCommittee(s shardingconfig.Instance) shard.State {
pubKey := shard.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(pub)
// TODO: directly read address for bls too
curNodeID := shard.NodeID{
curNodeID := shard.Slot{
common2.ParseAddr(hmyAccounts[index].Address),
pubKey,
nil,
}
com.NodeList = append(com.NodeList, curNodeID)
com.Slots = append(com.Slots, curNodeID)
}
// add FN runner's key
for j := shardHarmonyNodes; j < shardSize; j++ {
@ -100,12 +100,12 @@ func preStakingEnabledCommittee(s shardingconfig.Instance) shard.State {
pubKey := shard.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(pub)
// TODO: directly read address for bls too
curNodeID := shard.NodeID{
curNodeID := shard.Slot{
common2.ParseAddr(fnAccounts[index].Address),
pubKey,
nil,
}
com.NodeList = append(com.NodeList, curNodeID)
com.Slots = append(com.Slots, curNodeID)
}
shardState = append(shardState, com)
}
@ -137,7 +137,7 @@ func eposStakedCommittee(
hAccounts := s.HmyAccounts()
for i := 0; i < shardCount; i++ {
superComm[i] = shard.Committee{uint32(i), shard.NodeIDList{}}
superComm[i] = shard.Committee{uint32(i), shard.SlotList{}}
}
for i := range hAccounts {
@ -146,7 +146,7 @@ func eposStakedCommittee(
pub.DeserializeHexStr(hAccounts[i].BlsPublicKey)
pubKey := shard.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(pub)
superComm[spot].NodeList = append(superComm[spot].NodeList, shard.NodeID{
superComm[spot].Slots = append(superComm[spot].Slots, shard.Slot{
common2.ParseAddr(hAccounts[i].Address),
pubKey,
nil,
@ -164,7 +164,7 @@ func eposStakedCommittee(
for i := 0; i < stakedSlotsCount; i++ {
bucket := int(new(big.Int).Mod(staked[i].BlsPublicKey.Big(), shardBig).Int64())
slot := staked[i]
superComm[bucket].NodeList = append(superComm[bucket].NodeList, shard.NodeID{
superComm[bucket].Slots = append(superComm[bucket].Slots, shard.Slot{
slot.Address,
staked[i].BlsPublicKey,
&slot.Dec,
@ -191,10 +191,10 @@ func (def partialStakingEnabled) ComputePublicKeys(
allIdentities := make([][]*bls.PublicKey, len(superComm))
for i := range superComm {
allIdentities[i] = make([]*bls.PublicKey, len(superComm[i].NodeList))
for j := range superComm[i].NodeList {
allIdentities[i] = make([]*bls.PublicKey, len(superComm[i].Slots))
for j := range superComm[i].Slots {
identity := &bls.PublicKey{}
superComm[i].NodeList[j].BlsPublicKey.ToLibBLSPublicKey(identity)
superComm[i].Slots[j].BlsPublicKey.ToLibBLSPublicKey(identity)
allIdentities[i][j] = identity
}
}
@ -220,12 +220,12 @@ func (def partialStakingEnabled) ReadPublicKeysFromDB(
}
committerKeys := []*bls.PublicKey{}
for i := range subCommittee.NodeList {
for i := range subCommittee.Slots {
committerKey := new(bls.PublicKey)
err := subCommittee.NodeList[i].BlsPublicKey.ToLibBLSPublicKey(committerKey)
err := subCommittee.Slots[i].BlsPublicKey.ToLibBLSPublicKey(committerKey)
if err != nil {
return nil, ctxerror.New("cannot convert BLS public key",
"blsPublicKey", subCommittee.NodeList[i].BlsPublicKey).WithCause(err)
"blsPublicKey", subCommittee.Slots[i].BlsPublicKey).WithCause(err)
}
committerKeys = append(committerKeys, committerKey)
}

@ -34,27 +34,27 @@ type State []Committee
// BlsPublicKey defines the bls public key
type BlsPublicKey [PublicKeySizeInBytes]byte
// NodeID represents node id (BLS address)
type NodeID struct {
// Slot represents node id (BLS address)
type Slot struct {
EcdsaAddress common.Address `json:"ecdsa-address"`
BlsPublicKey BlsPublicKey `json:"bls-pubkey"`
// nil means not active, 0 means our node, >= 0 means staked node
StakeWithDelegationApplied *numeric.Dec `json:"staked-validator" rlp:"nil"`
}
// NodeIDList is a list of NodeIDList.
type NodeIDList []NodeID
// SlotList is a list of SlotList.
type SlotList []Slot
// Committee contains the active nodes in one shard
type Committee struct {
ShardID uint32 `json:"shard-id"`
NodeList NodeIDList `json:"subcommittee"`
ShardID uint32 `json:"shard-id"`
Slots SlotList `json:"subcommittee"`
}
// JSON produces a non-pretty printed JSON string of the SuperCommittee
func (ss State) JSON() string {
type t struct {
NodeID
Slot
EcdsaAddress string `json:"one-address"`
}
type v struct {
@ -64,12 +64,12 @@ func (ss State) JSON() string {
}
dump := make([]v, len(ss))
for i := range ss {
c := len(ss[i].NodeList)
c := len(ss[i].Slots)
dump[i].ShardID = ss[i].ShardID
dump[i].NodeList = make([]t, c)
dump[i].Count = c
for j := range ss[i].NodeList {
n := ss[i].NodeList[j]
for j := range ss[i].Slots {
n := ss[i].Slots[j]
dump[i].NodeList[j].BlsPublicKey = n.BlsPublicKey
dump[i].NodeList[j].StakeWithDelegationApplied = n.StakeWithDelegationApplied
dump[i].NodeList[j].EcdsaAddress = common2.MustAddressToBech32(n.EcdsaAddress)
@ -166,7 +166,7 @@ func CompareBlsPublicKey(k1, k2 BlsPublicKey) int {
}
// CompareNodeID compares two node IDs.
func CompareNodeID(id1, id2 *NodeID) int {
func CompareNodeID(id1, id2 *Slot) int {
if c := bytes.Compare(id1.EcdsaAddress[:], id2.EcdsaAddress[:]); c != 0 {
return c
}
@ -177,12 +177,12 @@ func CompareNodeID(id1, id2 *NodeID) int {
}
// DeepCopy returns a deep copy of the receiver.
func (l NodeIDList) DeepCopy() NodeIDList {
func (l SlotList) DeepCopy() SlotList {
return append(l[:0:0], l...)
}
// CompareNodeIDList compares two node ID lists.
func CompareNodeIDList(l1, l2 NodeIDList) int {
func CompareNodeIDList(l1, l2 SlotList) int {
commonLen := len(l1)
if commonLen > len(l2) {
commonLen = len(l2)
@ -205,7 +205,7 @@ func CompareNodeIDList(l1, l2 NodeIDList) int {
func (c Committee) DeepCopy() Committee {
r := Committee{}
r.ShardID = c.ShardID
r.NodeList = c.NodeList.DeepCopy()
r.Slots = c.Slots.DeepCopy()
return r
}
@ -217,7 +217,7 @@ func CompareCommittee(c1, c2 *Committee) int {
case c1.ShardID > c2.ShardID:
return +1
}
if c := CompareNodeIDList(c1.NodeList, c2.NodeList); c != 0 {
if c := CompareNodeIDList(c1.Slots, c2.Slots); c != 0 {
return c
}
return 0
@ -225,7 +225,7 @@ func CompareCommittee(c1, c2 *Committee) int {
// GetHashFromNodeList will sort the list, then use Keccak256 to hash the list
// NOTE: do not modify the underlining content for hash
func GetHashFromNodeList(nodeList []NodeID) []byte {
func GetHashFromNodeList(nodeList []Slot) []byte {
// in general, nodeList should not be empty
if nodeList == nil || len(nodeList) == 0 {
return []byte{}
@ -248,7 +248,7 @@ func (ss State) Hash() (h common.Hash) {
})
d := sha3.NewLegacyKeccak256()
for i := range copy {
hash := GetHashFromNodeList(copy[i].NodeList)
hash := GetHashFromNodeList(copy[i].Slots)
d.Write(hash)
}
d.Sum(h[:0])
@ -256,15 +256,15 @@ func (ss State) Hash() (h common.Hash) {
}
// CompareNodeIDByBLSKey compares two nodes by their ID; used to sort node list
func CompareNodeIDByBLSKey(n1 NodeID, n2 NodeID) int {
func CompareNodeIDByBLSKey(n1 Slot, n2 Slot) int {
return bytes.Compare(n1.BlsPublicKey[:], n2.BlsPublicKey[:])
}
// Serialize serialize NodeID into bytes
func (n NodeID) Serialize() []byte {
// Serialize serialize Slot into bytes
func (n Slot) Serialize() []byte {
return append(n.EcdsaAddress[:], n.BlsPublicKey[:]...)
}
func (n NodeID) String() string {
func (n Slot) String() string {
return "ECDSA: " + common2.MustAddressToBech32(n.EcdsaAddress) + ", BLS: " + hex.EncodeToString(n.BlsPublicKey[:])
}

@ -30,12 +30,12 @@ func init() {
}
func TestGetHashFromNodeList(t *testing.T) {
l1 := []NodeID{
l1 := []Slot{
{common.Address{0x11}, blsPubKey1, nil},
{common.Address{0x22}, blsPubKey2, nil},
{common.Address{0x33}, blsPubKey3, nil},
}
l2 := []NodeID{
l2 := []Slot{
{common.Address{0x22}, blsPubKey2, nil},
{common.Address{0x11}, blsPubKey1, nil},
{common.Address{0x33}, blsPubKey3, nil},
@ -51,7 +51,7 @@ func TestGetHashFromNodeList(t *testing.T) {
func TestHash(t *testing.T) {
com1 := Committee{
ShardID: 22,
NodeList: []NodeID{
Slots: []Slot{
{common.Address{0x12}, blsPubKey11, nil},
{common.Address{0x23}, blsPubKey22, nil},
{common.Address{0x11}, blsPubKey1, nil},
@ -59,7 +59,7 @@ func TestHash(t *testing.T) {
}
com2 := Committee{
ShardID: 2,
NodeList: []NodeID{
Slots: []Slot{
{common.Address{0x44}, blsPubKey4, nil},
{common.Address{0x55}, blsPubKey5, nil},
{common.Address{0x66}, blsPubKey6, nil},
@ -70,7 +70,7 @@ func TestHash(t *testing.T) {
com3 := Committee{
ShardID: 2,
NodeList: []NodeID{
Slots: []Slot{
{common.Address{0x44}, blsPubKey4, nil},
{common.Address{0x55}, blsPubKey5, nil},
{common.Address{0x66}, blsPubKey6, nil},
@ -78,7 +78,7 @@ func TestHash(t *testing.T) {
}
com4 := Committee{
ShardID: 22,
NodeList: []NodeID{
Slots: []Slot{
{common.Address{0x12}, blsPubKey11, nil},
{common.Address{0x23}, blsPubKey22, nil},
{common.Address{0x11}, blsPubKey1, nil},

@ -36,9 +36,6 @@ var (
type ValidatorWrapper struct {
Validator `json:"validator" yaml:"validator" rlp:"nil"`
Delegations []Delegation `json:"delegations" yaml:"delegations" rlp:"nil"`
// TODO: move snapshot into off-chain db.
SnapshotValidator *Validator `json:"snapshot_validator" yaml:"snaphost_validator" rlp:"nil"`
SnapshotDelegations []Delegation `json:"snapshot_delegations" yaml:"snapshot_delegations" rlp:"nil"`
}
// Validator - data fields for a validator

Loading…
Cancel
Save