accessors_chain_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. // Copyright 2018 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 rawdb
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "math/big"
  22. "math/rand"
  23. "os"
  24. "reflect"
  25. "testing"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/params"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. "golang.org/x/crypto/sha3"
  32. )
  33. // Tests block header storage and retrieval operations.
  34. func TestHeaderStorage(t *testing.T) {
  35. db := NewMemoryDatabase()
  36. // Create a test header to move around the database and make sure it's really new
  37. header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
  38. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  39. t.Fatalf("Non existent header returned: %v", entry)
  40. }
  41. // Write and verify the header in the database
  42. WriteHeader(db, header)
  43. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
  44. t.Fatalf("Stored header not found")
  45. } else if entry.Hash() != header.Hash() {
  46. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  47. }
  48. if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
  49. t.Fatalf("Stored header RLP not found")
  50. } else {
  51. hasher := sha3.NewLegacyKeccak256()
  52. hasher.Write(entry)
  53. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  54. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  55. }
  56. }
  57. // Delete the header and verify the execution
  58. DeleteHeader(db, header.Hash(), header.Number.Uint64())
  59. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  60. t.Fatalf("Deleted header returned: %v", entry)
  61. }
  62. }
  63. // Tests block body storage and retrieval operations.
  64. func TestBodyStorage(t *testing.T) {
  65. db := NewMemoryDatabase()
  66. // Create a test body to move around the database and make sure it's really new
  67. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  68. hasher := sha3.NewLegacyKeccak256()
  69. rlp.Encode(hasher, body)
  70. hash := common.BytesToHash(hasher.Sum(nil))
  71. if entry := ReadBody(db, hash, 0); entry != nil {
  72. t.Fatalf("Non existent body returned: %v", entry)
  73. }
  74. // Write and verify the body in the database
  75. WriteBody(db, hash, 0, body)
  76. if entry := ReadBody(db, hash, 0); entry == nil {
  77. t.Fatalf("Stored body not found")
  78. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  79. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  80. }
  81. if entry := ReadBodyRLP(db, hash, 0); entry == nil {
  82. t.Fatalf("Stored body RLP not found")
  83. } else {
  84. hasher := sha3.NewLegacyKeccak256()
  85. hasher.Write(entry)
  86. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  87. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  88. }
  89. }
  90. // Delete the body and verify the execution
  91. DeleteBody(db, hash, 0)
  92. if entry := ReadBody(db, hash, 0); entry != nil {
  93. t.Fatalf("Deleted body returned: %v", entry)
  94. }
  95. }
  96. // Tests block storage and retrieval operations.
  97. func TestBlockStorage(t *testing.T) {
  98. db := NewMemoryDatabase()
  99. // Create a test block to move around the database and make sure it's really new
  100. block := types.NewBlockWithHeader(&types.Header{
  101. Extra: []byte("test block"),
  102. UncleHash: types.EmptyUncleHash,
  103. TxHash: types.EmptyRootHash,
  104. ReceiptHash: types.EmptyRootHash,
  105. })
  106. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  107. t.Fatalf("Non existent block returned: %v", entry)
  108. }
  109. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  110. t.Fatalf("Non existent header returned: %v", entry)
  111. }
  112. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  113. t.Fatalf("Non existent body returned: %v", entry)
  114. }
  115. // Write and verify the block in the database
  116. WriteBlock(db, block)
  117. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  118. t.Fatalf("Stored block not found")
  119. } else if entry.Hash() != block.Hash() {
  120. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  121. }
  122. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
  123. t.Fatalf("Stored header not found")
  124. } else if entry.Hash() != block.Header().Hash() {
  125. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  126. }
  127. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
  128. t.Fatalf("Stored body not found")
  129. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  130. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
  131. }
  132. // Delete the block and verify the execution
  133. DeleteBlock(db, block.Hash(), block.NumberU64())
  134. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  135. t.Fatalf("Deleted block returned: %v", entry)
  136. }
  137. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  138. t.Fatalf("Deleted header returned: %v", entry)
  139. }
  140. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  141. t.Fatalf("Deleted body returned: %v", entry)
  142. }
  143. }
  144. // Tests that partial block contents don't get reassembled into full blocks.
  145. func TestPartialBlockStorage(t *testing.T) {
  146. db := NewMemoryDatabase()
  147. block := types.NewBlockWithHeader(&types.Header{
  148. Extra: []byte("test block"),
  149. UncleHash: types.EmptyUncleHash,
  150. TxHash: types.EmptyRootHash,
  151. ReceiptHash: types.EmptyRootHash,
  152. })
  153. // Store a header and check that it's not recognized as a block
  154. WriteHeader(db, block.Header())
  155. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  156. t.Fatalf("Non existent block returned: %v", entry)
  157. }
  158. DeleteHeader(db, block.Hash(), block.NumberU64())
  159. // Store a body and check that it's not recognized as a block
  160. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  161. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  162. t.Fatalf("Non existent block returned: %v", entry)
  163. }
  164. DeleteBody(db, block.Hash(), block.NumberU64())
  165. // Store a header and a body separately and check reassembly
  166. WriteHeader(db, block.Header())
  167. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  168. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  169. t.Fatalf("Stored block not found")
  170. } else if entry.Hash() != block.Hash() {
  171. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  172. }
  173. }
  174. // Tests block storage and retrieval operations.
  175. func TestBadBlockStorage(t *testing.T) {
  176. db := NewMemoryDatabase()
  177. // Create a test block to move around the database and make sure it's really new
  178. block := types.NewBlockWithHeader(&types.Header{
  179. Number: big.NewInt(1),
  180. Extra: []byte("bad block"),
  181. UncleHash: types.EmptyUncleHash,
  182. TxHash: types.EmptyRootHash,
  183. ReceiptHash: types.EmptyRootHash,
  184. })
  185. if entry := ReadBadBlock(db, block.Hash()); entry != nil {
  186. t.Fatalf("Non existent block returned: %v", entry)
  187. }
  188. // Write and verify the block in the database
  189. WriteBadBlock(db, block)
  190. if entry := ReadBadBlock(db, block.Hash()); entry == nil {
  191. t.Fatalf("Stored block not found")
  192. } else if entry.Hash() != block.Hash() {
  193. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  194. }
  195. // Write one more bad block
  196. blockTwo := types.NewBlockWithHeader(&types.Header{
  197. Number: big.NewInt(2),
  198. Extra: []byte("bad block two"),
  199. UncleHash: types.EmptyUncleHash,
  200. TxHash: types.EmptyRootHash,
  201. ReceiptHash: types.EmptyRootHash,
  202. })
  203. WriteBadBlock(db, blockTwo)
  204. // Write the block one again, should be filtered out.
  205. WriteBadBlock(db, block)
  206. badBlocks := ReadAllBadBlocks(db)
  207. if len(badBlocks) != 2 {
  208. t.Fatalf("Failed to load all bad blocks")
  209. }
  210. // Write a bunch of bad blocks, all the blocks are should sorted
  211. // in reverse order. The extra blocks should be truncated.
  212. for _, n := range rand.Perm(100) {
  213. block := types.NewBlockWithHeader(&types.Header{
  214. Number: big.NewInt(int64(n)),
  215. Extra: []byte("bad block"),
  216. UncleHash: types.EmptyUncleHash,
  217. TxHash: types.EmptyRootHash,
  218. ReceiptHash: types.EmptyRootHash,
  219. })
  220. WriteBadBlock(db, block)
  221. }
  222. badBlocks = ReadAllBadBlocks(db)
  223. if len(badBlocks) != badBlockToKeep {
  224. t.Fatalf("The number of persised bad blocks in incorrect %d", len(badBlocks))
  225. }
  226. for i := 0; i < len(badBlocks)-1; i++ {
  227. if badBlocks[i].NumberU64() < badBlocks[i+1].NumberU64() {
  228. t.Fatalf("The bad blocks are not sorted #[%d](%d) < #[%d](%d)", i, i+1, badBlocks[i].NumberU64(), badBlocks[i+1].NumberU64())
  229. }
  230. }
  231. // Delete all bad blocks
  232. DeleteBadBlocks(db)
  233. badBlocks = ReadAllBadBlocks(db)
  234. if len(badBlocks) != 0 {
  235. t.Fatalf("Failed to delete bad blocks")
  236. }
  237. }
  238. // Tests block total difficulty storage and retrieval operations.
  239. func TestTdStorage(t *testing.T) {
  240. db := NewMemoryDatabase()
  241. // Create a test TD to move around the database and make sure it's really new
  242. hash, td := common.Hash{}, big.NewInt(314)
  243. if entry := ReadTd(db, hash, 0); entry != nil {
  244. t.Fatalf("Non existent TD returned: %v", entry)
  245. }
  246. // Write and verify the TD in the database
  247. WriteTd(db, hash, 0, td)
  248. if entry := ReadTd(db, hash, 0); entry == nil {
  249. t.Fatalf("Stored TD not found")
  250. } else if entry.Cmp(td) != 0 {
  251. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  252. }
  253. // Delete the TD and verify the execution
  254. DeleteTd(db, hash, 0)
  255. if entry := ReadTd(db, hash, 0); entry != nil {
  256. t.Fatalf("Deleted TD returned: %v", entry)
  257. }
  258. }
  259. // Tests that canonical numbers can be mapped to hashes and retrieved.
  260. func TestCanonicalMappingStorage(t *testing.T) {
  261. db := NewMemoryDatabase()
  262. // Create a test canonical number and assigned hash to move around
  263. hash, number := common.Hash{0: 0xff}, uint64(314)
  264. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  265. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  266. }
  267. // Write and verify the TD in the database
  268. WriteCanonicalHash(db, hash, number)
  269. if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
  270. t.Fatalf("Stored canonical mapping not found")
  271. } else if entry != hash {
  272. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  273. }
  274. // Delete the TD and verify the execution
  275. DeleteCanonicalHash(db, number)
  276. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  277. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  278. }
  279. }
  280. // Tests that head headers and head blocks can be assigned, individually.
  281. func TestHeadStorage(t *testing.T) {
  282. db := NewMemoryDatabase()
  283. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  284. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  285. blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
  286. // Check that no head entries are in a pristine database
  287. if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
  288. t.Fatalf("Non head header entry returned: %v", entry)
  289. }
  290. if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
  291. t.Fatalf("Non head block entry returned: %v", entry)
  292. }
  293. if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
  294. t.Fatalf("Non fast head block entry returned: %v", entry)
  295. }
  296. // Assign separate entries for the head header and block
  297. WriteHeadHeaderHash(db, blockHead.Hash())
  298. WriteHeadBlockHash(db, blockFull.Hash())
  299. WriteHeadFastBlockHash(db, blockFast.Hash())
  300. // Check that both heads are present, and different (i.e. two heads maintained)
  301. if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
  302. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  303. }
  304. if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
  305. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  306. }
  307. if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
  308. t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
  309. }
  310. }
  311. // Tests that receipts associated with a single block can be stored and retrieved.
  312. func TestBlockReceiptStorage(t *testing.T) {
  313. db := NewMemoryDatabase()
  314. // Create a live block since we need metadata to reconstruct the receipt
  315. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  316. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  317. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  318. // Create the two receipts to manage afterwards
  319. receipt1 := &types.Receipt{
  320. Status: types.ReceiptStatusFailed,
  321. CumulativeGasUsed: 1,
  322. Logs: []*types.Log{
  323. {Address: common.BytesToAddress([]byte{0x11})},
  324. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  325. },
  326. TxHash: tx1.Hash(),
  327. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  328. GasUsed: 111111,
  329. }
  330. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  331. receipt2 := &types.Receipt{
  332. PostState: common.Hash{2}.Bytes(),
  333. CumulativeGasUsed: 2,
  334. Logs: []*types.Log{
  335. {Address: common.BytesToAddress([]byte{0x22})},
  336. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  337. },
  338. TxHash: tx2.Hash(),
  339. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  340. GasUsed: 222222,
  341. }
  342. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  343. receipts := []*types.Receipt{receipt1, receipt2}
  344. // Check that no receipt entries are in a pristine database
  345. hash := common.BytesToHash([]byte{0x03, 0x14})
  346. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  347. t.Fatalf("non existent receipts returned: %v", rs)
  348. }
  349. // Insert the body that corresponds to the receipts
  350. WriteBody(db, hash, 0, body)
  351. // Insert the receipt slice into the database and check presence
  352. WriteReceipts(db, hash, 0, receipts)
  353. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  354. t.Fatalf("no receipts returned")
  355. } else {
  356. if err := checkReceiptsRLP(rs, receipts); err != nil {
  357. t.Fatalf(err.Error())
  358. }
  359. }
  360. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  361. DeleteBody(db, hash, 0)
  362. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  363. t.Fatalf("receipts returned when body was deleted: %v", rs)
  364. }
  365. // Ensure that receipts without metadata can be returned without the block body too
  366. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  367. t.Fatalf(err.Error())
  368. }
  369. // Sanity check that body alone without the receipt is a full purge
  370. WriteBody(db, hash, 0, body)
  371. DeleteReceipts(db, hash, 0)
  372. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  373. t.Fatalf("deleted receipts returned: %v", rs)
  374. }
  375. }
  376. func checkReceiptsRLP(have, want types.Receipts) error {
  377. if len(have) != len(want) {
  378. return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
  379. }
  380. for i := 0; i < len(want); i++ {
  381. rlpHave, err := rlp.EncodeToBytes(have[i])
  382. if err != nil {
  383. return err
  384. }
  385. rlpWant, err := rlp.EncodeToBytes(want[i])
  386. if err != nil {
  387. return err
  388. }
  389. if !bytes.Equal(rlpHave, rlpWant) {
  390. return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
  391. }
  392. }
  393. return nil
  394. }
  395. func TestAncientStorage(t *testing.T) {
  396. // Freezer style fast import the chain.
  397. frdir := t.TempDir()
  398. db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
  399. if err != nil {
  400. t.Fatalf("failed to create database with ancient backend")
  401. }
  402. defer db.Close()
  403. // Create a test block
  404. block := types.NewBlockWithHeader(&types.Header{
  405. Number: big.NewInt(0),
  406. Extra: []byte("test block"),
  407. UncleHash: types.EmptyUncleHash,
  408. TxHash: types.EmptyRootHash,
  409. ReceiptHash: types.EmptyRootHash,
  410. })
  411. // Ensure nothing non-existent will be read
  412. hash, number := block.Hash(), block.NumberU64()
  413. if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
  414. t.Fatalf("non existent header returned")
  415. }
  416. if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
  417. t.Fatalf("non existent body returned")
  418. }
  419. if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
  420. t.Fatalf("non existent receipts returned")
  421. }
  422. if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
  423. t.Fatalf("non existent td returned")
  424. }
  425. // Write and verify the header in the database
  426. WriteAncientBlocks(db, []*types.Block{block}, []types.Receipts{nil}, big.NewInt(100))
  427. if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
  428. t.Fatalf("no header returned")
  429. }
  430. if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
  431. t.Fatalf("no body returned")
  432. }
  433. if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
  434. t.Fatalf("no receipts returned")
  435. }
  436. if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
  437. t.Fatalf("no td returned")
  438. }
  439. // Use a fake hash for data retrieval, nothing should be returned.
  440. fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
  441. if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
  442. t.Fatalf("invalid header returned")
  443. }
  444. if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
  445. t.Fatalf("invalid body returned")
  446. }
  447. if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
  448. t.Fatalf("invalid receipts returned")
  449. }
  450. if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
  451. t.Fatalf("invalid td returned")
  452. }
  453. }
  454. func TestCanonicalHashIteration(t *testing.T) {
  455. var cases = []struct {
  456. from, to uint64
  457. limit int
  458. expect []uint64
  459. }{
  460. {1, 8, 0, nil},
  461. {1, 8, 1, []uint64{1}},
  462. {1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
  463. {1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
  464. {2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
  465. {9, 10, 10, nil},
  466. }
  467. // Test empty db iteration
  468. db := NewMemoryDatabase()
  469. numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
  470. if len(numbers) != 0 {
  471. t.Fatalf("No entry should be returned to iterate an empty db")
  472. }
  473. // Fill database with testing data.
  474. for i := uint64(1); i <= 8; i++ {
  475. WriteCanonicalHash(db, common.Hash{}, i)
  476. WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
  477. }
  478. for i, c := range cases {
  479. numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
  480. if !reflect.DeepEqual(numbers, c.expect) {
  481. t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
  482. }
  483. }
  484. }
  485. func TestHashesInRange(t *testing.T) {
  486. mkHeader := func(number, seq int) *types.Header {
  487. h := types.Header{
  488. Difficulty: new(big.Int),
  489. Number: big.NewInt(int64(number)),
  490. GasLimit: uint64(seq),
  491. }
  492. return &h
  493. }
  494. db := NewMemoryDatabase()
  495. // For each number, write N versions of that particular number
  496. total := 0
  497. for i := 0; i < 15; i++ {
  498. for ii := 0; ii < i; ii++ {
  499. WriteHeader(db, mkHeader(i, ii))
  500. total++
  501. }
  502. }
  503. if have, want := len(ReadAllHashesInRange(db, 10, 10)), 10; have != want {
  504. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  505. }
  506. if have, want := len(ReadAllHashesInRange(db, 10, 9)), 0; have != want {
  507. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  508. }
  509. if have, want := len(ReadAllHashesInRange(db, 0, 100)), total; have != want {
  510. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  511. }
  512. if have, want := len(ReadAllHashesInRange(db, 9, 10)), 9+10; have != want {
  513. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  514. }
  515. if have, want := len(ReadAllHashes(db, 10)), 10; have != want {
  516. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  517. }
  518. if have, want := len(ReadAllHashes(db, 16)), 0; have != want {
  519. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  520. }
  521. if have, want := len(ReadAllHashes(db, 1)), 1; have != want {
  522. t.Fatalf("Wrong number of hashes read, want %d, got %d", want, have)
  523. }
  524. }
  525. // This measures the write speed of the WriteAncientBlocks operation.
  526. func BenchmarkWriteAncientBlocks(b *testing.B) {
  527. // Open freezer database.
  528. frdir := b.TempDir()
  529. db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
  530. if err != nil {
  531. b.Fatalf("failed to create database with ancient backend")
  532. }
  533. defer db.Close()
  534. // Create the data to insert. The blocks must have consecutive numbers, so we create
  535. // all of them ahead of time. However, there is no need to create receipts
  536. // individually for each block, just make one batch here and reuse it for all writes.
  537. const batchSize = 128
  538. const blockTxs = 20
  539. allBlocks := makeTestBlocks(b.N, blockTxs)
  540. batchReceipts := makeTestReceipts(batchSize, blockTxs)
  541. b.ResetTimer()
  542. // The benchmark loop writes batches of blocks, but note that the total block count is
  543. // b.N. This means the resulting ns/op measurement is the time it takes to write a
  544. // single block and its associated data.
  545. var td = big.NewInt(55)
  546. var totalSize int64
  547. for i := 0; i < b.N; i += batchSize {
  548. length := batchSize
  549. if i+batchSize > b.N {
  550. length = b.N - i
  551. }
  552. blocks := allBlocks[i : i+length]
  553. receipts := batchReceipts[:length]
  554. writeSize, err := WriteAncientBlocks(db, blocks, receipts, td)
  555. if err != nil {
  556. b.Fatal(err)
  557. }
  558. totalSize += writeSize
  559. }
  560. // Enable MB/s reporting.
  561. b.SetBytes(totalSize / int64(b.N))
  562. }
  563. // makeTestBlocks creates fake blocks for the ancient write benchmark.
  564. func makeTestBlocks(nblock int, txsPerBlock int) []*types.Block {
  565. key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  566. signer := types.LatestSignerForChainID(big.NewInt(8))
  567. // Create transactions.
  568. txs := make([]*types.Transaction, txsPerBlock)
  569. for i := 0; i < len(txs); i++ {
  570. var err error
  571. to := common.Address{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
  572. txs[i], err = types.SignNewTx(key, signer, &types.LegacyTx{
  573. Nonce: 2,
  574. GasPrice: big.NewInt(30000),
  575. Gas: 0x45454545,
  576. To: &to,
  577. })
  578. if err != nil {
  579. panic(err)
  580. }
  581. }
  582. // Create the blocks.
  583. blocks := make([]*types.Block, nblock)
  584. for i := 0; i < nblock; i++ {
  585. header := &types.Header{
  586. Number: big.NewInt(int64(i)),
  587. Extra: []byte("test block"),
  588. }
  589. blocks[i] = types.NewBlockWithHeader(header).WithBody(txs, nil)
  590. blocks[i].Hash() // pre-cache the block hash
  591. }
  592. return blocks
  593. }
  594. // makeTestReceipts creates fake receipts for the ancient write benchmark.
  595. func makeTestReceipts(n int, nPerBlock int) []types.Receipts {
  596. receipts := make([]*types.Receipt, nPerBlock)
  597. for i := 0; i < len(receipts); i++ {
  598. receipts[i] = &types.Receipt{
  599. Status: types.ReceiptStatusSuccessful,
  600. CumulativeGasUsed: 0x888888888,
  601. Logs: make([]*types.Log, 5),
  602. }
  603. }
  604. allReceipts := make([]types.Receipts, n)
  605. for i := 0; i < n; i++ {
  606. allReceipts[i] = receipts
  607. }
  608. return allReceipts
  609. }
  610. type fullLogRLP struct {
  611. Address common.Address
  612. Topics []common.Hash
  613. Data []byte
  614. BlockNumber uint64
  615. TxHash common.Hash
  616. TxIndex uint
  617. BlockHash common.Hash
  618. Index uint
  619. }
  620. func newFullLogRLP(l *types.Log) *fullLogRLP {
  621. return &fullLogRLP{
  622. Address: l.Address,
  623. Topics: l.Topics,
  624. Data: l.Data,
  625. BlockNumber: l.BlockNumber,
  626. TxHash: l.TxHash,
  627. TxIndex: l.TxIndex,
  628. BlockHash: l.BlockHash,
  629. Index: l.Index,
  630. }
  631. }
  632. // Tests that logs associated with a single block can be retrieved.
  633. func TestReadLogs(t *testing.T) {
  634. db := NewMemoryDatabase()
  635. // Create a live block since we need metadata to reconstruct the receipt
  636. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  637. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  638. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  639. // Create the two receipts to manage afterwards
  640. receipt1 := &types.Receipt{
  641. Status: types.ReceiptStatusFailed,
  642. CumulativeGasUsed: 1,
  643. Logs: []*types.Log{
  644. {Address: common.BytesToAddress([]byte{0x11})},
  645. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  646. },
  647. TxHash: tx1.Hash(),
  648. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  649. GasUsed: 111111,
  650. }
  651. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  652. receipt2 := &types.Receipt{
  653. PostState: common.Hash{2}.Bytes(),
  654. CumulativeGasUsed: 2,
  655. Logs: []*types.Log{
  656. {Address: common.BytesToAddress([]byte{0x22})},
  657. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  658. },
  659. TxHash: tx2.Hash(),
  660. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  661. GasUsed: 222222,
  662. }
  663. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  664. receipts := []*types.Receipt{receipt1, receipt2}
  665. hash := common.BytesToHash([]byte{0x03, 0x14})
  666. // Check that no receipt entries are in a pristine database
  667. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  668. t.Fatalf("non existent receipts returned: %v", rs)
  669. }
  670. // Insert the body that corresponds to the receipts
  671. WriteBody(db, hash, 0, body)
  672. // Insert the receipt slice into the database and check presence
  673. WriteReceipts(db, hash, 0, receipts)
  674. logs := ReadLogs(db, hash, 0, params.TestChainConfig)
  675. if len(logs) == 0 {
  676. t.Fatalf("no logs returned")
  677. }
  678. if have, want := len(logs), 2; have != want {
  679. t.Fatalf("unexpected number of logs returned, have %d want %d", have, want)
  680. }
  681. if have, want := len(logs[0]), 2; have != want {
  682. t.Fatalf("unexpected number of logs[0] returned, have %d want %d", have, want)
  683. }
  684. if have, want := len(logs[1]), 2; have != want {
  685. t.Fatalf("unexpected number of logs[1] returned, have %d want %d", have, want)
  686. }
  687. // Fill in log fields so we can compare their rlp encoding
  688. if err := types.Receipts(receipts).DeriveFields(params.TestChainConfig, hash, 0, body.Transactions); err != nil {
  689. t.Fatal(err)
  690. }
  691. for i, pr := range receipts {
  692. for j, pl := range pr.Logs {
  693. rlpHave, err := rlp.EncodeToBytes(newFullLogRLP(logs[i][j]))
  694. if err != nil {
  695. t.Fatal(err)
  696. }
  697. rlpWant, err := rlp.EncodeToBytes(newFullLogRLP(pl))
  698. if err != nil {
  699. t.Fatal(err)
  700. }
  701. if !bytes.Equal(rlpHave, rlpWant) {
  702. t.Fatalf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
  703. }
  704. }
  705. }
  706. }
  707. func TestDeriveLogFields(t *testing.T) {
  708. // Create a few transactions to have receipts for
  709. to2 := common.HexToAddress("0x2")
  710. to3 := common.HexToAddress("0x3")
  711. txs := types.Transactions{
  712. types.NewTx(&types.LegacyTx{
  713. Nonce: 1,
  714. Value: big.NewInt(1),
  715. Gas: 1,
  716. GasPrice: big.NewInt(1),
  717. }),
  718. types.NewTx(&types.LegacyTx{
  719. To: &to2,
  720. Nonce: 2,
  721. Value: big.NewInt(2),
  722. Gas: 2,
  723. GasPrice: big.NewInt(2),
  724. }),
  725. types.NewTx(&types.AccessListTx{
  726. To: &to3,
  727. Nonce: 3,
  728. Value: big.NewInt(3),
  729. Gas: 3,
  730. GasPrice: big.NewInt(3),
  731. }),
  732. }
  733. // Create the corresponding receipts
  734. receipts := []*receiptLogs{
  735. {
  736. Logs: []*types.Log{
  737. {Address: common.BytesToAddress([]byte{0x11})},
  738. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  739. },
  740. },
  741. {
  742. Logs: []*types.Log{
  743. {Address: common.BytesToAddress([]byte{0x22})},
  744. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  745. },
  746. },
  747. {
  748. Logs: []*types.Log{
  749. {Address: common.BytesToAddress([]byte{0x33})},
  750. {Address: common.BytesToAddress([]byte{0x03, 0x33})},
  751. },
  752. },
  753. }
  754. // Derive log metadata fields
  755. number := big.NewInt(1)
  756. hash := common.BytesToHash([]byte{0x03, 0x14})
  757. if err := deriveLogFields(receipts, hash, number.Uint64(), txs); err != nil {
  758. t.Fatal(err)
  759. }
  760. // Iterate over all the computed fields and check that they're correct
  761. logIndex := uint(0)
  762. for i := range receipts {
  763. for j := range receipts[i].Logs {
  764. if receipts[i].Logs[j].BlockNumber != number.Uint64() {
  765. t.Errorf("receipts[%d].Logs[%d].BlockNumber = %d, want %d", i, j, receipts[i].Logs[j].BlockNumber, number.Uint64())
  766. }
  767. if receipts[i].Logs[j].BlockHash != hash {
  768. t.Errorf("receipts[%d].Logs[%d].BlockHash = %s, want %s", i, j, receipts[i].Logs[j].BlockHash.String(), hash.String())
  769. }
  770. if receipts[i].Logs[j].TxHash != txs[i].Hash() {
  771. t.Errorf("receipts[%d].Logs[%d].TxHash = %s, want %s", i, j, receipts[i].Logs[j].TxHash.String(), txs[i].Hash().String())
  772. }
  773. if receipts[i].Logs[j].TxIndex != uint(i) {
  774. t.Errorf("receipts[%d].Logs[%d].TransactionIndex = %d, want %d", i, j, receipts[i].Logs[j].TxIndex, i)
  775. }
  776. if receipts[i].Logs[j].Index != logIndex {
  777. t.Errorf("receipts[%d].Logs[%d].Index = %d, want %d", i, j, receipts[i].Logs[j].Index, logIndex)
  778. }
  779. logIndex++
  780. }
  781. }
  782. }
  783. func BenchmarkDecodeRLPLogs(b *testing.B) {
  784. // Encoded receipts from block 0x14ee094309fbe8f70b65f45ebcc08fb33f126942d97464aad5eb91cfd1e2d269
  785. buf, err := os.ReadFile("testdata/stored_receipts.bin")
  786. if err != nil {
  787. b.Fatal(err)
  788. }
  789. b.Run("ReceiptForStorage", func(b *testing.B) {
  790. b.ReportAllocs()
  791. var r []*types.ReceiptForStorage
  792. for i := 0; i < b.N; i++ {
  793. if err := rlp.DecodeBytes(buf, &r); err != nil {
  794. b.Fatal(err)
  795. }
  796. }
  797. })
  798. b.Run("rlpLogs", func(b *testing.B) {
  799. b.ReportAllocs()
  800. var r []*receiptLogs
  801. for i := 0; i < b.N; i++ {
  802. if err := rlp.DecodeBytes(buf, &r); err != nil {
  803. b.Fatal(err)
  804. }
  805. }
  806. })
  807. }
  808. func TestHeadersRLPStorage(t *testing.T) {
  809. // Have N headers in the freezer
  810. frdir := t.TempDir()
  811. db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
  812. if err != nil {
  813. t.Fatalf("failed to create database with ancient backend")
  814. }
  815. defer db.Close()
  816. // Create blocks
  817. var chain []*types.Block
  818. var pHash common.Hash
  819. for i := 0; i < 100; i++ {
  820. block := types.NewBlockWithHeader(&types.Header{
  821. Number: big.NewInt(int64(i)),
  822. Extra: []byte("test block"),
  823. UncleHash: types.EmptyUncleHash,
  824. TxHash: types.EmptyRootHash,
  825. ReceiptHash: types.EmptyRootHash,
  826. ParentHash: pHash,
  827. })
  828. chain = append(chain, block)
  829. pHash = block.Hash()
  830. }
  831. var receipts []types.Receipts = make([]types.Receipts, 100)
  832. // Write first half to ancients
  833. WriteAncientBlocks(db, chain[:50], receipts[:50], big.NewInt(100))
  834. // Write second half to db
  835. for i := 50; i < 100; i++ {
  836. WriteCanonicalHash(db, chain[i].Hash(), chain[i].NumberU64())
  837. WriteBlock(db, chain[i])
  838. }
  839. checkSequence := func(from, amount int) {
  840. headersRlp := ReadHeaderRange(db, uint64(from), uint64(amount))
  841. if have, want := len(headersRlp), amount; have != want {
  842. t.Fatalf("have %d headers, want %d", have, want)
  843. }
  844. for i, headerRlp := range headersRlp {
  845. var header types.Header
  846. if err := rlp.DecodeBytes(headerRlp, &header); err != nil {
  847. t.Fatal(err)
  848. }
  849. if have, want := header.Number.Uint64(), uint64(from-i); have != want {
  850. t.Fatalf("wrong number, have %d want %d", have, want)
  851. }
  852. }
  853. }
  854. checkSequence(99, 20) // Latest block and 19 parents
  855. checkSequence(99, 50) // Latest block -> all db blocks
  856. checkSequence(99, 51) // Latest block -> one from ancients
  857. checkSequence(99, 52) // Latest blocks -> two from ancients
  858. checkSequence(50, 2) // One from db, one from ancients
  859. checkSequence(49, 1) // One from ancients
  860. checkSequence(49, 50) // All ancient ones
  861. checkSequence(99, 100) // All blocks
  862. checkSequence(0, 1) // Only genesis
  863. checkSequence(1, 1) // Only block 1
  864. checkSequence(1, 2) // Genesis + block 1
  865. }