database_util_test.go 22 KB

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