github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/consensus/dpos/api.go (about)

     1  // Copyright 2017 The elementalcore Authors
     2  // This file is part of the elementalcore library.
     3  //
     4  // The elementalcore library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The elementalcore library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the elementalcore library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package dpos
    18  
    19  import (
    20  	"github.com/Elemental-core/elementalcore/common"
    21  	"github.com/Elemental-core/elementalcore/consensus"
    22  	"github.com/Elemental-core/elementalcore/core/types"
    23  	"github.com/Elemental-core/elementalcore/rpc"
    24  
    25  	"math/big"
    26  )
    27  
    28  // API is a user facing RPC API to allow controlling the delegate and voting
    29  // mechanisms of the delegated-proof-of-stake
    30  type API struct {
    31  	chain consensus.ChainReader
    32  	dpos  *Dpos
    33  }
    34  
    35  // GetValidators retrieves the list of the validators at specified block
    36  func (api *API) GetValidators(number *rpc.BlockNumber) ([]common.Address, error) {
    37  	var header *types.Header
    38  	if number == nil || *number == rpc.LatestBlockNumber {
    39  		header = api.chain.CurrentHeader()
    40  	} else {
    41  		header = api.chain.GetHeaderByNumber(uint64(number.Int64()))
    42  	}
    43  	if header == nil {
    44  		return nil, errUnknownBlock
    45  	}
    46  
    47  	epochTrie, err := types.NewEpochTrie(header.DposContext.EpochHash, api.dpos.db)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	dposContext := types.DposContext{}
    52  	dposContext.SetEpoch(epochTrie)
    53  	validators, err := dposContext.GetValidators()
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	return validators, nil
    58  }
    59  
    60  // GetConfirmedBlockNumber retrieves the latest irreversible block
    61  func (api *API) GetConfirmedBlockNumber() (*big.Int, error) {
    62  	var err error
    63  	header := api.dpos.confirmedBlockHeader
    64  	if header == nil {
    65  		header, err = api.dpos.loadConfirmedBlockHeader(api.chain)
    66  		if err != nil {
    67  			return nil, err
    68  		}
    69  	}
    70  	return header.Number, nil
    71  }