Add missing staking related core code; and add some basic rpcs

pull/1836/head
Rongjian Lan 5 years ago
parent 77ff9d422d
commit bde9d38ed1
  1. 2
      block/factory/factory.go
  2. 4
      core/blockchain.go
  3. 2
      core/state_processor.go
  4. 47
      internal/hmyapi/blockchain.go
  5. 10
      internal/hmyapi/transactionpool.go
  6. 33
      internal/hmyapi/types.go
  7. 26
      node/node_handler.go
  8. 16
      staking/types/transaction.go
  9. 4
      staking/types/validator.go

@ -30,7 +30,7 @@ func NewFactory(chainConfig *params.ChainConfig) Factory {
func (f *factory) NewHeader(epoch *big.Int) *block.Header {
var impl blockif.Header
switch {
case epoch.Cmp(f.chainConfig.StakingEpoch) < 0: // REVERT BEFORE COMMIT
case epoch.Cmp(f.chainConfig.StakingEpoch) >= 0:
impl = v3.NewHeader()
case epoch.Cmp(f.chainConfig.CrossLinkEpoch) >= 0:
impl = v2.NewHeader()

@ -1171,7 +1171,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
}
// Do bookkeeping for new staking txns
//if bc.chainConfig.IsStaking(block.Epoch()) {
if bc.chainConfig.IsStaking(block.Epoch()) {
for _, tx := range block.StakingTransactions() {
err = bc.UpdateStakingMetaData(tx)
// keep offchain database consistency with onchain we need revert
@ -1181,7 +1181,7 @@ func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.
return NonStatTy, err
}
}
//}
}
//// Cross-links
if len(header.CrossLinks()) > 0 {

@ -266,9 +266,7 @@ func ApplyIncomingReceipt(config *params.ChainConfig, db *state.DB, header *bloc
// requires a signer to derive the sender.
// put it here to avoid cyclic import
func StakingToMessage(tx *staking.StakingTransaction, blockNum *big.Int) (types.Message, error) {
utils.Logger().Info().Msgf("ApplyStakingMessage: aaaaaa:")
payload, err := tx.RLPEncodeStakeMsg()
utils.Logger().Info().Msgf("ApplyStakingMessage: aaaaaa:", err)
if err != nil {
return types.Message{}, err
}

@ -2,6 +2,7 @@ package hmyapi
import (
"context"
"errors"
"fmt"
"math/big"
@ -298,33 +299,6 @@ func (s *PublicBlockChainAPI) GetLeader(ctx context.Context) string {
return s.LatestHeader(ctx).Leader
}
// GetValidatorInformation returns full validator info.
func (s *PublicBlockChainAPI) GetValidatorInformation(ctx context.Context, address string) (map[string]interface{}, error) {
validator := s.b.GetValidatorInformation(internal_common.ParseAddr(address))
slotPubKeys := make([]string, 0)
for _, slotPubKey := range validator.SlotPubKeys {
slotPubKeys = append(slotPubKeys, slotPubKey.Hex())
}
fields := map[string]interface{}{
"address": validator.Address.String(),
"stake": hexutil.Uint64(validator.Stake.Uint64()),
"name": validator.Description.Name,
"slotPubKeys": slotPubKeys,
"unbondingHeight": hexutil.Uint64(validator.UnbondingHeight.Uint64()),
"minSelfDelegation": hexutil.Uint64(validator.MinSelfDelegation.Uint64()),
"active": validator.Active,
"identity": validator.Description.Identity,
"commissionRate": hexutil.Uint64(validator.Commission.CommissionRates.Rate.Int.Uint64()),
"commissionUpdateHeight": hexutil.Uint64(validator.Commission.UpdateHeight.Uint64()),
"commissionMaxRate": hexutil.Uint64(validator.Commission.CommissionRates.MaxRate.Uint64()),
"commissionMaxChangeRate": hexutil.Uint64(validator.Commission.CommissionRates.MaxChangeRate.Uint64()),
"website": validator.Description.Website,
"securityContact": validator.Description.SecurityContact,
"details": validator.Description.Details,
}
return fields, nil
}
// GetStake returns validator stake.
func (s *PublicBlockChainAPI) GetStake(ctx context.Context, address string) hexutil.Uint64 {
validator := s.b.GetValidatorInformation(internal_common.ParseAddr(address))
@ -529,3 +503,22 @@ func (s *PublicBlockChainAPI) LatestHeader(ctx context.Context) *HeaderInformati
header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
return newHeaderInformation(header)
}
// GetAllValidatorAddresses returns all validator addresses.
func (s *PublicBlockChainAPI) GetAllValidatorAddresses() ([]common.Address, error) {
return s.b.GetAllValidatorAddresses(), nil
}
// GetActiveValidatorAddresses returns active validator addresses.
func (s *PublicBlockChainAPI) GetActiveValidatorAddresses() ([]common.Address, error) {
return s.b.GetActiveValidatorAddresses(), nil
}
// GetValidatorInfo returns information about a validator.
func (s *PublicBlockChainAPI) GetValidatorInfo(ctx context.Context, address common.Address) (*RPCValidator, error) {
validator := s.b.GetValidatorInformation(address)
if validator == nil {
return nil, errors.New(fmt.Sprintf("validator not found: %s", address.Hex()))
}
return newRPCValidator(validator), nil
}

@ -298,13 +298,3 @@ func (s *PublicTransactionPoolAPI) GetCXReceiptByHash(ctx context.Context, hash
}
return nil
}
// GetAllValidatorAddresses returns ...
func (s *PublicTransactionPoolAPI) GetAllValidatorAddresses() ([]common.Address, error) {
return s.b.GetAllValidatorAddresses(), nil
}
// GetActiveValidatorAddresses returns ...
func (s *PublicTransactionPoolAPI) GetActiveValidatorAddresses() ([]common.Address, error) {
return s.b.GetActiveValidatorAddresses(), nil
}

@ -6,6 +6,10 @@ import (
"strings"
"time"
"github.com/harmony-one/harmony/shard"
types2 "github.com/harmony-one/harmony/staking/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
ethtypes "github.com/ethereum/go-ethereum/core/types"
@ -60,6 +64,20 @@ type HeaderInformation struct {
LastCommitBitmap string `json:"lastCommitBitmap"`
}
// RPCValidator represents a validator
type RPCValidator struct {
Address common.Address `json:"address"`
SlotPubKeys []shard.BlsPublicKey `json:"slot_pub_keys"`
Stake *big.Int `json:"stake" yaml:"stake"`
UnbondingHeight *big.Int `json:"unbonding_height"`
MinSelfDelegation *big.Int `json:"min_self_delegation"`
MaxTotalDelegation *big.Int `json:"min_self_delegation"`
Active bool `json:"active"`
Commission types2.Commission `json:"commission"`
Description types2.Description `json:"description"`
CreationHeight *big.Int `json:"creation_height"`
}
func newHeaderInformation(header *block.Header) *HeaderInformation {
if header == nil {
return nil
@ -118,6 +136,21 @@ func newRPCCXReceipt(cx *types.CXReceipt, blockHash common.Hash, blockNumber uin
return result
}
func newRPCValidator(validator *types2.Validator) *RPCValidator {
return &RPCValidator{
validator.Address,
validator.SlotPubKeys,
validator.Stake,
validator.UnbondingHeight,
validator.MinSelfDelegation,
validator.MaxTotalDelegation,
validator.Active,
validator.Commission,
validator.Description,
validator.CreationHeight,
}
}
// newRPCTransaction returns a transaction that will serialize to the RPC
// representation, with the given location metadata set (if available).
func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {

@ -401,19 +401,19 @@ func (node *Node) AddNewBlock(newBlock *types.Block) error {
_, err := node.Blockchain().InsertChain([]*types.Block{newBlock}, true /* verifyHeaders */)
// Debug only
addrs, err := node.Blockchain().ReadValidatorList()
utils.Logger().Debug().Msgf("validator list updated, err=%v, len(addrs)=%v", err, len(addrs))
for i, addr := range addrs {
val, err := node.Blockchain().ValidatorInformation(addr)
if err != nil {
utils.Logger().Debug().Msgf("ValidatorInformation Error %v: err %v", i, err)
}
utils.Logger().Debug().Msgf("ValidatorInformation %v: %v", i, val)
}
currAddrs, err := node.Blockchain().ReadActiveValidatorList()
utils.Logger().Debug().Msgf("CurrentValidators : %v", currAddrs)
candidates := node.Blockchain().ValidatorCandidates()
utils.Logger().Debug().Msgf("CandidateValidators : %v", candidates)
//addrs, err := node.Blockchain().ReadValidatorList()
//utils.Logger().Debug().Msgf("validator list updated, err=%v, len(addrs)=%v", err, len(addrs))
//for i, addr := range addrs {
// val, err := node.Blockchain().ValidatorInformation(addr)
// if err != nil {
// utils.Logger().Debug().Msgf("ValidatorInformation Error %v: err %v", i, err)
// }
// utils.Logger().Debug().Msgf("ValidatorInformation %v: %v", i, val)
//}
//currAddrs, err := node.Blockchain().ReadActiveValidatorList()
//utils.Logger().Debug().Msgf("CurrentValidators : %v", currAddrs)
//candidates := node.Blockchain().ValidatorCandidates()
//utils.Logger().Debug().Msgf("CandidateValidators : %v", candidates)
// Finish debug
if err != nil {

@ -4,6 +4,7 @@ import (
"errors"
"io"
"math/big"
"reflect"
"sync/atomic"
"github.com/ethereum/go-ethereum/common"
@ -34,20 +35,7 @@ func (d *txdata) CopyFrom(d2 *txdata) {
d.AccountNonce = d2.AccountNonce
d.Price = new(big.Int).Set(d2.Price)
d.GasLimit = d2.GasLimit
//switch d.Directive { // TODO: make these deep copies.
//case DirectiveCreateValidator:
// d.StakeMsg = d2.StakeMsg.(CreateValidator)
//case DirectiveEditValidator:
// d.StakeMsg = d2.StakeMsg.(EditValidator)
//case DirectiveDelegate:
// d.StakeMsg = d2.StakeMsg.(Delegate)
//case DirectiveUndelegate:
// d.StakeMsg = d2.StakeMsg.(Undelegate)
//case DirectiveCollectRewards:
// d.StakeMsg = d2.StakeMsg.(CollectRewards)
//default:
// return
//}
d.StakeMsg = reflect.New(reflect.ValueOf(d2.StakeMsg).Elem().Type()).Interface()
d.V = new(big.Int).Set(d2.V)
d.R = new(big.Int).Set(d2.R)
d.S = new(big.Int).Set(d2.S)

@ -31,7 +31,7 @@ var (
errMinSelfDelegationTooSmall = errors.New("min_self_delegation has to be greater than 1 ONE")
errInvalidMaxTotalDelegation = errors.New("max_total_delegation can not be less than min_self_delegation")
errCommissionRateTooLarge = errors.New("commission rate and change rate can not be larger than max commission rate")
errInvalidComissionRate = errors.New("commission rate, change rate and max rate should be within 0-100%")
errInvalidComissionRate = errors.New("commission rate, change rate and max rate should be within 0-100 percent")
)
// ValidatorWrapper contains validator and its delegation information
@ -45,7 +45,7 @@ type Validator struct {
// ECDSA address of the validator
Address common.Address `json:"address" yaml:"address"`
// The BLS public key of the validator for consensus
SlotPubKeys []shard.BlsPublicKey `json:"validating_pub_key" yaml:"validating_pub_key"`
SlotPubKeys []shard.BlsPublicKey `json:"slot_pub_keys" yaml:"slot_pub_keys"`
// The stake put by the validator itself
Stake *big.Int `json:"stake" yaml:"stake"`
// if unbonding, height at which this validator has begun unbonding

Loading…
Cancel
Save