blockchain_diff_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. // testBlocks is the test parameters array for specific blocks.
  43. testBlocks = []testBlockParam{
  44. {
  45. // This txs params also used to default block.
  46. blockNr: 11,
  47. txs: []testTransactionParam{
  48. {
  49. to: common.Address{0x01},
  50. value: big.NewInt(1),
  51. gasPrice: big.NewInt(1),
  52. data: nil,
  53. },
  54. },
  55. },
  56. {
  57. blockNr: 12,
  58. txs: []testTransactionParam{
  59. {
  60. to: common.Address{0x01},
  61. value: big.NewInt(1),
  62. gasPrice: big.NewInt(1),
  63. data: nil,
  64. },
  65. {
  66. to: common.Address{0x02},
  67. value: big.NewInt(2),
  68. gasPrice: big.NewInt(2),
  69. data: nil,
  70. },
  71. },
  72. },
  73. {
  74. blockNr: 13,
  75. txs: []testTransactionParam{
  76. {
  77. to: common.Address{0x01},
  78. value: big.NewInt(1),
  79. gasPrice: big.NewInt(1),
  80. data: nil,
  81. },
  82. {
  83. to: common.Address{0x02},
  84. value: big.NewInt(2),
  85. gasPrice: big.NewInt(2),
  86. data: nil,
  87. },
  88. {
  89. to: common.Address{0x03},
  90. value: big.NewInt(3),
  91. gasPrice: big.NewInt(3),
  92. data: nil,
  93. },
  94. },
  95. },
  96. {
  97. blockNr: 14,
  98. txs: []testTransactionParam{},
  99. },
  100. }
  101. )
  102. type testTransactionParam struct {
  103. to common.Address
  104. value *big.Int
  105. gasPrice *big.Int
  106. data []byte
  107. }
  108. type testBlockParam struct {
  109. blockNr int
  110. txs []testTransactionParam
  111. }
  112. // testBackend is a mock implementation of the live Ethereum message handler. Its
  113. // purpose is to allow testing the request/reply workflows and wire serialization
  114. // in the `eth` protocol without actually doing any data processing.
  115. type testBackend struct {
  116. db ethdb.Database
  117. chain *BlockChain
  118. }
  119. // newTestBackend creates an empty chain and wraps it into a mock backend.
  120. func newTestBackend(blocks int, light bool) *testBackend {
  121. return newTestBackendWithGenerator(blocks, light)
  122. }
  123. // newTestBackend creates a chain with a number of explicitly defined blocks and
  124. // wraps it into a mock backend.
  125. func newTestBackendWithGenerator(blocks int, lightProcess bool) *testBackend {
  126. signer := types.HomesteadSigner{}
  127. // Create a database pre-initialize with a genesis block
  128. db := rawdb.NewMemoryDatabase()
  129. db.SetDiffStore(memorydb.New())
  130. (&Genesis{
  131. Config: params.TestChainConfig,
  132. Alloc: GenesisAlloc{testAddr: {Balance: big.NewInt(100000000000000000)}},
  133. }).MustCommit(db)
  134. chain, _ := NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil, EnablePersistDiff(860000))
  135. generator := func(i int, block *BlockGen) {
  136. // The chain maker doesn't have access to a chain, so the difficulty will be
  137. // lets unset (nil). Set it here to the correct value.
  138. block.SetCoinbase(testAddr)
  139. for idx, testBlock := range testBlocks {
  140. // Specific block setting, the index in this generator has 1 diff from specified blockNr.
  141. if i+1 == testBlock.blockNr {
  142. for _, testTransaction := range testBlock.txs {
  143. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), testTransaction.to,
  144. testTransaction.value, params.TxGas, testTransaction.gasPrice, testTransaction.data), signer, testKey)
  145. if err != nil {
  146. panic(err)
  147. }
  148. block.AddTxWithChain(chain, tx)
  149. }
  150. break
  151. }
  152. // Default block setting.
  153. if idx == len(testBlocks)-1 {
  154. // We want to simulate an empty middle block, having the same state as the
  155. // first one. The last is needs a state change again to force a reorg.
  156. for _, testTransaction := range testBlocks[0].txs {
  157. tx, err := types.SignTx(types.NewTransaction(block.TxNonce(testAddr), testTransaction.to,
  158. testTransaction.value, params.TxGas, testTransaction.gasPrice, testTransaction.data), signer, testKey)
  159. if err != nil {
  160. panic(err)
  161. }
  162. block.AddTxWithChain(chain, tx)
  163. }
  164. }
  165. }
  166. }
  167. bs, _ := GenerateChain(params.TestChainConfig, chain.Genesis(), ethash.NewFaker(), db, blocks, generator)
  168. if _, err := chain.InsertChain(bs); err != nil {
  169. panic(err)
  170. }
  171. if lightProcess {
  172. EnableLightProcessor(chain)
  173. }
  174. return &testBackend{
  175. db: db,
  176. chain: chain,
  177. }
  178. }
  179. // close tears down the transaction pool and chain behind the mock backend.
  180. func (b *testBackend) close() {
  181. b.chain.Stop()
  182. }
  183. func (b *testBackend) Chain() *BlockChain { return b.chain }
  184. func rawDataToDiffLayer(data rlp.RawValue) (*types.DiffLayer, error) {
  185. var diff types.DiffLayer
  186. hasher := sha3.NewLegacyKeccak256()
  187. err := rlp.DecodeBytes(data, &diff)
  188. if err != nil {
  189. return nil, err
  190. }
  191. hasher.Write(data)
  192. var diffHash common.Hash
  193. hasher.Sum(diffHash[:0])
  194. diff.DiffHash = diffHash
  195. hasher.Reset()
  196. return &diff, nil
  197. }
  198. func TestProcessDiffLayer(t *testing.T) {
  199. blockNum := 128
  200. fullBackend := newTestBackend(blockNum, false)
  201. falseDiff := 5
  202. defer fullBackend.close()
  203. lightBackend := newTestBackend(0, true)
  204. defer lightBackend.close()
  205. for i := 1; i <= blockNum-falseDiff; i++ {
  206. block := fullBackend.chain.GetBlockByNumber(uint64(i))
  207. if block == nil {
  208. t.Fatal("block should not be nil")
  209. }
  210. blockHash := block.Hash()
  211. rawDiff := fullBackend.chain.GetDiffLayerRLP(blockHash)
  212. if len(rawDiff) != 0 {
  213. diff, err := rawDataToDiffLayer(rawDiff)
  214. if err != nil {
  215. t.Errorf("failed to decode rawdata %v", err)
  216. }
  217. if diff == nil {
  218. continue
  219. }
  220. lightBackend.Chain().HandleDiffLayer(diff, "testpid", true)
  221. }
  222. _, err := lightBackend.chain.insertChain([]*types.Block{block}, true)
  223. if err != nil {
  224. t.Errorf("failed to insert block %v", err)
  225. }
  226. }
  227. currentBlock := lightBackend.chain.CurrentBlock()
  228. nextBlock := fullBackend.chain.GetBlockByNumber(currentBlock.NumberU64() + 1)
  229. rawDiff := fullBackend.chain.GetDiffLayerRLP(nextBlock.Hash())
  230. diff, _ := rawDataToDiffLayer(rawDiff)
  231. latestAccount, _ := snapshot.FullAccount(diff.Accounts[0].Blob)
  232. latestAccount.Balance = big.NewInt(0)
  233. bz, _ := rlp.EncodeToBytes(&latestAccount)
  234. diff.Accounts[0].Blob = bz
  235. lightBackend.Chain().HandleDiffLayer(diff, "testpid", true)
  236. _, err := lightBackend.chain.insertChain([]*types.Block{nextBlock}, true)
  237. if err != nil {
  238. t.Errorf("failed to process block %v", err)
  239. }
  240. // the diff cache should be cleared
  241. if len(lightBackend.chain.diffPeersToDiffHashes) != 0 {
  242. t.Errorf("the size of diffPeersToDiffHashes should be 0, but get %d", len(lightBackend.chain.diffPeersToDiffHashes))
  243. }
  244. if len(lightBackend.chain.diffHashToPeers) != 0 {
  245. t.Errorf("the size of diffHashToPeers should be 0, but get %d", len(lightBackend.chain.diffHashToPeers))
  246. }
  247. if len(lightBackend.chain.diffHashToBlockHash) != 0 {
  248. t.Errorf("the size of diffHashToBlockHash should be 0, but get %d", len(lightBackend.chain.diffHashToBlockHash))
  249. }
  250. if len(lightBackend.chain.blockHashToDiffLayers) != 0 {
  251. t.Errorf("the size of blockHashToDiffLayers should be 0, but get %d", len(lightBackend.chain.blockHashToDiffLayers))
  252. }
  253. }
  254. func TestFreezeDiffLayer(t *testing.T) {
  255. blockNum := 1024
  256. fullBackend := newTestBackend(blockNum, true)
  257. defer fullBackend.close()
  258. // Minus one empty block.
  259. if fullBackend.chain.diffQueue.Size() != blockNum-1 {
  260. t.Errorf("size of diff queue is wrong, expected: %d, get: %d", blockNum, fullBackend.chain.diffQueue.Size())
  261. }
  262. time.Sleep(diffLayerFreezerRecheckInterval + 1*time.Second)
  263. if fullBackend.chain.diffQueue.Size() != int(fullBackend.chain.triesInMemory) {
  264. t.Errorf("size of diff queue is wrong, expected: %d, get: %d", blockNum, fullBackend.chain.diffQueue.Size())
  265. }
  266. block := fullBackend.chain.GetBlockByNumber(uint64(blockNum / 2))
  267. diffStore := fullBackend.chain.db.DiffStore()
  268. rawData := rawdb.ReadDiffLayerRLP(diffStore, block.Hash())
  269. if len(rawData) == 0 {
  270. t.Error("do not find diff layer in db")
  271. }
  272. }
  273. func TestPruneDiffLayer(t *testing.T) {
  274. blockNum := 1024
  275. fullBackend := newTestBackend(blockNum, true)
  276. defer fullBackend.close()
  277. anotherFullBackend := newTestBackend(2*blockNum, true)
  278. defer anotherFullBackend.close()
  279. for num := uint64(1); num < uint64(blockNum); num++ {
  280. header := fullBackend.chain.GetHeaderByNumber(num)
  281. rawDiff := fullBackend.chain.GetDiffLayerRLP(header.Hash())
  282. if len(rawDiff) != 0 {
  283. diff, _ := rawDataToDiffLayer(rawDiff)
  284. fullBackend.Chain().HandleDiffLayer(diff, "testpid1", true)
  285. fullBackend.Chain().HandleDiffLayer(diff, "testpid2", true)
  286. }
  287. }
  288. fullBackend.chain.pruneDiffLayer()
  289. if len(fullBackend.chain.diffNumToBlockHashes) != maxDiffForkDist {
  290. t.Error("unexpected size of diffNumToBlockHashes")
  291. }
  292. if len(fullBackend.chain.diffPeersToDiffHashes) != 2 {
  293. t.Error("unexpected size of diffPeersToDiffHashes")
  294. }
  295. if len(fullBackend.chain.blockHashToDiffLayers) != maxDiffForkDist {
  296. t.Error("unexpected size of diffNumToBlockHashes")
  297. }
  298. if len(fullBackend.chain.diffHashToBlockHash) != maxDiffForkDist {
  299. t.Error("unexpected size of diffHashToBlockHash")
  300. }
  301. if len(fullBackend.chain.diffHashToPeers) != maxDiffForkDist {
  302. t.Error("unexpected size of diffHashToPeers")
  303. }
  304. blocks := make([]*types.Block, 0, blockNum)
  305. for i := blockNum + 1; i <= 2*blockNum; i++ {
  306. b := anotherFullBackend.chain.GetBlockByNumber(uint64(i))
  307. blocks = append(blocks, b)
  308. }
  309. fullBackend.chain.insertChain(blocks, true)
  310. fullBackend.chain.pruneDiffLayer()
  311. if len(fullBackend.chain.diffNumToBlockHashes) != 0 {
  312. t.Error("unexpected size of diffNumToBlockHashes")
  313. }
  314. if len(fullBackend.chain.diffPeersToDiffHashes) != 0 {
  315. t.Error("unexpected size of diffPeersToDiffHashes")
  316. }
  317. if len(fullBackend.chain.blockHashToDiffLayers) != 0 {
  318. t.Error("unexpected size of diffNumToBlockHashes")
  319. }
  320. if len(fullBackend.chain.diffHashToBlockHash) != 0 {
  321. t.Error("unexpected size of diffHashToBlockHash")
  322. }
  323. if len(fullBackend.chain.diffHashToPeers) != 0 {
  324. t.Error("unexpected size of diffHashToPeers")
  325. }
  326. }
  327. func TestGetDiffAccounts(t *testing.T) {
  328. blockNum := 128
  329. fullBackend := newTestBackend(blockNum, false)
  330. defer fullBackend.close()
  331. for _, testBlock := range testBlocks {
  332. block := fullBackend.chain.GetBlockByNumber(uint64(testBlock.blockNr))
  333. if block == nil {
  334. t.Fatal("block should not be nil")
  335. }
  336. blockHash := block.Hash()
  337. accounts, err := fullBackend.chain.GetDiffAccounts(blockHash)
  338. if err != nil {
  339. t.Errorf("get diff accounts eror for block number (%d): %v", testBlock.blockNr, err)
  340. }
  341. for idx, account := range accounts {
  342. if testAddr == account {
  343. break
  344. }
  345. if idx == len(accounts)-1 {
  346. t.Errorf("the diff accounts does't include addr: %v", testAddr)
  347. }
  348. }
  349. for _, transaction := range testBlock.txs {
  350. for idx, account := range accounts {
  351. if transaction.to == account {
  352. break
  353. }
  354. if idx == len(accounts)-1 {
  355. t.Errorf("the diff accounts does't include addr: %v", transaction.to)
  356. }
  357. }
  358. }
  359. }
  360. }