forkid.go 8.6 KB

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