blockchain_diff_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright 2020 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. // Tests that abnormal program termination (i.e.crash) and restart doesn't leave
  17. // the database in some strange state with gaps in the chain, nor with block data
  18. // dangling in the future.
  19. package core
  20. import (
  21. "math/big"
  22. "testing"
  23. "time"
  24. "golang.org/x/crypto/sha3"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus/ethash"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state/snapshot"
  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/ethdb"
  33. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. )
  37. var (
  38. // testKey is a private key to use for funding a tester account.
  39. testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  40. // testAddr is the Ethereum address of the tester account.
  41. testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
  42. )
  43. // testBackend is a mock implementation of the live Ethereum message handler. Its
  44. // purpose is to allow testing the request/reply workflows and wire serialization
  45. // in the `eth` protocol without actually doing any data processing.
  46. type testBackend struct {
  47. db ethdb.Database
  48. chain *BlockChain
  49. }
  50. // newTestBackend creates an empty chain and wraps it into a mock backend.
  51. func newTestBackend(blocks int, light bool) *testBackend {
  52. return newTestBackendWithGenerator(blocks, light)
  53. }
  54. // newTestBackend creates a chain with a number of explicitly defined blocks and
  55. // wraps it into a mock backend.
  56. func newTestBackendWithGenerator(blocks int, lightProcess bool) *testBackend {
  57. signer := types.HomesteadSigner{}
  58. // Create a database pre-initialize with a genesis block
  59. db := rawdb.NewMemoryDatabase()
  60. db.SetDiffStore(memorydb.New())
  61. (&Genesis{
  62. Config: params.TestChainConfig,
  63. Alloc: GenesisAlloc{testAddr: {Balance: big.NewInt(100000000000000000)}},
  64. }).MustCommit(db)
  65. chain, _ := NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil, EnablePersistDiff(860000))
  66. generator := func(i int, block *BlockGen) {
  67. // The chain maker doesn't have access to a chain, so the difficulty will be
  68. // lets unset (nil). Set it here to the correct value.
  69. block.SetCoinbase(testAddr)
  70. // We want to simulate an empty middle block, having the same state as the
  71. // first one. The last is needs a state change again to force a reorg.
  72. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), common.Address{0x01}, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testKey)
  73. if err != nil {
  74. panic(err)
  75. }
  76. block.AddTxWithChain(chain, tx)
  77. }
  78. bs, _ := GenerateChain(params.TestChainConfig, chain.Genesis(), ethash.NewFaker(), db, blocks, generator)
  79. if _, err := chain.InsertChain(bs); err != nil {
  80. panic(err)
  81. }
  82. if lightProcess {
  83. EnableLightProcessor(chain)
  84. }
  85. return &testBackend{
  86. db: db,
  87. chain: chain,
  88. }
  89. }
  90. // close tears down the transaction pool and chain behind the mock backend.
  91. func (b *testBackend) close() {
  92. b.chain.Stop()
  93. }
  94. func (b *testBackend) Chain() *BlockChain { return b.chain }
  95. func rawDataToDiffLayer(data rlp.RawValue) (*types.DiffLayer, error) {
  96. var diff types.DiffLayer
  97. hasher := sha3.NewLegacyKeccak256()
  98. err := rlp.DecodeBytes(data, &diff)
  99. if err != nil {
  100. return nil, err
  101. }
  102. hasher.Write(data)
  103. var diffHash common.Hash
  104. hasher.Sum(diffHash[:0])
  105. diff.DiffHash = diffHash
  106. hasher.Reset()
  107. return &diff, nil
  108. }
  109. func TestProcessDiffLayer(t *testing.T) {
  110. t.Parallel()
  111. blockNum := 128
  112. fullBackend := newTestBackend(blockNum, false)
  113. falseDiff := 5
  114. defer fullBackend.close()
  115. lightBackend := newTestBackend(0, true)
  116. defer lightBackend.close()
  117. for i := 1; i <= blockNum-falseDiff; i++ {
  118. block := fullBackend.chain.GetBlockByNumber(uint64(i))
  119. if block == nil {
  120. t.Fatal("block should not be nil")
  121. }
  122. blockHash := block.Hash()
  123. rawDiff := fullBackend.chain.GetDiffLayerRLP(blockHash)
  124. diff, err := rawDataToDiffLayer(rawDiff)
  125. if err != nil {
  126. t.Errorf("failed to decode rawdata %v", err)
  127. }
  128. lightBackend.Chain().HandleDiffLayer(diff, "testpid", true)
  129. _, err = lightBackend.chain.insertChain([]*types.Block{block}, true)
  130. if err != nil {
  131. t.Errorf("failed to insert block %v", err)
  132. }
  133. }
  134. currentBlock := lightBackend.chain.CurrentBlock()
  135. nextBlock := fullBackend.chain.GetBlockByNumber(currentBlock.NumberU64() + 1)
  136. rawDiff := fullBackend.chain.GetDiffLayerRLP(nextBlock.Hash())
  137. diff, _ := rawDataToDiffLayer(rawDiff)
  138. latestAccount, _ := snapshot.FullAccount(diff.Accounts[0].Blob)
  139. latestAccount.Balance = big.NewInt(0)
  140. bz, _ := rlp.EncodeToBytes(&latestAccount)
  141. diff.Accounts[0].Blob = bz
  142. lightBackend.Chain().HandleDiffLayer(diff, "testpid", true)
  143. _, err := lightBackend.chain.insertChain([]*types.Block{nextBlock}, true)
  144. if err != nil {
  145. t.Errorf("failed to process block %v", err)
  146. }
  147. // the diff cache should be cleared
  148. if len(lightBackend.chain.diffPeersToDiffHashes) != 0 {
  149. t.Errorf("the size of diffPeersToDiffHashes should be 0, but get %d", len(lightBackend.chain.diffPeersToDiffHashes))
  150. }
  151. if len(lightBackend.chain.diffHashToPeers) != 0 {
  152. t.Errorf("the size of diffHashToPeers should be 0, but get %d", len(lightBackend.chain.diffHashToPeers))
  153. }
  154. if len(lightBackend.chain.diffHashToBlockHash) != 0 {
  155. t.Errorf("the size of diffHashToBlockHash should be 0, but get %d", len(lightBackend.chain.diffHashToBlockHash))
  156. }
  157. if len(lightBackend.chain.blockHashToDiffLayers) != 0 {
  158. t.Errorf("the size of blockHashToDiffLayers should be 0, but get %d", len(lightBackend.chain.blockHashToDiffLayers))
  159. }
  160. }
  161. func TestFreezeDiffLayer(t *testing.T) {
  162. t.Parallel()
  163. blockNum := 1024
  164. fullBackend := newTestBackend(blockNum, true)
  165. defer fullBackend.close()
  166. if fullBackend.chain.diffQueue.Size() != blockNum {
  167. t.Errorf("size of diff queue is wrong, expected: %d, get: %d", blockNum, fullBackend.chain.diffQueue.Size())
  168. }
  169. time.Sleep(diffLayerFreezerRecheckInterval + 1*time.Second)
  170. if fullBackend.chain.diffQueue.Size() != int(fullBackend.chain.triesInMemory) {
  171. t.Errorf("size of diff queue is wrong, expected: %d, get: %d", blockNum, fullBackend.chain.diffQueue.Size())
  172. }
  173. block := fullBackend.chain.GetBlockByNumber(uint64(blockNum / 2))
  174. diffStore := fullBackend.chain.db.DiffStore()
  175. rawData := rawdb.ReadDiffLayerRLP(diffStore, block.Hash())
  176. if len(rawData) == 0 {
  177. t.Error("do not find diff layer in db")
  178. }
  179. }
  180. func TestPruneDiffLayer(t *testing.T) {
  181. t.Parallel()
  182. blockNum := 1024
  183. fullBackend := newTestBackend(blockNum, true)
  184. defer fullBackend.close()
  185. anotherFullBackend := newTestBackend(2*blockNum, true)
  186. defer anotherFullBackend.close()
  187. for num := uint64(1); num < uint64(blockNum); num++ {
  188. header := fullBackend.chain.GetHeaderByNumber(num)
  189. rawDiff := fullBackend.chain.GetDiffLayerRLP(header.Hash())
  190. diff, _ := rawDataToDiffLayer(rawDiff)
  191. fullBackend.Chain().HandleDiffLayer(diff, "testpid1", true)
  192. fullBackend.Chain().HandleDiffLayer(diff, "testpid2", true)
  193. }
  194. fullBackend.chain.pruneDiffLayer()
  195. if len(fullBackend.chain.diffNumToBlockHashes) != maxDiffForkDist {
  196. t.Error("unexpected size of diffNumToBlockHashes")
  197. }
  198. if len(fullBackend.chain.diffPeersToDiffHashes) != 2 {
  199. t.Error("unexpected size of diffPeersToDiffHashes")
  200. }
  201. if len(fullBackend.chain.blockHashToDiffLayers) != maxDiffForkDist {
  202. t.Error("unexpected size of diffNumToBlockHashes")
  203. }
  204. if len(fullBackend.chain.diffHashToBlockHash) != maxDiffForkDist {
  205. t.Error("unexpected size of diffHashToBlockHash")
  206. }
  207. if len(fullBackend.chain.diffHashToPeers) != maxDiffForkDist {
  208. t.Error("unexpected size of diffHashToPeers")
  209. }
  210. blocks := make([]*types.Block, 0, blockNum)
  211. for i := blockNum + 1; i <= 2*blockNum; i++ {
  212. b := anotherFullBackend.chain.GetBlockByNumber(uint64(i))
  213. blocks = append(blocks, b)
  214. }
  215. fullBackend.chain.insertChain(blocks, true)
  216. fullBackend.chain.pruneDiffLayer()
  217. if len(fullBackend.chain.diffNumToBlockHashes) != 0 {
  218. t.Error("unexpected size of diffNumToBlockHashes")
  219. }
  220. if len(fullBackend.chain.diffPeersToDiffHashes) != 0 {
  221. t.Error("unexpected size of diffPeersToDiffHashes")
  222. }
  223. if len(fullBackend.chain.blockHashToDiffLayers) != 0 {
  224. t.Error("unexpected size of diffNumToBlockHashes")
  225. }
  226. if len(fullBackend.chain.diffHashToBlockHash) != 0 {
  227. t.Error("unexpected size of diffHashToBlockHash")
  228. }
  229. if len(fullBackend.chain.diffHashToPeers) != 0 {
  230. t.Error("unexpected size of diffHashToPeers")
  231. }
  232. }