github.com/dogestan/eth@v1.9.7/core/forkid/forkid.go (about)

     1  // Copyright 2019 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 forkid implements EIP-2124 (https://eips.ethereum.org/EIPS/eip-2124).
    18  package forkid
    19  
    20  import (
    21  	"encoding/binary"
    22  	"errors"
    23  	"hash/crc32"
    24  	"math"
    25  	"math/big"
    26  	"reflect"
    27  	"strings"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/core"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/params"
    33  )
    34  
    35  var (
    36  	// ErrRemoteStale is returned by the validator if a remote fork checksum is a
    37  	// subset of our already applied forks, but the announced next fork block is
    38  	// not on our already passed chain.
    39  	ErrRemoteStale = errors.New("remote needs update")
    40  
    41  	// ErrLocalIncompatibleOrStale is returned by the validator if a remote fork
    42  	// checksum does not match any local checksum variation, signalling that the
    43  	// two chains have diverged in the past at some point (possibly at genesis).
    44  	ErrLocalIncompatibleOrStale = errors.New("local incompatible or needs update")
    45  )
    46  
    47  // ID is a fork identifier as defined by EIP-2124.
    48  type ID struct {
    49  	Hash [4]byte // CRC32 checksum of the genesis block and passed fork block numbers
    50  	Next uint64  // Block number of the next upcoming fork, or 0 if no forks are known
    51  }
    52  
    53  // Filter is a fork id filter to validate a remotely advertised ID.
    54  type Filter func(id ID) error
    55  
    56  // NewID calculates the Ethereum fork ID from the chain config and head.
    57  func NewID(chain *core.BlockChain) ID {
    58  	return newID(
    59  		chain.Config(),
    60  		chain.Genesis().Hash(),
    61  		chain.CurrentHeader().Number.Uint64(),
    62  	)
    63  }
    64  
    65  // newID is the internal version of NewID, which takes extracted values as its
    66  // arguments instead of a chain. The reason is to allow testing the IDs without
    67  // having to simulate an entire blockchain.
    68  func newID(config *params.ChainConfig, genesis common.Hash, head uint64) ID {
    69  	// Calculate the starting checksum from the genesis hash
    70  	hash := crc32.ChecksumIEEE(genesis[:])
    71  
    72  	// Calculate the current fork checksum and the next fork block
    73  	var next uint64
    74  	for _, fork := range gatherForks(config) {
    75  		if fork <= head {
    76  			// Fork already passed, checksum the previous hash and the fork number
    77  			hash = checksumUpdate(hash, fork)
    78  			continue
    79  		}
    80  		next = fork
    81  		break
    82  	}
    83  	return ID{Hash: checksumToBytes(hash), Next: next}
    84  }
    85  
    86  // NewFilter creates a filter that returns if a fork ID should be rejected or not
    87  // based on the local chain's status.
    88  func NewFilter(chain *core.BlockChain) Filter {
    89  	return newFilter(
    90  		chain.Config(),
    91  		chain.Genesis().Hash(),
    92  		func() uint64 {
    93  			return chain.CurrentHeader().Number.Uint64()
    94  		},
    95  	)
    96  }
    97  
    98  // NewStaticFilter creates a filter at block zero.
    99  func NewStaticFilter(config *params.ChainConfig, genesis common.Hash) Filter {
   100  	head := func() uint64 { return 0 }
   101  	return newFilter(config, genesis, head)
   102  }
   103  
   104  // newFilter is the internal version of NewFilter, taking closures as its arguments
   105  // instead of a chain. The reason is to allow testing it without having to simulate
   106  // an entire blockchain.
   107  func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() uint64) Filter {
   108  	// Calculate the all the valid fork hash and fork next combos
   109  	var (
   110  		forks = gatherForks(config)
   111  		sums  = make([][4]byte, len(forks)+1) // 0th is the genesis
   112  	)
   113  	hash := crc32.ChecksumIEEE(genesis[:])
   114  	sums[0] = checksumToBytes(hash)
   115  	for i, fork := range forks {
   116  		hash = checksumUpdate(hash, fork)
   117  		sums[i+1] = checksumToBytes(hash)
   118  	}
   119  	// Add two sentries to simplify the fork checks and don't require special
   120  	// casing the last one.
   121  	forks = append(forks, math.MaxUint64) // Last fork will never be passed
   122  
   123  	// Create a validator that will filter out incompatible chains
   124  	return func(id ID) error {
   125  		// Run the fork checksum validation ruleset:
   126  		//   1. If local and remote FORK_CSUM matches, compare local head to FORK_NEXT.
   127  		//        The two nodes are in the same fork state currently. They might know
   128  		//        of differing future forks, but that's not relevant until the fork
   129  		//        triggers (might be postponed, nodes might be updated to match).
   130  		//      1a. A remotely announced but remotely not passed block is already passed
   131  		//          locally, disconnect, since the chains are incompatible.
   132  		//      1b. No remotely announced fork; or not yet passed locally, connect.
   133  		//   2. If the remote FORK_CSUM is a subset of the local past forks and the
   134  		//      remote FORK_NEXT matches with the locally following fork block number,
   135  		//      connect.
   136  		//        Remote node is currently syncing. It might eventually diverge from
   137  		//        us, but at this current point in time we don't have enough information.
   138  		//   3. If the remote FORK_CSUM is a superset of the local past forks and can
   139  		//      be completed with locally known future forks, connect.
   140  		//        Local node is currently syncing. It might eventually diverge from
   141  		//        the remote, but at this current point in time we don't have enough
   142  		//        information.
   143  		//   4. Reject in all other cases.
   144  		head := headfn()
   145  		for i, fork := range forks {
   146  			// If our head is beyond this fork, continue to the next (we have a dummy
   147  			// fork of maxuint64 as the last item to always fail this check eventually).
   148  			if head > fork {
   149  				continue
   150  			}
   151  			// Found the first unpassed fork block, check if our current state matches
   152  			// the remote checksum (rule #1).
   153  			if sums[i] == id.Hash {
   154  				// Fork checksum matched, check if a remote future fork block already passed
   155  				// locally without the local node being aware of it (rule #1a).
   156  				if id.Next > 0 && head >= id.Next {
   157  					return ErrLocalIncompatibleOrStale
   158  				}
   159  				// Haven't passed locally a remote-only fork, accept the connection (rule #1b).
   160  				return nil
   161  			}
   162  			// The local and remote nodes are in different forks currently, check if the
   163  			// remote checksum is a subset of our local forks (rule #2).
   164  			for j := 0; j < i; j++ {
   165  				if sums[j] == id.Hash {
   166  					// Remote checksum is a subset, validate based on the announced next fork
   167  					if forks[j] != id.Next {
   168  						return ErrRemoteStale
   169  					}
   170  					return nil
   171  				}
   172  			}
   173  			// Remote chain is not a subset of our local one, check if it's a superset by
   174  			// any chance, signalling that we're simply out of sync (rule #3).
   175  			for j := i + 1; j < len(sums); j++ {
   176  				if sums[j] == id.Hash {
   177  					// Yay, remote checksum is a superset, ignore upcoming forks
   178  					return nil
   179  				}
   180  			}
   181  			// No exact, subset or superset match. We are on differing chains, reject.
   182  			return ErrLocalIncompatibleOrStale
   183  		}
   184  		log.Error("Impossible fork ID validation", "id", id)
   185  		return nil // Something's very wrong, accept rather than reject
   186  	}
   187  }
   188  
   189  // checksum calculates the IEEE CRC32 checksum of a block number.
   190  func checksum(fork uint64) uint32 {
   191  	var blob [8]byte
   192  	binary.BigEndian.PutUint64(blob[:], fork)
   193  	return crc32.ChecksumIEEE(blob[:])
   194  }
   195  
   196  // checksumUpdate calculates the next IEEE CRC32 checksum based on the previous
   197  // one and a fork block number (equivalent to CRC32(original-blob || fork)).
   198  func checksumUpdate(hash uint32, fork uint64) uint32 {
   199  	var blob [8]byte
   200  	binary.BigEndian.PutUint64(blob[:], fork)
   201  	return crc32.Update(hash, crc32.IEEETable, blob[:])
   202  }
   203  
   204  // checksumToBytes converts a uint32 checksum into a [4]byte array.
   205  func checksumToBytes(hash uint32) [4]byte {
   206  	var blob [4]byte
   207  	binary.BigEndian.PutUint32(blob[:], hash)
   208  	return blob
   209  }
   210  
   211  // gatherForks gathers all the known forks and creates a sorted list out of them.
   212  func gatherForks(config *params.ChainConfig) []uint64 {
   213  	// Gather all the fork block numbers via reflection
   214  	kind := reflect.TypeOf(params.ChainConfig{})
   215  	conf := reflect.ValueOf(config).Elem()
   216  
   217  	var forks []uint64
   218  	for i := 0; i < kind.NumField(); i++ {
   219  		// Fetch the next field and skip non-fork rules
   220  		field := kind.Field(i)
   221  		if !strings.HasSuffix(field.Name, "Block") {
   222  			continue
   223  		}
   224  		if field.Type != reflect.TypeOf(new(big.Int)) {
   225  			continue
   226  		}
   227  		// Extract the fork rule block number and aggregate it
   228  		rule := conf.Field(i).Interface().(*big.Int)
   229  		if rule != nil {
   230  			forks = append(forks, rule.Uint64())
   231  		}
   232  	}
   233  	// Sort the fork block numbers to permit chronologival XOR
   234  	for i := 0; i < len(forks); i++ {
   235  		for j := i + 1; j < len(forks); j++ {
   236  			if forks[i] > forks[j] {
   237  				forks[i], forks[j] = forks[j], forks[i]
   238  			}
   239  		}
   240  	}
   241  	// Deduplicate block numbers applying multiple forks
   242  	for i := 1; i < len(forks); i++ {
   243  		if forks[i] == forks[i-1] {
   244  			forks = append(forks[:i], forks[i+1:]...)
   245  			i--
   246  		}
   247  	}
   248  	// Skip any forks in block 0, that's the genesis ruleset
   249  	if len(forks) > 0 && forks[0] == 0 {
   250  		forks = forks[1:]
   251  	}
   252  	return forks
   253  }