block_validator_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. package core
  17. import (
  18. "encoding/json"
  19. "math/big"
  20. "runtime"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/consensus"
  25. "github.com/ethereum/go-ethereum/consensus/beacon"
  26. "github.com/ethereum/go-ethereum/consensus/clique"
  27. "github.com/ethereum/go-ethereum/consensus/ethash"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. // Tests that simple header verification works, for both good and bad blocks.
  35. func TestHeaderVerification(t *testing.T) {
  36. // Create a simple chain to verify
  37. var (
  38. testdb = rawdb.NewMemoryDatabase()
  39. gspec = &Genesis{Config: params.TestChainConfig}
  40. genesis = gspec.MustCommit(testdb)
  41. blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 8, nil)
  42. )
  43. headers := make([]*types.Header, len(blocks))
  44. for i, block := range blocks {
  45. headers[i] = block.Header()
  46. }
  47. // Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
  48. chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  49. defer chain.Stop()
  50. for i := 0; i < len(blocks); i++ {
  51. for j, valid := range []bool{true, false} {
  52. var results <-chan error
  53. if valid {
  54. engine := ethash.NewFaker()
  55. _, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
  56. } else {
  57. engine := ethash.NewFakeFailer(headers[i].Number.Uint64())
  58. _, results = engine.VerifyHeaders(chain, []*types.Header{headers[i]}, []bool{true})
  59. }
  60. // Wait for the verification result
  61. select {
  62. case result := <-results:
  63. if (result == nil) != valid {
  64. t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, result, valid)
  65. }
  66. case <-time.After(time.Second):
  67. t.Fatalf("test %d.%d: verification timeout", i, j)
  68. }
  69. // Make sure no more data is returned
  70. select {
  71. case result := <-results:
  72. t.Fatalf("test %d.%d: unexpected result returned: %v", i, j, result)
  73. case <-time.After(25 * time.Millisecond):
  74. }
  75. }
  76. chain.InsertChain(blocks[i : i+1])
  77. }
  78. }
  79. func TestHeaderVerificationForMergingClique(t *testing.T) { testHeaderVerificationForMerging(t, true) }
  80. func TestHeaderVerificationForMergingEthash(t *testing.T) { testHeaderVerificationForMerging(t, false) }
  81. // Tests the verification for eth1/2 merging, including pre-merge and post-merge
  82. func testHeaderVerificationForMerging(t *testing.T, isClique bool) {
  83. var (
  84. testdb = rawdb.NewMemoryDatabase()
  85. preBlocks []*types.Block
  86. postBlocks []*types.Block
  87. runEngine consensus.Engine
  88. chainConfig *params.ChainConfig
  89. merger = consensus.NewMerger(rawdb.NewMemoryDatabase())
  90. )
  91. if isClique {
  92. var (
  93. key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  94. addr = crypto.PubkeyToAddress(key.PublicKey)
  95. engine = clique.New(params.AllCliqueProtocolChanges.Clique, testdb)
  96. )
  97. genspec := &Genesis{
  98. ExtraData: make([]byte, 32+common.AddressLength+crypto.SignatureLength),
  99. Alloc: map[common.Address]GenesisAccount{
  100. addr: {Balance: big.NewInt(1)},
  101. },
  102. BaseFee: big.NewInt(params.InitialBaseFee),
  103. Difficulty: new(big.Int),
  104. }
  105. copy(genspec.ExtraData[32:], addr[:])
  106. genesis := genspec.MustCommit(testdb)
  107. genEngine := beacon.New(engine)
  108. preBlocks, _ = GenerateChain(params.AllCliqueProtocolChanges, genesis, genEngine, testdb, 8, nil)
  109. td := 0
  110. for i, block := range preBlocks {
  111. header := block.Header()
  112. if i > 0 {
  113. header.ParentHash = preBlocks[i-1].Hash()
  114. }
  115. header.Extra = make([]byte, 32+crypto.SignatureLength)
  116. header.Difficulty = big.NewInt(2)
  117. sig, _ := crypto.Sign(genEngine.SealHash(header).Bytes(), key)
  118. copy(header.Extra[len(header.Extra)-crypto.SignatureLength:], sig)
  119. preBlocks[i] = block.WithSeal(header)
  120. // calculate td
  121. td += int(block.Difficulty().Uint64())
  122. }
  123. config := *params.AllCliqueProtocolChanges
  124. config.TerminalTotalDifficulty = big.NewInt(int64(td))
  125. postBlocks, _ = GenerateChain(&config, preBlocks[len(preBlocks)-1], genEngine, testdb, 8, nil)
  126. chainConfig = &config
  127. runEngine = beacon.New(engine)
  128. } else {
  129. gspec := &Genesis{Config: params.TestChainConfig}
  130. genesis := gspec.MustCommit(testdb)
  131. genEngine := beacon.New(ethash.NewFaker())
  132. preBlocks, _ = GenerateChain(params.TestChainConfig, genesis, genEngine, testdb, 8, nil)
  133. td := 0
  134. for _, block := range preBlocks {
  135. // calculate td
  136. td += int(block.Difficulty().Uint64())
  137. }
  138. config := *params.TestChainConfig
  139. config.TerminalTotalDifficulty = big.NewInt(int64(td))
  140. postBlocks, _ = GenerateChain(params.TestChainConfig, preBlocks[len(preBlocks)-1], genEngine, testdb, 8, nil)
  141. chainConfig = &config
  142. runEngine = beacon.New(ethash.NewFaker())
  143. }
  144. preHeaders := make([]*types.Header, len(preBlocks))
  145. for i, block := range preBlocks {
  146. preHeaders[i] = block.Header()
  147. blob, _ := json.Marshal(block.Header())
  148. t.Logf("Log header before the merging %d: %v", block.NumberU64(), string(blob))
  149. }
  150. postHeaders := make([]*types.Header, len(postBlocks))
  151. for i, block := range postBlocks {
  152. postHeaders[i] = block.Header()
  153. blob, _ := json.Marshal(block.Header())
  154. t.Logf("Log header after the merging %d: %v", block.NumberU64(), string(blob))
  155. }
  156. // Run the header checker for blocks one-by-one, checking for both valid and invalid nonces
  157. chain, _ := NewBlockChain(testdb, nil, chainConfig, runEngine, vm.Config{}, nil, nil)
  158. defer chain.Stop()
  159. // Verify the blocks before the merging
  160. for i := 0; i < len(preBlocks); i++ {
  161. _, results := runEngine.VerifyHeaders(chain, []*types.Header{preHeaders[i]}, []bool{true})
  162. // Wait for the verification result
  163. select {
  164. case result := <-results:
  165. if result != nil {
  166. t.Errorf("test %d: verification failed %v", i, result)
  167. }
  168. case <-time.After(time.Second):
  169. t.Fatalf("test %d: verification timeout", i)
  170. }
  171. // Make sure no more data is returned
  172. select {
  173. case result := <-results:
  174. t.Fatalf("test %d: unexpected result returned: %v", i, result)
  175. case <-time.After(25 * time.Millisecond):
  176. }
  177. chain.InsertChain(preBlocks[i : i+1])
  178. }
  179. // Make the transition
  180. merger.ReachTTD()
  181. merger.FinalizePoS()
  182. // Verify the blocks after the merging
  183. for i := 0; i < len(postBlocks); i++ {
  184. _, results := runEngine.VerifyHeaders(chain, []*types.Header{postHeaders[i]}, []bool{true})
  185. // Wait for the verification result
  186. select {
  187. case result := <-results:
  188. if result != nil {
  189. t.Errorf("test %d: verification failed %v", i, result)
  190. }
  191. case <-time.After(time.Second):
  192. t.Fatalf("test %d: verification timeout", i)
  193. }
  194. // Make sure no more data is returned
  195. select {
  196. case result := <-results:
  197. t.Fatalf("test %d: unexpected result returned: %v", i, result)
  198. case <-time.After(25 * time.Millisecond):
  199. }
  200. chain.InsertBlockWithoutSetHead(postBlocks[i])
  201. }
  202. // Verify the blocks with pre-merge blocks and post-merge blocks
  203. var (
  204. headers []*types.Header
  205. seals []bool
  206. )
  207. for _, block := range preBlocks {
  208. headers = append(headers, block.Header())
  209. seals = append(seals, true)
  210. }
  211. for _, block := range postBlocks {
  212. headers = append(headers, block.Header())
  213. seals = append(seals, true)
  214. }
  215. _, results := runEngine.VerifyHeaders(chain, headers, seals)
  216. for i := 0; i < len(headers); i++ {
  217. select {
  218. case result := <-results:
  219. if result != nil {
  220. t.Errorf("test %d: verification failed %v", i, result)
  221. }
  222. case <-time.After(time.Second):
  223. t.Fatalf("test %d: verification timeout", i)
  224. }
  225. }
  226. // Make sure no more data is returned
  227. select {
  228. case result := <-results:
  229. t.Fatalf("unexpected result returned: %v", result)
  230. case <-time.After(25 * time.Millisecond):
  231. }
  232. }
  233. // Tests that concurrent header verification works, for both good and bad blocks.
  234. func TestHeaderConcurrentVerification2(t *testing.T) { testHeaderConcurrentVerification(t, 2) }
  235. func TestHeaderConcurrentVerification8(t *testing.T) { testHeaderConcurrentVerification(t, 8) }
  236. func TestHeaderConcurrentVerification32(t *testing.T) { testHeaderConcurrentVerification(t, 32) }
  237. func testHeaderConcurrentVerification(t *testing.T, threads int) {
  238. // Create a simple chain to verify
  239. var (
  240. testdb = rawdb.NewMemoryDatabase()
  241. gspec = &Genesis{Config: params.TestChainConfig}
  242. genesis = gspec.MustCommit(testdb)
  243. blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 8, nil)
  244. )
  245. headers := make([]*types.Header, len(blocks))
  246. seals := make([]bool, len(blocks))
  247. for i, block := range blocks {
  248. headers[i] = block.Header()
  249. seals[i] = true
  250. }
  251. // Set the number of threads to verify on
  252. old := runtime.GOMAXPROCS(threads)
  253. defer runtime.GOMAXPROCS(old)
  254. // Run the header checker for the entire block chain at once both for a valid and
  255. // also an invalid chain (enough if one arbitrary block is invalid).
  256. for i, valid := range []bool{true, false} {
  257. var results <-chan error
  258. if valid {
  259. chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
  260. _, results = chain.engine.VerifyHeaders(chain, headers, seals)
  261. chain.Stop()
  262. } else {
  263. chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeFailer(uint64(len(headers)-1)), vm.Config{}, nil, nil)
  264. _, results = chain.engine.VerifyHeaders(chain, headers, seals)
  265. chain.Stop()
  266. }
  267. // Wait for all the verification results
  268. checks := make(map[int]error)
  269. for j := 0; j < len(blocks); j++ {
  270. select {
  271. case result := <-results:
  272. checks[j] = result
  273. case <-time.After(time.Second):
  274. t.Fatalf("test %d.%d: verification timeout", i, j)
  275. }
  276. }
  277. // Check nonce check validity
  278. for j := 0; j < len(blocks); j++ {
  279. want := valid || (j < len(blocks)-2) // We chose the last-but-one nonce in the chain to fail
  280. if (checks[j] == nil) != want {
  281. t.Errorf("test %d.%d: validity mismatch: have %v, want %v", i, j, checks[j], want)
  282. }
  283. if !want {
  284. // A few blocks after the first error may pass verification due to concurrent
  285. // workers. We don't care about those in this test, just that the correct block
  286. // errors out.
  287. break
  288. }
  289. }
  290. // Make sure no more data is returned
  291. select {
  292. case result := <-results:
  293. t.Fatalf("test %d: unexpected result returned: %v", i, result)
  294. case <-time.After(25 * time.Millisecond):
  295. }
  296. }
  297. }
  298. // Tests that aborting a header validation indeed prevents further checks from being
  299. // run, as well as checks that no left-over goroutines are leaked.
  300. func TestHeaderConcurrentAbortion2(t *testing.T) { testHeaderConcurrentAbortion(t, 2) }
  301. func TestHeaderConcurrentAbortion8(t *testing.T) { testHeaderConcurrentAbortion(t, 8) }
  302. func TestHeaderConcurrentAbortion32(t *testing.T) { testHeaderConcurrentAbortion(t, 32) }
  303. func testHeaderConcurrentAbortion(t *testing.T, threads int) {
  304. // Create a simple chain to verify
  305. var (
  306. testdb = rawdb.NewMemoryDatabase()
  307. gspec = &Genesis{Config: params.TestChainConfig}
  308. genesis = gspec.MustCommit(testdb)
  309. blocks, _ = GenerateChain(params.TestChainConfig, genesis, ethash.NewFaker(), testdb, 1024, nil)
  310. )
  311. headers := make([]*types.Header, len(blocks))
  312. seals := make([]bool, len(blocks))
  313. for i, block := range blocks {
  314. headers[i] = block.Header()
  315. seals[i] = true
  316. }
  317. // Set the number of threads to verify on
  318. old := runtime.GOMAXPROCS(threads)
  319. defer runtime.GOMAXPROCS(old)
  320. // Start the verifications and immediately abort
  321. chain, _ := NewBlockChain(testdb, nil, params.TestChainConfig, ethash.NewFakeDelayer(time.Millisecond), vm.Config{}, nil, nil)
  322. defer chain.Stop()
  323. abort, results := chain.engine.VerifyHeaders(chain, headers, seals)
  324. close(abort)
  325. // Deplete the results channel
  326. verified := 0
  327. for depleted := false; !depleted; {
  328. select {
  329. case result := <-results:
  330. if result != nil {
  331. t.Errorf("header %d: validation failed: %v", verified, result)
  332. }
  333. verified++
  334. case <-time.After(50 * time.Millisecond):
  335. depleted = true
  336. }
  337. }
  338. // Check that abortion was honored by not processing too many POWs
  339. if verified > 2*threads {
  340. t.Errorf("verification count too large: have %d, want below %d", verified, 2*threads)
  341. }
  342. }
  343. func TestCalcGasLimit(t *testing.T) {
  344. for i, tc := range []struct {
  345. pGasLimit uint64
  346. max uint64
  347. min uint64
  348. }{
  349. {20000000, 20019530, 19980470},
  350. {40000000, 40039061, 39960939},
  351. } {
  352. // Increase
  353. if have, want := CalcGasLimit(tc.pGasLimit, 2*tc.pGasLimit), tc.max; have != want {
  354. t.Errorf("test %d: have %d want <%d", i, have, want)
  355. }
  356. // Decrease
  357. if have, want := CalcGasLimit(tc.pGasLimit, 0), tc.min; have != want {
  358. t.Errorf("test %d: have %d want >%d", i, have, want)
  359. }
  360. // Small decrease
  361. if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit-1), tc.pGasLimit-1; have != want {
  362. t.Errorf("test %d: have %d want %d", i, have, want)
  363. }
  364. // Small increase
  365. if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit+1), tc.pGasLimit+1; have != want {
  366. t.Errorf("test %d: have %d want %d", i, have, want)
  367. }
  368. // No change
  369. if have, want := CalcGasLimit(tc.pGasLimit, tc.pGasLimit), tc.pGasLimit; have != want {
  370. t.Errorf("test %d: have %d want %d", i, have, want)
  371. }
  372. }
  373. }