accessors_chain_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. "io/ioutil"
  22. "math/big"
  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/params"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "golang.org/x/crypto/sha3"
  31. )
  32. // Tests block header storage and retrieval operations.
  33. func TestHeaderStorage(t *testing.T) {
  34. db := NewMemoryDatabase()
  35. // Create a test header to move around the database and make sure it's really new
  36. header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
  37. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  38. t.Fatalf("Non existent header returned: %v", entry)
  39. }
  40. // Write and verify the header in the database
  41. WriteHeader(db, header)
  42. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
  43. t.Fatalf("Stored header not found")
  44. } else if entry.Hash() != header.Hash() {
  45. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  46. }
  47. if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
  48. t.Fatalf("Stored header RLP not found")
  49. } else {
  50. hasher := sha3.NewLegacyKeccak256()
  51. hasher.Write(entry)
  52. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  53. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  54. }
  55. }
  56. // Delete the header and verify the execution
  57. DeleteHeader(db, header.Hash(), header.Number.Uint64())
  58. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  59. t.Fatalf("Deleted header returned: %v", entry)
  60. }
  61. }
  62. // Tests block body storage and retrieval operations.
  63. func TestBodyStorage(t *testing.T) {
  64. db := NewMemoryDatabase()
  65. // Create a test body to move around the database and make sure it's really new
  66. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  67. hasher := sha3.NewLegacyKeccak256()
  68. rlp.Encode(hasher, body)
  69. hash := common.BytesToHash(hasher.Sum(nil))
  70. if entry := ReadBody(db, hash, 0); entry != nil {
  71. t.Fatalf("Non existent body returned: %v", entry)
  72. }
  73. // Write and verify the body in the database
  74. WriteBody(db, hash, 0, body)
  75. if entry := ReadBody(db, hash, 0); entry == nil {
  76. t.Fatalf("Stored body not found")
  77. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  78. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  79. }
  80. if entry := ReadBodyRLP(db, hash, 0); entry == nil {
  81. t.Fatalf("Stored body RLP not found")
  82. } else {
  83. hasher := sha3.NewLegacyKeccak256()
  84. hasher.Write(entry)
  85. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  86. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  87. }
  88. }
  89. // Delete the body and verify the execution
  90. DeleteBody(db, hash, 0)
  91. if entry := ReadBody(db, hash, 0); entry != nil {
  92. t.Fatalf("Deleted body returned: %v", entry)
  93. }
  94. }
  95. // Tests block storage and retrieval operations.
  96. func TestBlockStorage(t *testing.T) {
  97. db := NewMemoryDatabase()
  98. // Create a test block to move around the database and make sure it's really new
  99. block := types.NewBlockWithHeader(&types.Header{
  100. Extra: []byte("test block"),
  101. UncleHash: types.EmptyUncleHash,
  102. TxHash: types.EmptyRootHash,
  103. ReceiptHash: types.EmptyRootHash,
  104. })
  105. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  106. t.Fatalf("Non existent block returned: %v", entry)
  107. }
  108. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  109. t.Fatalf("Non existent header returned: %v", entry)
  110. }
  111. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  112. t.Fatalf("Non existent body returned: %v", entry)
  113. }
  114. // Write and verify the block in the database
  115. WriteBlock(db, block)
  116. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  117. t.Fatalf("Stored block not found")
  118. } else if entry.Hash() != block.Hash() {
  119. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  120. }
  121. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
  122. t.Fatalf("Stored header not found")
  123. } else if entry.Hash() != block.Header().Hash() {
  124. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  125. }
  126. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
  127. t.Fatalf("Stored body not found")
  128. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  129. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
  130. }
  131. // Delete the block and verify the execution
  132. DeleteBlock(db, block.Hash(), block.NumberU64())
  133. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  134. t.Fatalf("Deleted block returned: %v", entry)
  135. }
  136. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  137. t.Fatalf("Deleted header returned: %v", entry)
  138. }
  139. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  140. t.Fatalf("Deleted body returned: %v", entry)
  141. }
  142. }
  143. // Tests that partial block contents don't get reassembled into full blocks.
  144. func TestPartialBlockStorage(t *testing.T) {
  145. db := NewMemoryDatabase()
  146. block := types.NewBlockWithHeader(&types.Header{
  147. Extra: []byte("test block"),
  148. UncleHash: types.EmptyUncleHash,
  149. TxHash: types.EmptyRootHash,
  150. ReceiptHash: types.EmptyRootHash,
  151. })
  152. // Store a header and check that it's not recognized as a block
  153. WriteHeader(db, block.Header())
  154. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  155. t.Fatalf("Non existent block returned: %v", entry)
  156. }
  157. DeleteHeader(db, block.Hash(), block.NumberU64())
  158. // Store a body and check that it's not recognized as a block
  159. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  160. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  161. t.Fatalf("Non existent block returned: %v", entry)
  162. }
  163. DeleteBody(db, block.Hash(), block.NumberU64())
  164. // Store a header and a body separately and check reassembly
  165. WriteHeader(db, block.Header())
  166. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  167. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  168. t.Fatalf("Stored block not found")
  169. } else if entry.Hash() != block.Hash() {
  170. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  171. }
  172. }
  173. // Tests block total difficulty storage and retrieval operations.
  174. func TestTdStorage(t *testing.T) {
  175. db := NewMemoryDatabase()
  176. // Create a test TD to move around the database and make sure it's really new
  177. hash, td := common.Hash{}, big.NewInt(314)
  178. if entry := ReadTd(db, hash, 0); entry != nil {
  179. t.Fatalf("Non existent TD returned: %v", entry)
  180. }
  181. // Write and verify the TD in the database
  182. WriteTd(db, hash, 0, td)
  183. if entry := ReadTd(db, hash, 0); entry == nil {
  184. t.Fatalf("Stored TD not found")
  185. } else if entry.Cmp(td) != 0 {
  186. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  187. }
  188. // Delete the TD and verify the execution
  189. DeleteTd(db, hash, 0)
  190. if entry := ReadTd(db, hash, 0); entry != nil {
  191. t.Fatalf("Deleted TD returned: %v", entry)
  192. }
  193. }
  194. // Tests that canonical numbers can be mapped to hashes and retrieved.
  195. func TestCanonicalMappingStorage(t *testing.T) {
  196. db := NewMemoryDatabase()
  197. // Create a test canonical number and assinged hash to move around
  198. hash, number := common.Hash{0: 0xff}, uint64(314)
  199. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  200. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  201. }
  202. // Write and verify the TD in the database
  203. WriteCanonicalHash(db, hash, number)
  204. if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
  205. t.Fatalf("Stored canonical mapping not found")
  206. } else if entry != hash {
  207. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  208. }
  209. // Delete the TD and verify the execution
  210. DeleteCanonicalHash(db, number)
  211. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  212. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  213. }
  214. }
  215. // Tests that head headers and head blocks can be assigned, individually.
  216. func TestHeadStorage(t *testing.T) {
  217. db := NewMemoryDatabase()
  218. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  219. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  220. blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
  221. // Check that no head entries are in a pristine database
  222. if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
  223. t.Fatalf("Non head header entry returned: %v", entry)
  224. }
  225. if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
  226. t.Fatalf("Non head block entry returned: %v", entry)
  227. }
  228. if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
  229. t.Fatalf("Non fast head block entry returned: %v", entry)
  230. }
  231. // Assign separate entries for the head header and block
  232. WriteHeadHeaderHash(db, blockHead.Hash())
  233. WriteHeadBlockHash(db, blockFull.Hash())
  234. WriteHeadFastBlockHash(db, blockFast.Hash())
  235. // Check that both heads are present, and different (i.e. two heads maintained)
  236. if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
  237. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  238. }
  239. if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
  240. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  241. }
  242. if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
  243. t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
  244. }
  245. }
  246. // Tests that receipts associated with a single block can be stored and retrieved.
  247. func TestBlockReceiptStorage(t *testing.T) {
  248. db := NewMemoryDatabase()
  249. // Create a live block since we need metadata to reconstruct the receipt
  250. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  251. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  252. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  253. // Create the two receipts to manage afterwards
  254. receipt1 := &types.Receipt{
  255. Status: types.ReceiptStatusFailed,
  256. CumulativeGasUsed: 1,
  257. Logs: []*types.Log{
  258. {Address: common.BytesToAddress([]byte{0x11})},
  259. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  260. },
  261. TxHash: tx1.Hash(),
  262. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  263. GasUsed: 111111,
  264. }
  265. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  266. receipt2 := &types.Receipt{
  267. PostState: common.Hash{2}.Bytes(),
  268. CumulativeGasUsed: 2,
  269. Logs: []*types.Log{
  270. {Address: common.BytesToAddress([]byte{0x22})},
  271. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  272. },
  273. TxHash: tx2.Hash(),
  274. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  275. GasUsed: 222222,
  276. }
  277. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  278. receipts := []*types.Receipt{receipt1, receipt2}
  279. // Check that no receipt entries are in a pristine database
  280. hash := common.BytesToHash([]byte{0x03, 0x14})
  281. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  282. t.Fatalf("non existent receipts returned: %v", rs)
  283. }
  284. // Insert the body that corresponds to the receipts
  285. WriteBody(db, hash, 0, body)
  286. // Insert the receipt slice into the database and check presence
  287. WriteReceipts(db, hash, 0, receipts)
  288. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  289. t.Fatalf("no receipts returned")
  290. } else {
  291. if err := checkReceiptsRLP(rs, receipts); err != nil {
  292. t.Fatalf(err.Error())
  293. }
  294. }
  295. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  296. DeleteBody(db, hash, 0)
  297. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  298. t.Fatalf("receipts returned when body was deleted: %v", rs)
  299. }
  300. // Ensure that receipts without metadata can be returned without the block body too
  301. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  302. t.Fatalf(err.Error())
  303. }
  304. // Sanity check that body alone without the receipt is a full purge
  305. WriteBody(db, hash, 0, body)
  306. DeleteReceipts(db, hash, 0)
  307. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  308. t.Fatalf("deleted receipts returned: %v", rs)
  309. }
  310. }
  311. func checkReceiptsRLP(have, want types.Receipts) error {
  312. if len(have) != len(want) {
  313. return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
  314. }
  315. for i := 0; i < len(want); i++ {
  316. rlpHave, err := rlp.EncodeToBytes(have[i])
  317. if err != nil {
  318. return err
  319. }
  320. rlpWant, err := rlp.EncodeToBytes(want[i])
  321. if err != nil {
  322. return err
  323. }
  324. if !bytes.Equal(rlpHave, rlpWant) {
  325. return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
  326. }
  327. }
  328. return nil
  329. }
  330. func TestAncientStorage(t *testing.T) {
  331. // Freezer style fast import the chain.
  332. frdir, err := ioutil.TempDir("", "")
  333. if err != nil {
  334. t.Fatalf("failed to create temp freezer dir: %v", err)
  335. }
  336. defer os.Remove(frdir)
  337. db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "")
  338. if err != nil {
  339. t.Fatalf("failed to create database with ancient backend")
  340. }
  341. // Create a test block
  342. block := types.NewBlockWithHeader(&types.Header{
  343. Number: big.NewInt(0),
  344. Extra: []byte("test block"),
  345. UncleHash: types.EmptyUncleHash,
  346. TxHash: types.EmptyRootHash,
  347. ReceiptHash: types.EmptyRootHash,
  348. })
  349. // Ensure nothing non-existent will be read
  350. hash, number := block.Hash(), block.NumberU64()
  351. if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
  352. t.Fatalf("non existent header returned")
  353. }
  354. if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
  355. t.Fatalf("non existent body returned")
  356. }
  357. if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
  358. t.Fatalf("non existent receipts returned")
  359. }
  360. if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
  361. t.Fatalf("non existent td returned")
  362. }
  363. // Write and verify the header in the database
  364. WriteAncientBlock(db, block, nil, big.NewInt(100))
  365. if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
  366. t.Fatalf("no header returned")
  367. }
  368. if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
  369. t.Fatalf("no body returned")
  370. }
  371. if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
  372. t.Fatalf("no receipts returned")
  373. }
  374. if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
  375. t.Fatalf("no td returned")
  376. }
  377. // Use a fake hash for data retrieval, nothing should be returned.
  378. fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
  379. if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
  380. t.Fatalf("invalid header returned")
  381. }
  382. if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
  383. t.Fatalf("invalid body returned")
  384. }
  385. if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
  386. t.Fatalf("invalid receipts returned")
  387. }
  388. if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
  389. t.Fatalf("invalid td returned")
  390. }
  391. }
  392. func TestCanonicalHashIteration(t *testing.T) {
  393. var cases = []struct {
  394. from, to uint64
  395. limit int
  396. expect []uint64
  397. }{
  398. {1, 8, 0, nil},
  399. {1, 8, 1, []uint64{1}},
  400. {1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
  401. {1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
  402. {2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
  403. {9, 10, 10, nil},
  404. }
  405. // Test empty db iteration
  406. db := NewMemoryDatabase()
  407. numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
  408. if len(numbers) != 0 {
  409. t.Fatalf("No entry should be returned to iterate an empty db")
  410. }
  411. // Fill database with testing data.
  412. for i := uint64(1); i <= 8; i++ {
  413. WriteCanonicalHash(db, common.Hash{}, i)
  414. WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
  415. }
  416. for i, c := range cases {
  417. numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
  418. if !reflect.DeepEqual(numbers, c.expect) {
  419. t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
  420. }
  421. }
  422. }