github.com/smalaichami/go-bowhead@v0.0.0-20180311002552-16302db95eaa/aht/peer.go (about)

     1  // Copyright 2015 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 eth
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"math/big"
    23  	"sync"
    24  	"time"
    25  
    26  	"github.com/smalaichami/go-bowhead/common"
    27  	"github.com/smalaichami/go-bowhead/core/types"
    28  	"github.com/smalaichami/go-bowhead/p2p"
    29  	"github.com/smalaichami/go-bowhead/rlp"
    30  	"gopkg.in/fatih/set.v0"
    31  )
    32  
    33  var (
    34  	errClosed            = errors.New("peer set is closed")
    35  	errAlreadyRegistered = errors.New("peer is already registered")
    36  	errNotRegistered     = errors.New("peer is not registered")
    37  )
    38  
    39  const (
    40  	maxKnownTxs      = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS)
    41  	maxKnownBlocks   = 1024  // Maximum block hashes to keep in the known list (prevent DOS)
    42  	handshakeTimeout = 5 * time.Second
    43  )
    44  
    45  // PeerInfo represents a short summary of the Ethereum sub-protocol metadata known
    46  // about a connected peer.
    47  type PeerInfo struct {
    48  	Version    int      `json:"version"`    // Ethereum protocol version negotiated
    49  	Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
    50  	Head       string   `json:"head"`       // SHA3 hash of the peer's best owned block
    51  }
    52  
    53  type peer struct {
    54  	id string
    55  
    56  	*p2p.Peer
    57  	rw p2p.MsgReadWriter
    58  
    59  	version  int         // Protocol version negotiated
    60  	forkDrop *time.Timer // Timed connection dropper if forks aren't validated in time
    61  
    62  	head common.Hash
    63  	td   *big.Int
    64  	lock sync.RWMutex
    65  
    66  	knownTxs    *set.Set // Set of transaction hashes known to be known by this peer
    67  	knownBlocks *set.Set // Set of block hashes known to be known by this peer
    68  }
    69  
    70  func newPeer(version int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
    71  	id := p.ID()
    72  
    73  	return &peer{
    74  		Peer:        p,
    75  		rw:          rw,
    76  		version:     version,
    77  		id:          fmt.Sprintf("%x", id[:8]),
    78  		knownTxs:    set.New(),
    79  		knownBlocks: set.New(),
    80  	}
    81  }
    82  
    83  // Info gathers and returns a collection of metadata known about a peer.
    84  func (p *peer) Info() *PeerInfo {
    85  	hash, td := p.Head()
    86  
    87  	return &PeerInfo{
    88  		Version:    p.version,
    89  		Difficulty: td,
    90  		Head:       hash.Hex(),
    91  	}
    92  }
    93  
    94  // Head retrieves a copy of the current head hash and total difficulty of the
    95  // peer.
    96  func (p *peer) Head() (hash common.Hash, td *big.Int) {
    97  	p.lock.RLock()
    98  	defer p.lock.RUnlock()
    99  
   100  	copy(hash[:], p.head[:])
   101  	return hash, new(big.Int).Set(p.td)
   102  }
   103  
   104  // SetHead updates the head hash and total difficulty of the peer.
   105  func (p *peer) SetHead(hash common.Hash, td *big.Int) {
   106  	p.lock.Lock()
   107  	defer p.lock.Unlock()
   108  
   109  	copy(p.head[:], hash[:])
   110  	p.td.Set(td)
   111  }
   112  
   113  // MarkBlock marks a block as known for the peer, ensuring that the block will
   114  // never be propagated to this particular peer.
   115  func (p *peer) MarkBlock(hash common.Hash) {
   116  	// If we reached the memory allowance, drop a previously known block hash
   117  	for p.knownBlocks.Size() >= maxKnownBlocks {
   118  		p.knownBlocks.Pop()
   119  	}
   120  	p.knownBlocks.Add(hash)
   121  }
   122  
   123  // MarkTransaction marks a transaction as known for the peer, ensuring that it
   124  // will never be propagated to this particular peer.
   125  func (p *peer) MarkTransaction(hash common.Hash) {
   126  	// If we reached the memory allowance, drop a previously known transaction hash
   127  	for p.knownTxs.Size() >= maxKnownTxs {
   128  		p.knownTxs.Pop()
   129  	}
   130  	p.knownTxs.Add(hash)
   131  }
   132  
   133  // SendTransactions sends transactions to the peer and includes the hashes
   134  // in its transaction hash set for future reference.
   135  func (p *peer) SendTransactions(txs types.Transactions) error {
   136  	for _, tx := range txs {
   137  		p.knownTxs.Add(tx.Hash())
   138  	}
   139  	return p2p.Send(p.rw, TxMsg, txs)
   140  }
   141  
   142  // SendNewBlockHashes announces the availability of a number of blocks through
   143  // a hash notification.
   144  func (p *peer) SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error {
   145  	for _, hash := range hashes {
   146  		p.knownBlocks.Add(hash)
   147  	}
   148  	request := make(newBlockHashesData, len(hashes))
   149  	for i := 0; i < len(hashes); i++ {
   150  		request[i].Hash = hashes[i]
   151  		request[i].Number = numbers[i]
   152  	}
   153  	return p2p.Send(p.rw, NewBlockHashesMsg, request)
   154  }
   155  
   156  // SendNewBlock propagates an entire block to a remote peer.
   157  func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
   158  	p.knownBlocks.Add(block.Hash())
   159  	return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
   160  }
   161  
   162  // SendBlockHeaders sends a batch of block headers to the remote peer.
   163  func (p *peer) SendBlockHeaders(headers []*types.Header) error {
   164  	return p2p.Send(p.rw, BlockHeadersMsg, headers)
   165  }
   166  
   167  // SendBlockBodies sends a batch of block contents to the remote peer.
   168  func (p *peer) SendBlockBodies(bodies []*blockBody) error {
   169  	return p2p.Send(p.rw, BlockBodiesMsg, blockBodiesData(bodies))
   170  }
   171  
   172  // SendBlockBodiesRLP sends a batch of block contents to the remote peer from
   173  // an already RLP encoded format.
   174  func (p *peer) SendBlockBodiesRLP(bodies []rlp.RawValue) error {
   175  	return p2p.Send(p.rw, BlockBodiesMsg, bodies)
   176  }
   177  
   178  // SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
   179  // hashes requested.
   180  func (p *peer) SendNodeData(data [][]byte) error {
   181  	return p2p.Send(p.rw, NodeDataMsg, data)
   182  }
   183  
   184  // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
   185  // ones requested from an already RLP encoded format.
   186  func (p *peer) SendReceiptsRLP(receipts []rlp.RawValue) error {
   187  	return p2p.Send(p.rw, ReceiptsMsg, receipts)
   188  }
   189  
   190  // RequestOneHeader is a wrapper around the header query functions to fetch a
   191  // single header. It is used solely by the fetcher.
   192  func (p *peer) RequestOneHeader(hash common.Hash) error {
   193  	p.Log().Debug("Fetching single header", "hash", hash)
   194  	return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: uint64(1), Skip: uint64(0), Reverse: false})
   195  }
   196  
   197  // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the
   198  // specified header query, based on the hash of an origin block.
   199  func (p *peer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
   200  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
   201  	return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
   202  }
   203  
   204  // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the
   205  // specified header query, based on the number of an origin block.
   206  func (p *peer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
   207  	p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
   208  	return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
   209  }
   210  
   211  // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes
   212  // specified.
   213  func (p *peer) RequestBodies(hashes []common.Hash) error {
   214  	p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
   215  	return p2p.Send(p.rw, GetBlockBodiesMsg, hashes)
   216  }
   217  
   218  // RequestNodeData fetches a batch of arbitrary data from a node's known state
   219  // data, corresponding to the specified hashes.
   220  func (p *peer) RequestNodeData(hashes []common.Hash) error {
   221  	p.Log().Debug("Fetching batch of state data", "count", len(hashes))
   222  	return p2p.Send(p.rw, GetNodeDataMsg, hashes)
   223  }
   224  
   225  // RequestReceipts fetches a batch of transaction receipts from a remote node.
   226  func (p *peer) RequestReceipts(hashes []common.Hash) error {
   227  	p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
   228  	return p2p.Send(p.rw, GetReceiptsMsg, hashes)
   229  }
   230  
   231  // Handshake executes the eth protocol handshake, negotiating version number,
   232  // network IDs, difficulties, head and genesis blocks.
   233  func (p *peer) Handshake(network uint64, td *big.Int, head common.Hash, genesis common.Hash) error {
   234  	// Send out own handshake in a new thread
   235  	errc := make(chan error, 2)
   236  	var status statusData // safe to read after two values have been received from errc
   237  
   238  	go func() {
   239  		errc <- p2p.Send(p.rw, StatusMsg, &statusData{
   240  			ProtocolVersion: uint32(p.version),
   241  			NetworkId:       network,
   242  			TD:              td,
   243  			CurrentBlock:    head,
   244  			GenesisBlock:    genesis,
   245  		})
   246  	}()
   247  	go func() {
   248  		errc <- p.readStatus(network, &status, genesis)
   249  	}()
   250  	timeout := time.NewTimer(handshakeTimeout)
   251  	defer timeout.Stop()
   252  	for i := 0; i < 2; i++ {
   253  		select {
   254  		case err := <-errc:
   255  			if err != nil {
   256  				return err
   257  			}
   258  		case <-timeout.C:
   259  			return p2p.DiscReadTimeout
   260  		}
   261  	}
   262  	p.td, p.head = status.TD, status.CurrentBlock
   263  	return nil
   264  }
   265  
   266  func (p *peer) readStatus(network uint64, status *statusData, genesis common.Hash) (err error) {
   267  	msg, err := p.rw.ReadMsg()
   268  	if err != nil {
   269  		return err
   270  	}
   271  	if msg.Code != StatusMsg {
   272  		return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
   273  	}
   274  	if msg.Size > ProtocolMaxMsgSize {
   275  		return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
   276  	}
   277  	// Decode the handshake and make sure everything matches
   278  	if err := msg.Decode(&status); err != nil {
   279  		return errResp(ErrDecode, "msg %v: %v", msg, err)
   280  	}
   281  	if status.GenesisBlock != genesis {
   282  		return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
   283  	}
   284  	if status.NetworkId != network {
   285  		return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)
   286  	}
   287  	if int(status.ProtocolVersion) != p.version {
   288  		return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
   289  	}
   290  	return nil
   291  }
   292  
   293  // String implements fmt.Stringer.
   294  func (p *peer) String() string {
   295  	return fmt.Sprintf("Peer %s [%s]", p.id,
   296  		fmt.Sprintf("eth/%2d", p.version),
   297  	)
   298  }
   299  
   300  // peerSet represents the collection of active peers currently participating in
   301  // the Ethereum sub-protocol.
   302  type peerSet struct {
   303  	peers  map[string]*peer
   304  	lock   sync.RWMutex
   305  	closed bool
   306  }
   307  
   308  // newPeerSet creates a new peer set to track the active participants.
   309  func newPeerSet() *peerSet {
   310  	return &peerSet{
   311  		peers: make(map[string]*peer),
   312  	}
   313  }
   314  
   315  // Register injects a new peer into the working set, or returns an error if the
   316  // peer is already known.
   317  func (ps *peerSet) Register(p *peer) error {
   318  	ps.lock.Lock()
   319  	defer ps.lock.Unlock()
   320  
   321  	if ps.closed {
   322  		return errClosed
   323  	}
   324  	if _, ok := ps.peers[p.id]; ok {
   325  		return errAlreadyRegistered
   326  	}
   327  	ps.peers[p.id] = p
   328  	return nil
   329  }
   330  
   331  // Unregister removes a remote peer from the active set, disabling any further
   332  // actions to/from that particular entity.
   333  func (ps *peerSet) Unregister(id string) error {
   334  	ps.lock.Lock()
   335  	defer ps.lock.Unlock()
   336  
   337  	if _, ok := ps.peers[id]; !ok {
   338  		return errNotRegistered
   339  	}
   340  	delete(ps.peers, id)
   341  	return nil
   342  }
   343  
   344  // Peer retrieves the registered peer with the given id.
   345  func (ps *peerSet) Peer(id string) *peer {
   346  	ps.lock.RLock()
   347  	defer ps.lock.RUnlock()
   348  
   349  	return ps.peers[id]
   350  }
   351  
   352  // Len returns if the current number of peers in the set.
   353  func (ps *peerSet) Len() int {
   354  	ps.lock.RLock()
   355  	defer ps.lock.RUnlock()
   356  
   357  	return len(ps.peers)
   358  }
   359  
   360  // PeersWithoutBlock retrieves a list of peers that do not have a given block in
   361  // their set of known hashes.
   362  func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
   363  	ps.lock.RLock()
   364  	defer ps.lock.RUnlock()
   365  
   366  	list := make([]*peer, 0, len(ps.peers))
   367  	for _, p := range ps.peers {
   368  		if !p.knownBlocks.Has(hash) {
   369  			list = append(list, p)
   370  		}
   371  	}
   372  	return list
   373  }
   374  
   375  // PeersWithoutTx retrieves a list of peers that do not have a given transaction
   376  // in their set of known hashes.
   377  func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
   378  	ps.lock.RLock()
   379  	defer ps.lock.RUnlock()
   380  
   381  	list := make([]*peer, 0, len(ps.peers))
   382  	for _, p := range ps.peers {
   383  		if !p.knownTxs.Has(hash) {
   384  			list = append(list, p)
   385  		}
   386  	}
   387  	return list
   388  }
   389  
   390  // BestPeer retrieves the known peer with the currently highest total difficulty.
   391  func (ps *peerSet) BestPeer() *peer {
   392  	ps.lock.RLock()
   393  	defer ps.lock.RUnlock()
   394  
   395  	var (
   396  		bestPeer *peer
   397  		bestTd   *big.Int
   398  	)
   399  	for _, p := range ps.peers {
   400  		if _, td := p.Head(); bestPeer == nil || td.Cmp(bestTd) > 0 {
   401  			bestPeer, bestTd = p, td
   402  		}
   403  	}
   404  	return bestPeer
   405  }
   406  
   407  // Close disconnects all peers.
   408  // No new peers can be registered after Close has returned.
   409  func (ps *peerSet) Close() {
   410  	ps.lock.Lock()
   411  	defer ps.lock.Unlock()
   412  
   413  	for _, p := range ps.peers {
   414  		p.Disconnect(p2p.DiscQuitting)
   415  	}
   416  	ps.closed = true
   417  }