github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+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  // Address implements istanbul.Backend.Address
   104  func (sb *backend) Address() common.Address {
   105  	return sb.address
   106  }
   107  
   108  // Validators implements istanbul.Backend.Validators
   109  func (sb *backend) Validators(proposal istanbul.Proposal) istanbul.ValidatorSet {
   110  	return sb.getValidators(proposal.Number().Uint64(), proposal.Hash())
   111  }
   112  
   113  // Broadcast implements istanbul.Backend.Broadcast
   114  func (sb *backend) Broadcast(valSet istanbul.ValidatorSet, payload []byte) error {
   115  	// send to others
   116  	sb.Gossip(valSet, payload)
   117  	// send to self
   118  	msg := istanbul.MessageEvent{
   119  		Payload: payload,
   120  	}
   121  	go sb.istanbulEventMux.Post(msg)
   122  	return nil
   123  }
   124  
   125  // Broadcast implements istanbul.Backend.Gossip
   126  func (sb *backend) Gossip(valSet istanbul.ValidatorSet, payload []byte) error {
   127  	hash := istanbul.RLPHash(payload)
   128  	sb.knownMessages.Add(hash, true)
   129  
   130  	targets := make(map[common.Address]bool)
   131  	for _, val := range valSet.List() {
   132  		if val.Address() != sb.Address() {
   133  			targets[val.Address()] = true
   134  		}
   135  	}
   136  
   137  	if sb.broadcaster != nil && len(targets) > 0 {
   138  		ps := sb.broadcaster.FindPeers(targets)
   139  		for addr, p := range ps {
   140  			ms, ok := sb.recentMessages.Get(addr)
   141  			var m *lru.ARCCache
   142  			if ok {
   143  				m, _ = ms.(*lru.ARCCache)
   144  				if _, k := m.Get(hash); k {
   145  					// This peer had this event, skip it
   146  					continue
   147  				}
   148  			} else {
   149  				m, _ = lru.NewARC(inmemoryMessages)
   150  			}
   151  
   152  			m.Add(hash, true)
   153  			sb.recentMessages.Add(addr, m)
   154  
   155  			go p.Send(istanbulMsg, payload)
   156  		}
   157  	}
   158  	return nil
   159  }
   160  
   161  // Commit implements istanbul.Backend.Commit
   162  func (sb *backend) Commit(proposal istanbul.Proposal, seals [][]byte) error {
   163  	// Check if the proposal is a valid block
   164  	block := &types.Block{}
   165  	block, ok := proposal.(*types.Block)
   166  	if !ok {
   167  		sb.logger.Error("Invalid proposal, %v", proposal)
   168  		return errInvalidProposal
   169  	}
   170  
   171  	h := block.Header()
   172  	// Append seals into extra-data
   173  	err := writeCommittedSeals(h, seals)
   174  	if err != nil {
   175  		return err
   176  	}
   177  	// update block's header
   178  	block = block.WithSeal(h)
   179  
   180  	sb.logger.Info("Committed", "address", sb.Address(), "hash", proposal.Hash(), "number", proposal.Number().Uint64())
   181  	// - if the proposed and committed blocks are the same, send the proposed hash
   182  	//   to commit channel, which is being watched inside the engine.Seal() function.
   183  	// - otherwise, we try to insert the block.
   184  	// -- if success, the ChainHeadEvent event will be broadcasted, try to build
   185  	//    the next block and the previous Seal() will be stopped.
   186  	// -- otherwise, a error will be returned and a round change event will be fired.
   187  	if sb.proposedBlockHash == block.Hash() {
   188  		// feed block hash to Seal() and wait the Seal() result
   189  		sb.commitCh <- block
   190  		return nil
   191  	}
   192  
   193  	if sb.broadcaster != nil {
   194  		sb.broadcaster.Enqueue(fetcherID, block)
   195  	}
   196  	return nil
   197  }
   198  
   199  // EventMux implements istanbul.Backend.EventMux
   200  func (sb *backend) EventMux() *event.TypeMux {
   201  	return sb.istanbulEventMux
   202  }
   203  
   204  // Verify implements istanbul.Backend.Verify
   205  func (sb *backend) Verify(proposal istanbul.Proposal) (time.Duration, error) {
   206  	// Check if the proposal is a valid block
   207  	block := &types.Block{}
   208  	block, ok := proposal.(*types.Block)
   209  	if !ok {
   210  		sb.logger.Error("Invalid proposal, %v", proposal)
   211  		return 0, errInvalidProposal
   212  	}
   213  
   214  	// check bad block
   215  	if sb.HasBadProposal(block.Hash()) {
   216  		return 0, core.ErrBlacklistedHash
   217  	}
   218  
   219  	// check block body
   220  	txnHash := types.DeriveSha(block.Transactions())
   221  	uncleHash := types.CalcUncleHash(block.Uncles())
   222  	if txnHash != block.Header().TxHash {
   223  		return 0, errMismatchTxhashes
   224  	}
   225  	if uncleHash != nilUncleHash {
   226  		return 0, errInvalidUncleHash
   227  	}
   228  
   229  	// verify the header of proposed block
   230  	err := sb.VerifyHeader(sb.chain, block.Header(), false)
   231  	// ignore errEmptyCommittedSeals error because we don't have the committed seals yet
   232  	if err == nil || err == errEmptyCommittedSeals {
   233  		return 0, nil
   234  	} else if err == consensus.ErrFutureBlock {
   235  		return time.Unix(block.Header().Time.Int64(), 0).Sub(now()), consensus.ErrFutureBlock
   236  	}
   237  	return 0, err
   238  }
   239  
   240  // Sign implements istanbul.Backend.Sign
   241  func (sb *backend) Sign(data []byte) ([]byte, error) {
   242  	hashData := crypto.Keccak256([]byte(data))
   243  	return crypto.Sign(hashData, sb.privateKey)
   244  }
   245  
   246  // CheckSignature implements istanbul.Backend.CheckSignature
   247  func (sb *backend) CheckSignature(data []byte, address common.Address, sig []byte) error {
   248  	signer, err := istanbul.GetSignatureAddress(data, sig)
   249  	if err != nil {
   250  		log.Error("Failed to get signer address", "err", err)
   251  		return err
   252  	}
   253  	// Compare derived addresses
   254  	if signer != address {
   255  		return errInvalidSignature
   256  	}
   257  	return nil
   258  }
   259  
   260  // HasPropsal implements istanbul.Backend.HashBlock
   261  func (sb *backend) HasPropsal(hash common.Hash, number *big.Int) bool {
   262  	return sb.chain.GetHeader(hash, number.Uint64()) != nil
   263  }
   264  
   265  // GetProposer implements istanbul.Backend.GetProposer
   266  func (sb *backend) GetProposer(number uint64) common.Address {
   267  	if h := sb.chain.GetHeaderByNumber(number); h != nil {
   268  		a, _ := sb.Author(h)
   269  		return a
   270  	}
   271  	return common.Address{}
   272  }
   273  
   274  // ParentValidators implements istanbul.Backend.GetParentValidators
   275  func (sb *backend) ParentValidators(proposal istanbul.Proposal) istanbul.ValidatorSet {
   276  	if block, ok := proposal.(*types.Block); ok {
   277  		return sb.getValidators(block.Number().Uint64()-1, block.ParentHash())
   278  	}
   279  	return validator.NewSet(nil, sb.config.ProposerPolicy)
   280  }
   281  
   282  func (sb *backend) getValidators(number uint64, hash common.Hash) istanbul.ValidatorSet {
   283  	snap, err := sb.snapshot(sb.chain, number, hash, nil)
   284  	if err != nil {
   285  		return validator.NewSet(nil, sb.config.ProposerPolicy)
   286  	}
   287  	return snap.ValSet
   288  }
   289  
   290  func (sb *backend) LastProposal() (istanbul.Proposal, common.Address) {
   291  	block := sb.currentBlock()
   292  
   293  	var proposer common.Address
   294  	if block.Number().Cmp(common.Big0) > 0 {
   295  		var err error
   296  		proposer, err = sb.Author(block.Header())
   297  		if err != nil {
   298  			sb.logger.Error("Failed to get block proposer", "err", err)
   299  			return nil, common.Address{}
   300  		}
   301  	}
   302  
   303  	// Return header only block here since we don't need block body
   304  	return block, proposer
   305  }
   306  
   307  func (sb *backend) HasBadProposal(hash common.Hash) bool {
   308  	if sb.hasBadBlock == nil {
   309  		return false
   310  	}
   311  	return sb.hasBadBlock(hash)
   312  }