github.com/ConsenSys/Quorum@v20.10.0+incompatible/consensus/istanbul/backend/backend.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package backend
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"math/big"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/consensus"
    27  	"github.com/ethereum/go-ethereum/consensus/istanbul"
    28  	istanbulCore "github.com/ethereum/go-ethereum/consensus/istanbul/core"
    29  	"github.com/ethereum/go-ethereum/consensus/istanbul/validator"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/crypto"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/event"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	lru "github.com/hashicorp/golang-lru"
    37  )
    38  
    39  const (
    40  	// fetcherID is the ID indicates the block is from Istanbul engine
    41  	fetcherID = "istanbul"
    42  )
    43  
    44  // New creates an Ethereum backend for Istanbul core engine.
    45  func New(config *istanbul.Config, privateKey *ecdsa.PrivateKey, db ethdb.Database) consensus.Istanbul {
    46  	// Allocate the snapshot caches and create the engine
    47  	recents, _ := lru.NewARC(inmemorySnapshots)
    48  	recentMessages, _ := lru.NewARC(inmemoryPeers)
    49  	knownMessages, _ := lru.NewARC(inmemoryMessages)
    50  	backend := &backend{
    51  		config:           config,
    52  		istanbulEventMux: new(event.TypeMux),
    53  		privateKey:       privateKey,
    54  		address:          crypto.PubkeyToAddress(privateKey.PublicKey),
    55  		logger:           log.New(),
    56  		db:               db,
    57  		commitCh:         make(chan *types.Block, 1),
    58  		recents:          recents,
    59  		candidates:       make(map[common.Address]bool),
    60  		coreStarted:      false,
    61  		recentMessages:   recentMessages,
    62  		knownMessages:    knownMessages,
    63  	}
    64  	backend.core = istanbulCore.New(backend, backend.config)
    65  	return backend
    66  }
    67  
    68  // ----------------------------------------------------------------------------
    69  
    70  type backend struct {
    71  	config           *istanbul.Config
    72  	istanbulEventMux *event.TypeMux
    73  	privateKey       *ecdsa.PrivateKey
    74  	address          common.Address
    75  	core             istanbulCore.Engine
    76  	logger           log.Logger
    77  	db               ethdb.Database
    78  	chain            consensus.ChainReader
    79  	currentBlock     func() *types.Block
    80  	hasBadBlock      func(hash common.Hash) bool
    81  
    82  	// the channels for istanbul engine notifications
    83  	commitCh          chan *types.Block
    84  	proposedBlockHash common.Hash
    85  	sealMu            sync.Mutex
    86  	coreStarted       bool
    87  	coreMu            sync.RWMutex
    88  
    89  	// Current list of candidates we are pushing
    90  	candidates map[common.Address]bool
    91  	// Protects the signer fields
    92  	candidatesLock sync.RWMutex
    93  	// Snapshots for recent block to speed up reorgs
    94  	recents *lru.ARCCache
    95  
    96  	// event subscription for ChainHeadEvent event
    97  	broadcaster consensus.Broadcaster
    98  
    99  	recentMessages *lru.ARCCache // the cache of peer's messages
   100  	knownMessages  *lru.ARCCache // the cache of self messages
   101  }
   102  
   103  // zekun: HACK
   104  func (sb *backend) CalcDifficulty(chain consensus.ChainReader, time uint64, parent *types.Header) *big.Int {
   105  	return new(big.Int)
   106  }
   107  
   108  // Address implements istanbul.Backend.Address
   109  func (sb *backend) Address() common.Address {
   110  	return sb.address
   111  }
   112  
   113  // Validators implements istanbul.Backend.Validators
   114  func (sb *backend) Validators(proposal istanbul.Proposal) istanbul.ValidatorSet {
   115  	return sb.getValidators(proposal.Number().Uint64(), proposal.Hash())
   116  }
   117  
   118  // Broadcast implements istanbul.Backend.Broadcast
   119  func (sb *backend) Broadcast(valSet istanbul.ValidatorSet, payload []byte) error {
   120  	// send to others
   121  	sb.Gossip(valSet, payload)
   122  	// send to self
   123  	msg := istanbul.MessageEvent{
   124  		Payload: payload,
   125  	}
   126  	go sb.istanbulEventMux.Post(msg)
   127  	return nil
   128  }
   129  
   130  // Broadcast implements istanbul.Backend.Gossip
   131  func (sb *backend) Gossip(valSet istanbul.ValidatorSet, payload []byte) error {
   132  	hash := istanbul.RLPHash(payload)
   133  	sb.knownMessages.Add(hash, true)
   134  
   135  	targets := make(map[common.Address]bool)
   136  	for _, val := range valSet.List() {
   137  		if val.Address() != sb.Address() {
   138  			targets[val.Address()] = true
   139  		}
   140  	}
   141  	if sb.broadcaster != nil && len(targets) > 0 {
   142  		ps := sb.broadcaster.FindPeers(targets)
   143  		for addr, p := range ps {
   144  			ms, ok := sb.recentMessages.Get(addr)
   145  			var m *lru.ARCCache
   146  			if ok {
   147  				m, _ = ms.(*lru.ARCCache)
   148  				if _, k := m.Get(hash); k {
   149  					// This peer had this event, skip it
   150  					continue
   151  				}
   152  			} else {
   153  				m, _ = lru.NewARC(inmemoryMessages)
   154  			}
   155  
   156  			m.Add(hash, true)
   157  			sb.recentMessages.Add(addr, m)
   158  			go p.Send(istanbulMsg, payload)
   159  		}
   160  	}
   161  	return nil
   162  }
   163  
   164  // Commit implements istanbul.Backend.Commit
   165  func (sb *backend) Commit(proposal istanbul.Proposal, seals [][]byte) error {
   166  	// Check if the proposal is a valid block
   167  	block := &types.Block{}
   168  	block, ok := proposal.(*types.Block)
   169  	if !ok {
   170  		sb.logger.Error("Invalid proposal, %v", proposal)
   171  		return errInvalidProposal
   172  	}
   173  
   174  	h := block.Header()
   175  	// Append seals into extra-data
   176  	err := writeCommittedSeals(h, seals)
   177  	if err != nil {
   178  		return err
   179  	}
   180  	// update block's header
   181  	block = block.WithSeal(h)
   182  
   183  	sb.logger.Info("Committed", "address", sb.Address(), "hash", proposal.Hash(), "number", proposal.Number().Uint64())
   184  	// - if the proposed and committed blocks are the same, send the proposed hash
   185  	//   to commit channel, which is being watched inside the engine.Seal() function.
   186  	// - otherwise, we try to insert the block.
   187  	// -- if success, the ChainHeadEvent event will be broadcasted, try to build
   188  	//    the next block and the previous Seal() will be stopped.
   189  	// -- otherwise, a error will be returned and a round change event will be fired.
   190  	if sb.proposedBlockHash == block.Hash() {
   191  		// feed block hash to Seal() and wait the Seal() result
   192  		sb.commitCh <- block
   193  		return nil
   194  	}
   195  
   196  	if sb.broadcaster != nil {
   197  		sb.broadcaster.Enqueue(fetcherID, block)
   198  	}
   199  	return nil
   200  }
   201  
   202  // EventMux implements istanbul.Backend.EventMux
   203  func (sb *backend) EventMux() *event.TypeMux {
   204  	return sb.istanbulEventMux
   205  }
   206  
   207  // Verify implements istanbul.Backend.Verify
   208  func (sb *backend) Verify(proposal istanbul.Proposal) (time.Duration, error) {
   209  	// Check if the proposal is a valid block
   210  	block := &types.Block{}
   211  	block, ok := proposal.(*types.Block)
   212  	if !ok {
   213  		sb.logger.Error("Invalid proposal, %v", proposal)
   214  		return 0, errInvalidProposal
   215  	}
   216  
   217  	// check bad block
   218  	if sb.HasBadProposal(block.Hash()) {
   219  		return 0, core.ErrBlacklistedHash
   220  	}
   221  
   222  	// check block body
   223  	txnHash := types.DeriveSha(block.Transactions())
   224  	uncleHash := types.CalcUncleHash(block.Uncles())
   225  	if txnHash != block.Header().TxHash {
   226  		return 0, errMismatchTxhashes
   227  	}
   228  	if uncleHash != nilUncleHash {
   229  		return 0, errInvalidUncleHash
   230  	}
   231  
   232  	// verify the header of proposed block
   233  	err := sb.VerifyHeader(sb.chain, block.Header(), false)
   234  	// ignore errEmptyCommittedSeals error because we don't have the committed seals yet
   235  	if err == nil || err == errEmptyCommittedSeals {
   236  		return 0, nil
   237  	} else if err == consensus.ErrFutureBlock {
   238  		return time.Unix(int64(block.Header().Time), 0).Sub(now()), consensus.ErrFutureBlock
   239  	}
   240  	return 0, err
   241  }
   242  
   243  // Sign implements istanbul.Backend.Sign
   244  func (sb *backend) Sign(data []byte) ([]byte, error) {
   245  	hashData := crypto.Keccak256(data)
   246  	return crypto.Sign(hashData, sb.privateKey)
   247  }
   248  
   249  // CheckSignature implements istanbul.Backend.CheckSignature
   250  func (sb *backend) CheckSignature(data []byte, address common.Address, sig []byte) error {
   251  	signer, err := istanbul.GetSignatureAddress(data, sig)
   252  	if err != nil {
   253  		log.Error("Failed to get signer address", "err", err)
   254  		return err
   255  	}
   256  	// Compare derived addresses
   257  	if signer != address {
   258  		return errInvalidSignature
   259  	}
   260  	return nil
   261  }
   262  
   263  // HasPropsal implements istanbul.Backend.HashBlock
   264  func (sb *backend) HasPropsal(hash common.Hash, number *big.Int) bool {
   265  	return sb.chain.GetHeader(hash, number.Uint64()) != nil
   266  }
   267  
   268  // GetProposer implements istanbul.Backend.GetProposer
   269  func (sb *backend) GetProposer(number uint64) common.Address {
   270  	if h := sb.chain.GetHeaderByNumber(number); h != nil {
   271  		a, _ := sb.Author(h)
   272  		return a
   273  	}
   274  	return common.Address{}
   275  }
   276  
   277  // ParentValidators implements istanbul.Backend.GetParentValidators
   278  func (sb *backend) ParentValidators(proposal istanbul.Proposal) istanbul.ValidatorSet {
   279  	if block, ok := proposal.(*types.Block); ok {
   280  		return sb.getValidators(block.Number().Uint64()-1, block.ParentHash())
   281  	}
   282  	return validator.NewSet(nil, sb.config.ProposerPolicy)
   283  }
   284  
   285  func (sb *backend) getValidators(number uint64, hash common.Hash) istanbul.ValidatorSet {
   286  	snap, err := sb.snapshot(sb.chain, number, hash, nil)
   287  	if err != nil {
   288  		return validator.NewSet(nil, sb.config.ProposerPolicy)
   289  	}
   290  	return snap.ValSet
   291  }
   292  
   293  func (sb *backend) LastProposal() (istanbul.Proposal, common.Address) {
   294  	block := sb.currentBlock()
   295  
   296  	var proposer common.Address
   297  	if block.Number().Cmp(common.Big0) > 0 {
   298  		var err error
   299  		proposer, err = sb.Author(block.Header())
   300  		if err != nil {
   301  			sb.logger.Error("Failed to get block proposer", "err", err)
   302  			return nil, common.Address{}
   303  		}
   304  	}
   305  
   306  	// Return header only block here since we don't need block body
   307  	return block, proposer
   308  }
   309  
   310  func (sb *backend) HasBadProposal(hash common.Hash) bool {
   311  	if sb.hasBadBlock == nil {
   312  		return false
   313  	}
   314  	return sb.hasBadBlock(hash)
   315  }
   316  
   317  func (sb *backend) Close() error {
   318  	return nil
   319  }