database_util_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. "bytes"
  19. "encoding/json"
  20. "io/ioutil"
  21. "math/big"
  22. "os"
  23. "testing"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/math"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/crypto/sha3"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/params"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. type diffTest struct {
  34. ParentTimestamp uint64
  35. ParentDifficulty *big.Int
  36. CurrentTimestamp uint64
  37. CurrentBlocknumber *big.Int
  38. CurrentDifficulty *big.Int
  39. }
  40. func (d *diffTest) UnmarshalJSON(b []byte) (err error) {
  41. var ext struct {
  42. ParentTimestamp string
  43. ParentDifficulty string
  44. CurrentTimestamp string
  45. CurrentBlocknumber string
  46. CurrentDifficulty string
  47. }
  48. if err := json.Unmarshal(b, &ext); err != nil {
  49. return err
  50. }
  51. d.ParentTimestamp = math.MustParseUint64(ext.ParentTimestamp)
  52. d.ParentDifficulty = math.MustParseBig256(ext.ParentDifficulty)
  53. d.CurrentTimestamp = math.MustParseUint64(ext.CurrentTimestamp)
  54. d.CurrentBlocknumber = math.MustParseBig256(ext.CurrentBlocknumber)
  55. d.CurrentDifficulty = math.MustParseBig256(ext.CurrentDifficulty)
  56. return nil
  57. }
  58. func TestCalcDifficulty(t *testing.T) {
  59. file, err := os.Open("../tests/files/BasicTests/difficulty.json")
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. defer file.Close()
  64. tests := make(map[string]diffTest)
  65. err = json.NewDecoder(file).Decode(&tests)
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. config := &params.ChainConfig{HomesteadBlock: big.NewInt(1150000)}
  70. for name, test := range tests {
  71. number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1))
  72. diff := CalcDifficulty(config, test.CurrentTimestamp, test.ParentTimestamp, number, test.ParentDifficulty)
  73. if diff.Cmp(test.CurrentDifficulty) != 0 {
  74. t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff)
  75. }
  76. }
  77. }
  78. // Tests block header storage and retrieval operations.
  79. func TestHeaderStorage(t *testing.T) {
  80. db, _ := ethdb.NewMemDatabase()
  81. // Create a test header to move around the database and make sure it's really new
  82. header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
  83. if entry := GetHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  84. t.Fatalf("Non existent header returned: %v", entry)
  85. }
  86. // Write and verify the header in the database
  87. if err := WriteHeader(db, header); err != nil {
  88. t.Fatalf("Failed to write header into database: %v", err)
  89. }
  90. if entry := GetHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
  91. t.Fatalf("Stored header not found")
  92. } else if entry.Hash() != header.Hash() {
  93. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  94. }
  95. if entry := GetHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
  96. t.Fatalf("Stored header RLP not found")
  97. } else {
  98. hasher := sha3.NewKeccak256()
  99. hasher.Write(entry)
  100. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  101. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  102. }
  103. }
  104. // Delete the header and verify the execution
  105. DeleteHeader(db, header.Hash(), header.Number.Uint64())
  106. if entry := GetHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  107. t.Fatalf("Deleted header returned: %v", entry)
  108. }
  109. }
  110. // Tests block body storage and retrieval operations.
  111. func TestBodyStorage(t *testing.T) {
  112. db, _ := ethdb.NewMemDatabase()
  113. // Create a test body to move around the database and make sure it's really new
  114. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  115. hasher := sha3.NewKeccak256()
  116. rlp.Encode(hasher, body)
  117. hash := common.BytesToHash(hasher.Sum(nil))
  118. if entry := GetBody(db, hash, 0); entry != nil {
  119. t.Fatalf("Non existent body returned: %v", entry)
  120. }
  121. // Write and verify the body in the database
  122. if err := WriteBody(db, hash, 0, body); err != nil {
  123. t.Fatalf("Failed to write body into database: %v", err)
  124. }
  125. if entry := GetBody(db, hash, 0); entry == nil {
  126. t.Fatalf("Stored body not found")
  127. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  128. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  129. }
  130. if entry := GetBodyRLP(db, hash, 0); entry == nil {
  131. t.Fatalf("Stored body RLP not found")
  132. } else {
  133. hasher := sha3.NewKeccak256()
  134. hasher.Write(entry)
  135. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  136. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  137. }
  138. }
  139. // Delete the body and verify the execution
  140. DeleteBody(db, hash, 0)
  141. if entry := GetBody(db, hash, 0); entry != nil {
  142. t.Fatalf("Deleted body returned: %v", entry)
  143. }
  144. }
  145. // Tests block storage and retrieval operations.
  146. func TestBlockStorage(t *testing.T) {
  147. db, _ := ethdb.NewMemDatabase()
  148. // Create a test block to move around the database and make sure it's really new
  149. block := types.NewBlockWithHeader(&types.Header{
  150. Extra: []byte("test block"),
  151. UncleHash: types.EmptyUncleHash,
  152. TxHash: types.EmptyRootHash,
  153. ReceiptHash: types.EmptyRootHash,
  154. })
  155. if entry := GetBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  156. t.Fatalf("Non existent block returned: %v", entry)
  157. }
  158. if entry := GetHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  159. t.Fatalf("Non existent header returned: %v", entry)
  160. }
  161. if entry := GetBody(db, block.Hash(), block.NumberU64()); entry != nil {
  162. t.Fatalf("Non existent body returned: %v", entry)
  163. }
  164. // Write and verify the block in the database
  165. if err := WriteBlock(db, block); err != nil {
  166. t.Fatalf("Failed to write block into database: %v", err)
  167. }
  168. if entry := GetBlock(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. if entry := GetHeader(db, block.Hash(), block.NumberU64()); entry == nil {
  174. t.Fatalf("Stored header not found")
  175. } else if entry.Hash() != block.Header().Hash() {
  176. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  177. }
  178. if entry := GetBody(db, block.Hash(), block.NumberU64()); entry == nil {
  179. t.Fatalf("Stored body not found")
  180. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  181. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
  182. }
  183. // Delete the block and verify the execution
  184. DeleteBlock(db, block.Hash(), block.NumberU64())
  185. if entry := GetBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  186. t.Fatalf("Deleted block returned: %v", entry)
  187. }
  188. if entry := GetHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  189. t.Fatalf("Deleted header returned: %v", entry)
  190. }
  191. if entry := GetBody(db, block.Hash(), block.NumberU64()); entry != nil {
  192. t.Fatalf("Deleted body returned: %v", entry)
  193. }
  194. }
  195. // Tests that partial block contents don't get reassembled into full blocks.
  196. func TestPartialBlockStorage(t *testing.T) {
  197. db, _ := ethdb.NewMemDatabase()
  198. block := types.NewBlockWithHeader(&types.Header{
  199. Extra: []byte("test block"),
  200. UncleHash: types.EmptyUncleHash,
  201. TxHash: types.EmptyRootHash,
  202. ReceiptHash: types.EmptyRootHash,
  203. })
  204. // Store a header and check that it's not recognized as a block
  205. if err := WriteHeader(db, block.Header()); err != nil {
  206. t.Fatalf("Failed to write header into database: %v", err)
  207. }
  208. if entry := GetBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  209. t.Fatalf("Non existent block returned: %v", entry)
  210. }
  211. DeleteHeader(db, block.Hash(), block.NumberU64())
  212. // Store a body and check that it's not recognized as a block
  213. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  214. t.Fatalf("Failed to write body into database: %v", err)
  215. }
  216. if entry := GetBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  217. t.Fatalf("Non existent block returned: %v", entry)
  218. }
  219. DeleteBody(db, block.Hash(), block.NumberU64())
  220. // Store a header and a body separately and check reassembly
  221. if err := WriteHeader(db, block.Header()); err != nil {
  222. t.Fatalf("Failed to write header into database: %v", err)
  223. }
  224. if err := WriteBody(db, block.Hash(), block.NumberU64(), block.Body()); err != nil {
  225. t.Fatalf("Failed to write body into database: %v", err)
  226. }
  227. if entry := GetBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  228. t.Fatalf("Stored block not found")
  229. } else if entry.Hash() != block.Hash() {
  230. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  231. }
  232. }
  233. // Tests block total difficulty storage and retrieval operations.
  234. func TestTdStorage(t *testing.T) {
  235. db, _ := ethdb.NewMemDatabase()
  236. // Create a test TD to move around the database and make sure it's really new
  237. hash, td := common.Hash{}, big.NewInt(314)
  238. if entry := GetTd(db, hash, 0); entry != nil {
  239. t.Fatalf("Non existent TD returned: %v", entry)
  240. }
  241. // Write and verify the TD in the database
  242. if err := WriteTd(db, hash, 0, td); err != nil {
  243. t.Fatalf("Failed to write TD into database: %v", err)
  244. }
  245. if entry := GetTd(db, hash, 0); entry == nil {
  246. t.Fatalf("Stored TD not found")
  247. } else if entry.Cmp(td) != 0 {
  248. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  249. }
  250. // Delete the TD and verify the execution
  251. DeleteTd(db, hash, 0)
  252. if entry := GetTd(db, hash, 0); entry != nil {
  253. t.Fatalf("Deleted TD returned: %v", entry)
  254. }
  255. }
  256. // Tests that canonical numbers can be mapped to hashes and retrieved.
  257. func TestCanonicalMappingStorage(t *testing.T) {
  258. db, _ := ethdb.NewMemDatabase()
  259. // Create a test canonical number and assinged hash to move around
  260. hash, number := common.Hash{0: 0xff}, uint64(314)
  261. if entry := GetCanonicalHash(db, number); entry != (common.Hash{}) {
  262. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  263. }
  264. // Write and verify the TD in the database
  265. if err := WriteCanonicalHash(db, hash, number); err != nil {
  266. t.Fatalf("Failed to write canonical mapping into database: %v", err)
  267. }
  268. if entry := GetCanonicalHash(db, number); entry == (common.Hash{}) {
  269. t.Fatalf("Stored canonical mapping not found")
  270. } else if entry != hash {
  271. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  272. }
  273. // Delete the TD and verify the execution
  274. DeleteCanonicalHash(db, number)
  275. if entry := GetCanonicalHash(db, number); entry != (common.Hash{}) {
  276. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  277. }
  278. }
  279. // Tests that head headers and head blocks can be assigned, individually.
  280. func TestHeadStorage(t *testing.T) {
  281. db, _ := ethdb.NewMemDatabase()
  282. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  283. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  284. blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
  285. // Check that no head entries are in a pristine database
  286. if entry := GetHeadHeaderHash(db); entry != (common.Hash{}) {
  287. t.Fatalf("Non head header entry returned: %v", entry)
  288. }
  289. if entry := GetHeadBlockHash(db); entry != (common.Hash{}) {
  290. t.Fatalf("Non head block entry returned: %v", entry)
  291. }
  292. if entry := GetHeadFastBlockHash(db); entry != (common.Hash{}) {
  293. t.Fatalf("Non fast head block entry returned: %v", entry)
  294. }
  295. // Assign separate entries for the head header and block
  296. if err := WriteHeadHeaderHash(db, blockHead.Hash()); err != nil {
  297. t.Fatalf("Failed to write head header hash: %v", err)
  298. }
  299. if err := WriteHeadBlockHash(db, blockFull.Hash()); err != nil {
  300. t.Fatalf("Failed to write head block hash: %v", err)
  301. }
  302. if err := WriteHeadFastBlockHash(db, blockFast.Hash()); err != nil {
  303. t.Fatalf("Failed to write fast head block hash: %v", err)
  304. }
  305. // Check that both heads are present, and different (i.e. two heads maintained)
  306. if entry := GetHeadHeaderHash(db); entry != blockHead.Hash() {
  307. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  308. }
  309. if entry := GetHeadBlockHash(db); entry != blockFull.Hash() {
  310. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  311. }
  312. if entry := GetHeadFastBlockHash(db); entry != blockFast.Hash() {
  313. t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
  314. }
  315. }
  316. // Tests that transactions and associated metadata can be stored and retrieved.
  317. func TestTransactionStorage(t *testing.T) {
  318. db, _ := ethdb.NewMemDatabase()
  319. tx1 := types.NewTransaction(1, common.BytesToAddress([]byte{0x11}), big.NewInt(111), big.NewInt(1111), big.NewInt(11111), []byte{0x11, 0x11, 0x11})
  320. tx2 := types.NewTransaction(2, common.BytesToAddress([]byte{0x22}), big.NewInt(222), big.NewInt(2222), big.NewInt(22222), []byte{0x22, 0x22, 0x22})
  321. tx3 := types.NewTransaction(3, common.BytesToAddress([]byte{0x33}), big.NewInt(333), big.NewInt(3333), big.NewInt(33333), []byte{0x33, 0x33, 0x33})
  322. txs := []*types.Transaction{tx1, tx2, tx3}
  323. block := types.NewBlock(&types.Header{Number: big.NewInt(314)}, txs, nil, nil)
  324. // Check that no transactions entries are in a pristine database
  325. for i, tx := range txs {
  326. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  327. t.Fatalf("tx #%d [%x]: non existent transaction returned: %v", i, tx.Hash(), txn)
  328. }
  329. }
  330. // Insert all the transactions into the database, and verify contents
  331. if err := WriteTransactions(db, block); err != nil {
  332. t.Fatalf("failed to write transactions: %v", err)
  333. }
  334. for i, tx := range txs {
  335. if txn, hash, number, index := GetTransaction(db, tx.Hash()); txn == nil {
  336. t.Fatalf("tx #%d [%x]: transaction not found", i, tx.Hash())
  337. } else {
  338. if hash != block.Hash() || number != block.NumberU64() || index != uint64(i) {
  339. t.Fatalf("tx #%d [%x]: positional metadata mismatch: have %x/%d/%d, want %x/%v/%v", i, tx.Hash(), hash, number, index, block.Hash(), block.NumberU64(), i)
  340. }
  341. if tx.String() != txn.String() {
  342. t.Fatalf("tx #%d [%x]: transaction mismatch: have %v, want %v", i, tx.Hash(), txn, tx)
  343. }
  344. }
  345. }
  346. // Delete the transactions and check purge
  347. for i, tx := range txs {
  348. DeleteTransaction(db, tx.Hash())
  349. if txn, _, _, _ := GetTransaction(db, tx.Hash()); txn != nil {
  350. t.Fatalf("tx #%d [%x]: deleted transaction returned: %v", i, tx.Hash(), txn)
  351. }
  352. }
  353. }
  354. // Tests that receipts can be stored and retrieved.
  355. func TestReceiptStorage(t *testing.T) {
  356. db, _ := ethdb.NewMemDatabase()
  357. receipt1 := &types.Receipt{
  358. PostState: []byte{0x01},
  359. CumulativeGasUsed: big.NewInt(1),
  360. Logs: []*types.Log{
  361. {Address: common.BytesToAddress([]byte{0x11})},
  362. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  363. },
  364. TxHash: common.BytesToHash([]byte{0x11, 0x11}),
  365. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  366. GasUsed: big.NewInt(111111),
  367. }
  368. receipt2 := &types.Receipt{
  369. PostState: []byte{0x02},
  370. CumulativeGasUsed: big.NewInt(2),
  371. Logs: []*types.Log{
  372. {Address: common.BytesToAddress([]byte{0x22})},
  373. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  374. },
  375. TxHash: common.BytesToHash([]byte{0x22, 0x22}),
  376. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  377. GasUsed: big.NewInt(222222),
  378. }
  379. receipts := []*types.Receipt{receipt1, receipt2}
  380. // Check that no receipt entries are in a pristine database
  381. for i, receipt := range receipts {
  382. if r := GetReceipt(db, receipt.TxHash); r != nil {
  383. t.Fatalf("receipt #%d [%x]: non existent receipt returned: %v", i, receipt.TxHash, r)
  384. }
  385. }
  386. // Insert all the receipts into the database, and verify contents
  387. if err := WriteReceipts(db, receipts); err != nil {
  388. t.Fatalf("failed to write receipts: %v", err)
  389. }
  390. for i, receipt := range receipts {
  391. if r := GetReceipt(db, receipt.TxHash); r == nil {
  392. t.Fatalf("receipt #%d [%x]: receipt not found", i, receipt.TxHash)
  393. } else {
  394. rlpHave, _ := rlp.EncodeToBytes(r)
  395. rlpWant, _ := rlp.EncodeToBytes(receipt)
  396. if !bytes.Equal(rlpHave, rlpWant) {
  397. t.Fatalf("receipt #%d [%x]: receipt mismatch: have %v, want %v", i, receipt.TxHash, r, receipt)
  398. }
  399. }
  400. }
  401. // Delete the receipts and check purge
  402. for i, receipt := range receipts {
  403. DeleteReceipt(db, receipt.TxHash)
  404. if r := GetReceipt(db, receipt.TxHash); r != nil {
  405. t.Fatalf("receipt #%d [%x]: deleted receipt returned: %v", i, receipt.TxHash, r)
  406. }
  407. }
  408. }
  409. // Tests that receipts associated with a single block can be stored and retrieved.
  410. func TestBlockReceiptStorage(t *testing.T) {
  411. db, _ := ethdb.NewMemDatabase()
  412. receipt1 := &types.Receipt{
  413. PostState: []byte{0x01},
  414. CumulativeGasUsed: big.NewInt(1),
  415. Logs: []*types.Log{
  416. {Address: common.BytesToAddress([]byte{0x11})},
  417. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  418. },
  419. TxHash: common.BytesToHash([]byte{0x11, 0x11}),
  420. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  421. GasUsed: big.NewInt(111111),
  422. }
  423. receipt2 := &types.Receipt{
  424. PostState: []byte{0x02},
  425. CumulativeGasUsed: big.NewInt(2),
  426. Logs: []*types.Log{
  427. {Address: common.BytesToAddress([]byte{0x22})},
  428. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  429. },
  430. TxHash: common.BytesToHash([]byte{0x22, 0x22}),
  431. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  432. GasUsed: big.NewInt(222222),
  433. }
  434. receipts := []*types.Receipt{receipt1, receipt2}
  435. // Check that no receipt entries are in a pristine database
  436. hash := common.BytesToHash([]byte{0x03, 0x14})
  437. if rs := GetBlockReceipts(db, hash, 0); len(rs) != 0 {
  438. t.Fatalf("non existent receipts returned: %v", rs)
  439. }
  440. // Insert the receipt slice into the database and check presence
  441. if err := WriteBlockReceipts(db, hash, 0, receipts); err != nil {
  442. t.Fatalf("failed to write block receipts: %v", err)
  443. }
  444. if rs := GetBlockReceipts(db, hash, 0); len(rs) == 0 {
  445. t.Fatalf("no receipts returned")
  446. } else {
  447. for i := 0; i < len(receipts); i++ {
  448. rlpHave, _ := rlp.EncodeToBytes(rs[i])
  449. rlpWant, _ := rlp.EncodeToBytes(receipts[i])
  450. if !bytes.Equal(rlpHave, rlpWant) {
  451. t.Fatalf("receipt #%d: receipt mismatch: have %v, want %v", i, rs[i], receipts[i])
  452. }
  453. }
  454. }
  455. // Delete the receipt slice and check purge
  456. DeleteBlockReceipts(db, hash, 0)
  457. if rs := GetBlockReceipts(db, hash, 0); len(rs) != 0 {
  458. t.Fatalf("deleted receipts returned: %v", rs)
  459. }
  460. }
  461. func TestMipmapBloom(t *testing.T) {
  462. db, _ := ethdb.NewMemDatabase()
  463. receipt1 := new(types.Receipt)
  464. receipt1.Logs = []*types.Log{
  465. {Address: common.BytesToAddress([]byte("test"))},
  466. {Address: common.BytesToAddress([]byte("address"))},
  467. }
  468. receipt2 := new(types.Receipt)
  469. receipt2.Logs = []*types.Log{
  470. {Address: common.BytesToAddress([]byte("test"))},
  471. {Address: common.BytesToAddress([]byte("address1"))},
  472. }
  473. WriteMipmapBloom(db, 1, types.Receipts{receipt1})
  474. WriteMipmapBloom(db, 2, types.Receipts{receipt2})
  475. for _, level := range MIPMapLevels {
  476. bloom := GetMipmapBloom(db, 2, level)
  477. if !bloom.Test(new(big.Int).SetBytes([]byte("address1"))) {
  478. t.Error("expected test to be included on level:", level)
  479. }
  480. }
  481. // reset
  482. db, _ = ethdb.NewMemDatabase()
  483. receipt := new(types.Receipt)
  484. receipt.Logs = []*types.Log{
  485. {Address: common.BytesToAddress([]byte("test"))},
  486. }
  487. WriteMipmapBloom(db, 999, types.Receipts{receipt1})
  488. receipt = new(types.Receipt)
  489. receipt.Logs = []*types.Log{
  490. {Address: common.BytesToAddress([]byte("test 1"))},
  491. }
  492. WriteMipmapBloom(db, 1000, types.Receipts{receipt})
  493. bloom := GetMipmapBloom(db, 1000, 1000)
  494. if bloom.TestBytes([]byte("test")) {
  495. t.Error("test should not have been included")
  496. }
  497. }
  498. func TestMipmapChain(t *testing.T) {
  499. dir, err := ioutil.TempDir("", "mipmap")
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. defer os.RemoveAll(dir)
  504. var (
  505. db, _ = ethdb.NewLDBDatabase(dir, 0, 0)
  506. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  507. addr = crypto.PubkeyToAddress(key1.PublicKey)
  508. addr2 = common.BytesToAddress([]byte("jeff"))
  509. hash1 = common.BytesToHash([]byte("topic1"))
  510. )
  511. defer db.Close()
  512. genesis := testGenesis(addr, big.NewInt(1000000)).MustCommit(db)
  513. chain, receipts := GenerateChain(params.TestChainConfig, genesis, db, 1010, func(i int, gen *BlockGen) {
  514. var receipts types.Receipts
  515. switch i {
  516. case 1:
  517. receipt := types.NewReceipt(nil, new(big.Int))
  518. receipt.Logs = []*types.Log{{Address: addr, Topics: []common.Hash{hash1}}}
  519. gen.AddUncheckedReceipt(receipt)
  520. receipts = types.Receipts{receipt}
  521. case 1000:
  522. receipt := types.NewReceipt(nil, new(big.Int))
  523. receipt.Logs = []*types.Log{{Address: addr2}}
  524. gen.AddUncheckedReceipt(receipt)
  525. receipts = types.Receipts{receipt}
  526. }
  527. // store the receipts
  528. err := WriteReceipts(db, receipts)
  529. if err != nil {
  530. t.Fatal(err)
  531. }
  532. WriteMipmapBloom(db, uint64(i+1), receipts)
  533. })
  534. for i, block := range chain {
  535. WriteBlock(db, block)
  536. if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil {
  537. t.Fatalf("failed to insert block number: %v", err)
  538. }
  539. if err := WriteHeadBlockHash(db, block.Hash()); err != nil {
  540. t.Fatalf("failed to insert block number: %v", err)
  541. }
  542. if err := WriteBlockReceipts(db, block.Hash(), block.NumberU64(), receipts[i]); err != nil {
  543. t.Fatal("error writing block receipts:", err)
  544. }
  545. }
  546. bloom := GetMipmapBloom(db, 0, 1000)
  547. if bloom.TestBytes(addr2[:]) {
  548. t.Error("address was included in bloom and should not have")
  549. }
  550. }