github.com/nisdas/go-ethereum@v1.9.7/eth/protocol.go (about)

     1  // Copyright 2014 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  	"fmt"
    21  	"io"
    22  	"math/big"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  	"github.com/ethereum/go-ethereum/core"
    26  	"github.com/ethereum/go-ethereum/core/forkid"
    27  	"github.com/ethereum/go-ethereum/core/types"
    28  	"github.com/ethereum/go-ethereum/event"
    29  	"github.com/ethereum/go-ethereum/rlp"
    30  )
    31  
    32  // Constants to match up protocol versions and messages
    33  const (
    34  	eth63 = 63
    35  	eth64 = 64
    36  )
    37  
    38  // protocolName is the official short name of the protocol used during capability negotiation.
    39  const protocolName = "eth"
    40  
    41  // ProtocolVersions are the supported versions of the eth protocol (first is primary).
    42  var ProtocolVersions = []uint{eth64, eth63}
    43  
    44  // protocolLengths are the number of implemented message corresponding to different protocol versions.
    45  var protocolLengths = map[uint]uint64{eth64: 17, eth63: 17}
    46  
    47  const protocolMaxMsgSize = 10 * 1024 * 1024 // Maximum cap on the size of a protocol message
    48  
    49  // eth protocol message codes
    50  const (
    51  	StatusMsg          = 0x00
    52  	NewBlockHashesMsg  = 0x01
    53  	TxMsg              = 0x02
    54  	GetBlockHeadersMsg = 0x03
    55  	BlockHeadersMsg    = 0x04
    56  	GetBlockBodiesMsg  = 0x05
    57  	BlockBodiesMsg     = 0x06
    58  	NewBlockMsg        = 0x07
    59  	GetNodeDataMsg     = 0x0d
    60  	NodeDataMsg        = 0x0e
    61  	GetReceiptsMsg     = 0x0f
    62  	ReceiptsMsg        = 0x10
    63  )
    64  
    65  type errCode int
    66  
    67  const (
    68  	ErrMsgTooLarge = iota
    69  	ErrDecode
    70  	ErrInvalidMsgCode
    71  	ErrProtocolVersionMismatch
    72  	ErrNetworkIDMismatch
    73  	ErrGenesisMismatch
    74  	ErrForkIDRejected
    75  	ErrNoStatusMsg
    76  	ErrExtraStatusMsg
    77  )
    78  
    79  func (e errCode) String() string {
    80  	return errorToString[int(e)]
    81  }
    82  
    83  // XXX change once legacy code is out
    84  var errorToString = map[int]string{
    85  	ErrMsgTooLarge:             "Message too long",
    86  	ErrDecode:                  "Invalid message",
    87  	ErrInvalidMsgCode:          "Invalid message code",
    88  	ErrProtocolVersionMismatch: "Protocol version mismatch",
    89  	ErrNetworkIDMismatch:       "Network ID mismatch",
    90  	ErrGenesisMismatch:         "Genesis mismatch",
    91  	ErrForkIDRejected:          "Fork ID rejected",
    92  	ErrNoStatusMsg:             "No status message",
    93  	ErrExtraStatusMsg:          "Extra status message",
    94  }
    95  
    96  type txPool interface {
    97  	// AddRemotes should add the given transactions to the pool.
    98  	AddRemotes([]*types.Transaction) []error
    99  
   100  	// Pending should return pending transactions.
   101  	// The slice should be modifiable by the caller.
   102  	Pending() (map[common.Address]types.Transactions, error)
   103  
   104  	// SubscribeNewTxsEvent should return an event subscription of
   105  	// NewTxsEvent and send events to the given channel.
   106  	SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
   107  }
   108  
   109  // statusData63 is the network packet for the status message for eth/63.
   110  type statusData63 struct {
   111  	ProtocolVersion uint32
   112  	NetworkId       uint64
   113  	TD              *big.Int
   114  	CurrentBlock    common.Hash
   115  	GenesisBlock    common.Hash
   116  }
   117  
   118  // statusData is the network packet for the status message for eth/64 and later.
   119  type statusData struct {
   120  	ProtocolVersion uint32
   121  	NetworkID       uint64
   122  	TD              *big.Int
   123  	Head            common.Hash
   124  	Genesis         common.Hash
   125  	ForkID          forkid.ID
   126  }
   127  
   128  // newBlockHashesData is the network packet for the block announcements.
   129  type newBlockHashesData []struct {
   130  	Hash   common.Hash // Hash of one particular block being announced
   131  	Number uint64      // Number of one particular block being announced
   132  }
   133  
   134  // getBlockHeadersData represents a block header query.
   135  type getBlockHeadersData struct {
   136  	Origin  hashOrNumber // Block from which to retrieve headers
   137  	Amount  uint64       // Maximum number of headers to retrieve
   138  	Skip    uint64       // Blocks to skip between consecutive headers
   139  	Reverse bool         // Query direction (false = rising towards latest, true = falling towards genesis)
   140  }
   141  
   142  // hashOrNumber is a combined field for specifying an origin block.
   143  type hashOrNumber struct {
   144  	Hash   common.Hash // Block hash from which to retrieve headers (excludes Number)
   145  	Number uint64      // Block hash from which to retrieve headers (excludes Hash)
   146  }
   147  
   148  // EncodeRLP is a specialized encoder for hashOrNumber to encode only one of the
   149  // two contained union fields.
   150  func (hn *hashOrNumber) EncodeRLP(w io.Writer) error {
   151  	if hn.Hash == (common.Hash{}) {
   152  		return rlp.Encode(w, hn.Number)
   153  	}
   154  	if hn.Number != 0 {
   155  		return fmt.Errorf("both origin hash (%x) and number (%d) provided", hn.Hash, hn.Number)
   156  	}
   157  	return rlp.Encode(w, hn.Hash)
   158  }
   159  
   160  // DecodeRLP is a specialized decoder for hashOrNumber to decode the contents
   161  // into either a block hash or a block number.
   162  func (hn *hashOrNumber) DecodeRLP(s *rlp.Stream) error {
   163  	_, size, _ := s.Kind()
   164  	origin, err := s.Raw()
   165  	if err == nil {
   166  		switch {
   167  		case size == 32:
   168  			err = rlp.DecodeBytes(origin, &hn.Hash)
   169  		case size <= 8:
   170  			err = rlp.DecodeBytes(origin, &hn.Number)
   171  		default:
   172  			err = fmt.Errorf("invalid input size %d for origin", size)
   173  		}
   174  	}
   175  	return err
   176  }
   177  
   178  // newBlockData is the network packet for the block propagation message.
   179  type newBlockData struct {
   180  	Block *types.Block
   181  	TD    *big.Int
   182  }
   183  
   184  // sanityCheck verifies that the values are reasonable, as a DoS protection
   185  func (request *newBlockData) sanityCheck() error {
   186  	if err := request.Block.SanityCheck(); err != nil {
   187  		return err
   188  	}
   189  	//TD at mainnet block #7753254 is 76 bits. If it becomes 100 million times
   190  	// larger, it will still fit within 100 bits
   191  	if tdlen := request.TD.BitLen(); tdlen > 100 {
   192  		return fmt.Errorf("too large block TD: bitlen %d", tdlen)
   193  	}
   194  	return nil
   195  }
   196  
   197  // blockBody represents the data content of a single block.
   198  type blockBody struct {
   199  	Transactions []*types.Transaction // Transactions contained within a block
   200  	Uncles       []*types.Header      // Uncles contained within a block
   201  }
   202  
   203  // blockBodiesData is the network packet for block content distribution.
   204  type blockBodiesData []*blockBody