accessors_chain_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. "math/rand"
  24. "os"
  25. "reflect"
  26. "testing"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/params"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/stretchr/testify/assert"
  34. "golang.org/x/crypto/sha3"
  35. )
  36. // Tests block header storage and retrieval operations.
  37. func TestHeaderStorage(t *testing.T) {
  38. db := NewMemoryDatabase()
  39. // Create a test header to move around the database and make sure it's really new
  40. header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
  41. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  42. t.Fatalf("Non existent header returned: %v", entry)
  43. }
  44. // Write and verify the header in the database
  45. WriteHeader(db, header)
  46. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
  47. t.Fatalf("Stored header not found")
  48. } else if entry.Hash() != header.Hash() {
  49. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  50. }
  51. if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
  52. t.Fatalf("Stored header RLP not found")
  53. } else {
  54. hasher := sha3.NewLegacyKeccak256()
  55. hasher.Write(entry)
  56. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  57. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  58. }
  59. }
  60. // Delete the header and verify the execution
  61. DeleteHeader(db, header.Hash(), header.Number.Uint64())
  62. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  63. t.Fatalf("Deleted header returned: %v", entry)
  64. }
  65. }
  66. // Tests block body storage and retrieval operations.
  67. func TestBodyStorage(t *testing.T) {
  68. db := NewMemoryDatabase()
  69. // Create a test body to move around the database and make sure it's really new
  70. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  71. hasher := sha3.NewLegacyKeccak256()
  72. rlp.Encode(hasher, body)
  73. hash := common.BytesToHash(hasher.Sum(nil))
  74. if entry := ReadBody(db, hash, 0); entry != nil {
  75. t.Fatalf("Non existent body returned: %v", entry)
  76. }
  77. // Write and verify the body in the database
  78. WriteBody(db, hash, 0, body)
  79. if entry := ReadBody(db, hash, 0); entry == nil {
  80. t.Fatalf("Stored body not found")
  81. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(types.Transactions(body.Transactions), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  82. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  83. }
  84. if entry := ReadBodyRLP(db, hash, 0); entry == nil {
  85. t.Fatalf("Stored body RLP not found")
  86. } else {
  87. hasher := sha3.NewLegacyKeccak256()
  88. hasher.Write(entry)
  89. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  90. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  91. }
  92. }
  93. // Delete the body and verify the execution
  94. DeleteBody(db, hash, 0)
  95. if entry := ReadBody(db, hash, 0); entry != nil {
  96. t.Fatalf("Deleted body returned: %v", entry)
  97. }
  98. }
  99. // Tests block storage and retrieval operations.
  100. func TestBlockStorage(t *testing.T) {
  101. db := NewMemoryDatabase()
  102. // Create a test block to move around the database and make sure it's really new
  103. block := types.NewBlockWithHeader(&types.Header{
  104. Extra: []byte("test block"),
  105. UncleHash: types.EmptyUncleHash,
  106. TxHash: types.EmptyRootHash,
  107. ReceiptHash: types.EmptyRootHash,
  108. })
  109. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  110. t.Fatalf("Non existent block returned: %v", entry)
  111. }
  112. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  113. t.Fatalf("Non existent header returned: %v", entry)
  114. }
  115. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  116. t.Fatalf("Non existent body returned: %v", entry)
  117. }
  118. // Write and verify the block in the database
  119. WriteBlock(db, block)
  120. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  121. t.Fatalf("Stored block not found")
  122. } else if entry.Hash() != block.Hash() {
  123. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  124. }
  125. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
  126. t.Fatalf("Stored header not found")
  127. } else if entry.Hash() != block.Header().Hash() {
  128. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  129. }
  130. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
  131. t.Fatalf("Stored body not found")
  132. } else if types.DeriveSha(types.Transactions(entry.Transactions), newHasher()) != types.DeriveSha(block.Transactions(), newHasher()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  133. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
  134. }
  135. // Delete the block and verify the execution
  136. DeleteBlock(db, block.Hash(), block.NumberU64())
  137. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  138. t.Fatalf("Deleted block returned: %v", entry)
  139. }
  140. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  141. t.Fatalf("Deleted header returned: %v", entry)
  142. }
  143. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  144. t.Fatalf("Deleted body returned: %v", entry)
  145. }
  146. }
  147. // Tests that partial block contents don't get reassembled into full blocks.
  148. func TestPartialBlockStorage(t *testing.T) {
  149. db := NewMemoryDatabase()
  150. block := types.NewBlockWithHeader(&types.Header{
  151. Extra: []byte("test block"),
  152. UncleHash: types.EmptyUncleHash,
  153. TxHash: types.EmptyRootHash,
  154. ReceiptHash: types.EmptyRootHash,
  155. })
  156. // Store a header and check that it's not recognized as a block
  157. WriteHeader(db, block.Header())
  158. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  159. t.Fatalf("Non existent block returned: %v", entry)
  160. }
  161. DeleteHeader(db, block.Hash(), block.NumberU64())
  162. // Store a body and check that it's not recognized as a block
  163. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  164. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  165. t.Fatalf("Non existent block returned: %v", entry)
  166. }
  167. DeleteBody(db, block.Hash(), block.NumberU64())
  168. // Store a header and a body separately and check reassembly
  169. WriteHeader(db, block.Header())
  170. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  171. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  172. t.Fatalf("Stored block not found")
  173. } else if entry.Hash() != block.Hash() {
  174. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  175. }
  176. }
  177. // Tests block storage and retrieval operations.
  178. func TestBadBlockStorage(t *testing.T) {
  179. db := NewMemoryDatabase()
  180. // Create a test block to move around the database and make sure it's really new
  181. block := types.NewBlockWithHeader(&types.Header{
  182. Number: big.NewInt(1),
  183. Extra: []byte("bad block"),
  184. UncleHash: types.EmptyUncleHash,
  185. TxHash: types.EmptyRootHash,
  186. ReceiptHash: types.EmptyRootHash,
  187. })
  188. if entry := ReadBadBlock(db, block.Hash()); entry != nil {
  189. t.Fatalf("Non existent block returned: %v", entry)
  190. }
  191. // Write and verify the block in the database
  192. WriteBadBlock(db, block)
  193. if entry := ReadBadBlock(db, block.Hash()); entry == nil {
  194. t.Fatalf("Stored block not found")
  195. } else if entry.Hash() != block.Hash() {
  196. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  197. }
  198. // Write one more bad block
  199. blockTwo := types.NewBlockWithHeader(&types.Header{
  200. Number: big.NewInt(2),
  201. Extra: []byte("bad block two"),
  202. UncleHash: types.EmptyUncleHash,
  203. TxHash: types.EmptyRootHash,
  204. ReceiptHash: types.EmptyRootHash,
  205. })
  206. WriteBadBlock(db, blockTwo)
  207. // Write the block one again, should be filtered out.
  208. WriteBadBlock(db, block)
  209. badBlocks := ReadAllBadBlocks(db)
  210. if len(badBlocks) != 2 {
  211. t.Fatalf("Failed to load all bad blocks")
  212. }
  213. // Write a bunch of bad blocks, all the blocks are should sorted
  214. // in reverse order. The extra blocks should be truncated.
  215. for _, n := range rand.Perm(100) {
  216. block := types.NewBlockWithHeader(&types.Header{
  217. Number: big.NewInt(int64(n)),
  218. Extra: []byte("bad block"),
  219. UncleHash: types.EmptyUncleHash,
  220. TxHash: types.EmptyRootHash,
  221. ReceiptHash: types.EmptyRootHash,
  222. })
  223. WriteBadBlock(db, block)
  224. }
  225. badBlocks = ReadAllBadBlocks(db)
  226. if len(badBlocks) != badBlockToKeep {
  227. t.Fatalf("The number of persised bad blocks in incorrect %d", len(badBlocks))
  228. }
  229. for i := 0; i < len(badBlocks)-1; i++ {
  230. if badBlocks[i].NumberU64() < badBlocks[i+1].NumberU64() {
  231. t.Fatalf("The bad blocks are not sorted #[%d](%d) < #[%d](%d)", i, i+1, badBlocks[i].NumberU64(), badBlocks[i+1].NumberU64())
  232. }
  233. }
  234. // Delete all bad blocks
  235. DeleteBadBlocks(db)
  236. badBlocks = ReadAllBadBlocks(db)
  237. if len(badBlocks) != 0 {
  238. t.Fatalf("Failed to delete bad blocks")
  239. }
  240. }
  241. // Tests block total difficulty storage and retrieval operations.
  242. func TestTdStorage(t *testing.T) {
  243. db := NewMemoryDatabase()
  244. // Create a test TD to move around the database and make sure it's really new
  245. hash, td := common.Hash{}, big.NewInt(314)
  246. if entry := ReadTd(db, hash, 0); entry != nil {
  247. t.Fatalf("Non existent TD returned: %v", entry)
  248. }
  249. // Write and verify the TD in the database
  250. WriteTd(db, hash, 0, td)
  251. if entry := ReadTd(db, hash, 0); entry == nil {
  252. t.Fatalf("Stored TD not found")
  253. } else if entry.Cmp(td) != 0 {
  254. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  255. }
  256. // Delete the TD and verify the execution
  257. DeleteTd(db, hash, 0)
  258. if entry := ReadTd(db, hash, 0); entry != nil {
  259. t.Fatalf("Deleted TD returned: %v", entry)
  260. }
  261. }
  262. // Tests that canonical numbers can be mapped to hashes and retrieved.
  263. func TestCanonicalMappingStorage(t *testing.T) {
  264. db := NewMemoryDatabase()
  265. // Create a test canonical number and assinged hash to move around
  266. hash, number := common.Hash{0: 0xff}, uint64(314)
  267. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  268. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  269. }
  270. // Write and verify the TD in the database
  271. WriteCanonicalHash(db, hash, number)
  272. if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
  273. t.Fatalf("Stored canonical mapping not found")
  274. } else if entry != hash {
  275. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  276. }
  277. // Delete the TD and verify the execution
  278. DeleteCanonicalHash(db, number)
  279. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  280. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  281. }
  282. }
  283. // Tests that head headers and head blocks can be assigned, individually.
  284. func TestHeadStorage(t *testing.T) {
  285. db := NewMemoryDatabase()
  286. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  287. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  288. blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
  289. // Check that no head entries are in a pristine database
  290. if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
  291. t.Fatalf("Non head header entry returned: %v", entry)
  292. }
  293. if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
  294. t.Fatalf("Non head block entry returned: %v", entry)
  295. }
  296. if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
  297. t.Fatalf("Non fast head block entry returned: %v", entry)
  298. }
  299. // Assign separate entries for the head header and block
  300. WriteHeadHeaderHash(db, blockHead.Hash())
  301. WriteHeadBlockHash(db, blockFull.Hash())
  302. WriteHeadFastBlockHash(db, blockFast.Hash())
  303. // Check that both heads are present, and different (i.e. two heads maintained)
  304. if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
  305. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  306. }
  307. if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
  308. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  309. }
  310. if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
  311. t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
  312. }
  313. }
  314. // Tests that receipts associated with a single block can be stored and retrieved.
  315. func TestBlockReceiptStorage(t *testing.T) {
  316. db := NewMemoryDatabase()
  317. // Create a live block since we need metadata to reconstruct the receipt
  318. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  319. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  320. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  321. // Create the two receipts to manage afterwards
  322. receipt1 := &types.Receipt{
  323. Status: types.ReceiptStatusFailed,
  324. CumulativeGasUsed: 1,
  325. Logs: []*types.Log{
  326. {Address: common.BytesToAddress([]byte{0x11})},
  327. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  328. },
  329. TxHash: tx1.Hash(),
  330. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  331. GasUsed: 111111,
  332. }
  333. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  334. receipt2 := &types.Receipt{
  335. PostState: common.Hash{2}.Bytes(),
  336. CumulativeGasUsed: 2,
  337. Logs: []*types.Log{
  338. {Address: common.BytesToAddress([]byte{0x22})},
  339. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  340. },
  341. TxHash: tx2.Hash(),
  342. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  343. GasUsed: 222222,
  344. }
  345. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  346. receipts := []*types.Receipt{receipt1, receipt2}
  347. // Check that no receipt entries are in a pristine database
  348. hash := common.BytesToHash([]byte{0x03, 0x14})
  349. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  350. t.Fatalf("non existent receipts returned: %v", rs)
  351. }
  352. // Insert the body that corresponds to the receipts
  353. WriteBody(db, hash, 0, body)
  354. // Insert the receipt slice into the database and check presence
  355. WriteReceipts(db, hash, 0, receipts)
  356. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  357. t.Fatalf("no receipts returned")
  358. } else {
  359. if err := checkReceiptsRLP(rs, receipts); err != nil {
  360. t.Fatalf(err.Error())
  361. }
  362. // check that the raw data does not contain the quorumExtraData array (since the prepared receipts do not have any quorumExtraData)
  363. receiptData := ReadReceiptsRLP(db, hash, 0)
  364. _, extraData, err := rlp.SplitList(receiptData)
  365. assert.NoError(t, err)
  366. assert.Empty(t, extraData)
  367. }
  368. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  369. DeleteBody(db, hash, 0)
  370. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  371. t.Fatalf("receipts returned when body was deleted: %v", rs)
  372. }
  373. // Ensure that receipts without metadata can be returned without the block body too
  374. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  375. t.Fatalf(err.Error())
  376. }
  377. // Sanity check that body alone without the receipt is a full purge
  378. WriteBody(db, hash, 0, body)
  379. DeleteReceipts(db, hash, 0)
  380. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  381. t.Fatalf("deleted receipts returned: %v", rs)
  382. }
  383. }
  384. func TestBlockReceiptStorageWithLegacyMPSV1EncodingWithMPSData(t *testing.T) {
  385. db := NewMemoryDatabase()
  386. // Create a live block since we need metadata to reconstruct the receipt
  387. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  388. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  389. tx2.SetPrivate()
  390. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  391. // Create the two receipts to manage afterwards
  392. receipt1 := &types.Receipt{
  393. Status: types.ReceiptStatusFailed,
  394. CumulativeGasUsed: 1,
  395. Logs: []*types.Log{
  396. {Address: common.BytesToAddress([]byte{0x11})},
  397. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  398. },
  399. TxHash: tx1.Hash(),
  400. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  401. GasUsed: 111111,
  402. }
  403. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  404. psiReceipt2 := &types.Receipt{
  405. PostState: common.Hash{2}.Bytes(),
  406. CumulativeGasUsed: 2,
  407. Logs: []*types.Log{
  408. {Address: common.BytesToAddress([]byte{0x22})},
  409. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  410. },
  411. TxHash: tx2.Hash(),
  412. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  413. GasUsed: 222222,
  414. }
  415. receipt2 := &types.Receipt{
  416. PostState: common.Hash{2}.Bytes(),
  417. CumulativeGasUsed: 2,
  418. Logs: []*types.Log{
  419. {Address: common.BytesToAddress([]byte{0x22})},
  420. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  421. },
  422. TxHash: tx2.Hash(),
  423. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  424. GasUsed: 222222,
  425. QuorumReceiptExtraData: types.QuorumReceiptExtraData{
  426. PSReceipts: map[types.PrivateStateIdentifier]*types.Receipt{types.PrivateStateIdentifier("psi1"): psiReceipt2},
  427. },
  428. }
  429. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  430. receipts := []*types.Receipt{receipt1, receipt2}
  431. // Check that no receipt entries are in a pristine database
  432. hash := common.BytesToHash([]byte{0x03, 0x14})
  433. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  434. t.Fatalf("non existent receipts returned: %v", rs)
  435. }
  436. // Insert the body that corresponds to the receipts
  437. WriteBody(db, hash, 0, body)
  438. // Insert the receipt slice into the database and check presence
  439. WriteReceiptsMPSV1(db, hash, 0, receipts)
  440. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  441. t.Fatalf("no receipts returned")
  442. } else {
  443. if err := checkReceiptsRLP(rs, receipts); err != nil {
  444. t.Fatalf(err.Error())
  445. }
  446. rec2 := rs[1]
  447. assert.Len(t, rec2.PSReceipts, 1)
  448. psRec2 := rec2.PSReceipts[types.PrivateStateIdentifier("psi1")]
  449. assert.NotNil(t, psRec2)
  450. }
  451. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  452. DeleteBody(db, hash, 0)
  453. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  454. t.Fatalf("receipts returned when body was deleted: %v", rs)
  455. }
  456. // Ensure that receipts without metadata can be returned without the block body too
  457. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  458. t.Fatalf(err.Error())
  459. }
  460. }
  461. func TestBlockReceiptStorageWithLegacyMPSV1EncodingWithoutMPSData(t *testing.T) {
  462. db := NewMemoryDatabase()
  463. // Create a live block since we need metadata to reconstruct the receipt
  464. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  465. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  466. tx2.SetPrivate()
  467. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  468. // Create the two receipts to manage afterwards
  469. receipt1 := &types.Receipt{
  470. Status: types.ReceiptStatusFailed,
  471. CumulativeGasUsed: 1,
  472. Logs: []*types.Log{
  473. {Address: common.BytesToAddress([]byte{0x11})},
  474. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  475. },
  476. TxHash: tx1.Hash(),
  477. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  478. GasUsed: 111111,
  479. }
  480. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  481. receipt2 := &types.Receipt{
  482. PostState: common.Hash{2}.Bytes(),
  483. CumulativeGasUsed: 2,
  484. Logs: []*types.Log{
  485. {Address: common.BytesToAddress([]byte{0x22})},
  486. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  487. },
  488. TxHash: tx2.Hash(),
  489. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  490. GasUsed: 222222,
  491. }
  492. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  493. receipts := []*types.Receipt{receipt1, receipt2}
  494. // Check that no receipt entries are in a pristine database
  495. hash := common.BytesToHash([]byte{0x03, 0x14})
  496. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  497. t.Fatalf("non existent receipts returned: %v", rs)
  498. }
  499. // Insert the body that corresponds to the receipts
  500. WriteBody(db, hash, 0, body)
  501. // Insert the receipt slice into the database and check presence
  502. WriteReceiptsMPSV1(db, hash, 0, receipts)
  503. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  504. t.Fatalf("no receipts returned")
  505. } else {
  506. if err := checkReceiptsRLP(rs, receipts); err != nil {
  507. t.Fatalf(err.Error())
  508. }
  509. rec2 := rs[1]
  510. assert.Len(t, rec2.PSReceipts, 0)
  511. }
  512. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  513. DeleteBody(db, hash, 0)
  514. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  515. t.Fatalf("receipts returned when body was deleted: %v", rs)
  516. }
  517. // Ensure that receipts without metadata can be returned without the block body too
  518. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  519. t.Fatalf(err.Error())
  520. }
  521. }
  522. // Tests that receipts associated with a single block can be stored and retrieved.
  523. func TestBlockReceiptStorageWithQuorumExtraData(t *testing.T) {
  524. db := NewMemoryDatabase()
  525. // Create a live block since we need metadata to reconstruct the receipt
  526. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  527. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  528. tx2.SetPrivate()
  529. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  530. // Create the two receipts to manage afterwards
  531. receipt1 := &types.Receipt{
  532. Status: types.ReceiptStatusFailed,
  533. CumulativeGasUsed: 1,
  534. Logs: []*types.Log{
  535. {Address: common.BytesToAddress([]byte{0x11})},
  536. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  537. },
  538. TxHash: tx1.Hash(),
  539. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  540. GasUsed: 111111,
  541. }
  542. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  543. psiReceipt2 := &types.Receipt{
  544. PostState: common.Hash{2}.Bytes(),
  545. CumulativeGasUsed: 2,
  546. Logs: []*types.Log{
  547. {Address: common.BytesToAddress([]byte{0x22})},
  548. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  549. },
  550. TxHash: tx2.Hash(),
  551. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  552. GasUsed: 222222,
  553. QuorumReceiptExtraData: types.QuorumReceiptExtraData{
  554. RevertReason: []byte("arbitraryvalue"),
  555. },
  556. }
  557. receipt2 := &types.Receipt{
  558. PostState: common.Hash{2}.Bytes(),
  559. CumulativeGasUsed: 2,
  560. Logs: []*types.Log{
  561. {Address: common.BytesToAddress([]byte{0x22})},
  562. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  563. },
  564. TxHash: tx2.Hash(),
  565. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  566. GasUsed: 222222,
  567. QuorumReceiptExtraData: types.QuorumReceiptExtraData{
  568. RevertReason: []byte("arbitraryvalue"),
  569. PSReceipts: map[types.PrivateStateIdentifier]*types.Receipt{types.PrivateStateIdentifier("psi1"): psiReceipt2},
  570. },
  571. }
  572. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  573. receipts := []*types.Receipt{receipt1, receipt2}
  574. // Check that no receipt entries are in a pristine database
  575. hash := common.BytesToHash([]byte{0x03, 0x14})
  576. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  577. t.Fatalf("non existent receipts returned: %v", rs)
  578. }
  579. // Insert the body that corresponds to the receipts
  580. WriteBody(db, hash, 0, body)
  581. // Insert the receipt slice into the database and check presence
  582. WriteReceipts(db, hash, 0, receipts)
  583. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  584. t.Fatalf("no receipts returned")
  585. } else {
  586. if err := checkReceiptsRLP(rs, receipts); err != nil {
  587. t.Fatalf(err.Error())
  588. }
  589. rec2 := rs[1]
  590. assert.Len(t, rec2.PSReceipts, 1)
  591. assert.Equal(t, rec2.RevertReason, []byte("arbitraryvalue"))
  592. psRec2 := rec2.PSReceipts[types.PrivateStateIdentifier("psi1")]
  593. assert.Equal(t, psRec2.RevertReason, []byte("arbitraryvalue"))
  594. }
  595. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  596. DeleteBody(db, hash, 0)
  597. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  598. t.Fatalf("receipts returned when body was deleted: %v", rs)
  599. }
  600. // Ensure that receipts without metadata can be returned without the block body too
  601. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  602. t.Fatalf(err.Error())
  603. }
  604. // Sanity check that body alone without the receipt is a full purge
  605. WriteBody(db, hash, 0, body)
  606. DeleteReceipts(db, hash, 0)
  607. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  608. t.Fatalf("deleted receipts returned: %v", rs)
  609. }
  610. }
  611. func checkReceiptsRLP(have, want types.Receipts) error {
  612. if len(have) != len(want) {
  613. return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
  614. }
  615. for i := 0; i < len(want); i++ {
  616. rlpHave, err := rlp.EncodeToBytes(have[i])
  617. if err != nil {
  618. return err
  619. }
  620. rlpWant, err := rlp.EncodeToBytes(want[i])
  621. if err != nil {
  622. return err
  623. }
  624. if !bytes.Equal(rlpHave, rlpWant) {
  625. return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
  626. }
  627. }
  628. return nil
  629. }
  630. func TestAncientStorage(t *testing.T) {
  631. // Freezer style fast import the chain.
  632. frdir, err := ioutil.TempDir("", "")
  633. if err != nil {
  634. t.Fatalf("failed to create temp freezer dir: %v", err)
  635. }
  636. defer os.Remove(frdir)
  637. db, err := NewDatabaseWithFreezer(NewMemoryDatabase(), frdir, "", false)
  638. if err != nil {
  639. t.Fatalf("failed to create database with ancient backend")
  640. }
  641. // Create a test block
  642. block := types.NewBlockWithHeader(&types.Header{
  643. Number: big.NewInt(0),
  644. Extra: []byte("test block"),
  645. UncleHash: types.EmptyUncleHash,
  646. TxHash: types.EmptyRootHash,
  647. ReceiptHash: types.EmptyRootHash,
  648. })
  649. // Ensure nothing non-existent will be read
  650. hash, number := block.Hash(), block.NumberU64()
  651. if blob := ReadHeaderRLP(db, hash, number); len(blob) > 0 {
  652. t.Fatalf("non existent header returned")
  653. }
  654. if blob := ReadBodyRLP(db, hash, number); len(blob) > 0 {
  655. t.Fatalf("non existent body returned")
  656. }
  657. if blob := ReadReceiptsRLP(db, hash, number); len(blob) > 0 {
  658. t.Fatalf("non existent receipts returned")
  659. }
  660. if blob := ReadTdRLP(db, hash, number); len(blob) > 0 {
  661. t.Fatalf("non existent td returned")
  662. }
  663. // Write and verify the header in the database
  664. WriteAncientBlock(db, block, nil, big.NewInt(100))
  665. if blob := ReadHeaderRLP(db, hash, number); len(blob) == 0 {
  666. t.Fatalf("no header returned")
  667. }
  668. if blob := ReadBodyRLP(db, hash, number); len(blob) == 0 {
  669. t.Fatalf("no body returned")
  670. }
  671. if blob := ReadReceiptsRLP(db, hash, number); len(blob) == 0 {
  672. t.Fatalf("no receipts returned")
  673. }
  674. if blob := ReadTdRLP(db, hash, number); len(blob) == 0 {
  675. t.Fatalf("no td returned")
  676. }
  677. // Use a fake hash for data retrieval, nothing should be returned.
  678. fakeHash := common.BytesToHash([]byte{0x01, 0x02, 0x03})
  679. if blob := ReadHeaderRLP(db, fakeHash, number); len(blob) != 0 {
  680. t.Fatalf("invalid header returned")
  681. }
  682. if blob := ReadBodyRLP(db, fakeHash, number); len(blob) != 0 {
  683. t.Fatalf("invalid body returned")
  684. }
  685. if blob := ReadReceiptsRLP(db, fakeHash, number); len(blob) != 0 {
  686. t.Fatalf("invalid receipts returned")
  687. }
  688. if blob := ReadTdRLP(db, fakeHash, number); len(blob) != 0 {
  689. t.Fatalf("invalid td returned")
  690. }
  691. }
  692. func TestCanonicalHashIteration(t *testing.T) {
  693. var cases = []struct {
  694. from, to uint64
  695. limit int
  696. expect []uint64
  697. }{
  698. {1, 8, 0, nil},
  699. {1, 8, 1, []uint64{1}},
  700. {1, 8, 10, []uint64{1, 2, 3, 4, 5, 6, 7}},
  701. {1, 9, 10, []uint64{1, 2, 3, 4, 5, 6, 7, 8}},
  702. {2, 9, 10, []uint64{2, 3, 4, 5, 6, 7, 8}},
  703. {9, 10, 10, nil},
  704. }
  705. // Test empty db iteration
  706. db := NewMemoryDatabase()
  707. numbers, _ := ReadAllCanonicalHashes(db, 0, 10, 10)
  708. if len(numbers) != 0 {
  709. t.Fatalf("No entry should be returned to iterate an empty db")
  710. }
  711. // Fill database with testing data.
  712. for i := uint64(1); i <= 8; i++ {
  713. WriteCanonicalHash(db, common.Hash{}, i)
  714. WriteTd(db, common.Hash{}, i, big.NewInt(10)) // Write some interferential data
  715. }
  716. for i, c := range cases {
  717. numbers, _ := ReadAllCanonicalHashes(db, c.from, c.to, c.limit)
  718. if !reflect.DeepEqual(numbers, c.expect) {
  719. t.Fatalf("Case %d failed, want %v, got %v", i, c.expect, numbers)
  720. }
  721. }
  722. }
  723. func WriteReceiptsMPSV1(db ethdb.KeyValueWriter, hash common.Hash, number uint64, receipts types.Receipts) {
  724. // Convert the receipts into their storage form and serialize them
  725. storageReceipts := make([]*types.ReceiptForStorageMPSV1, len(receipts))
  726. for i, receipt := range receipts {
  727. storageReceipts[i] = (*types.ReceiptForStorageMPSV1)(receipt)
  728. }
  729. bytes, err := rlp.EncodeToBytes(storageReceipts)
  730. if err != nil {
  731. log.Crit("Failed to encode block receipts", "err", err)
  732. }
  733. // Store the flattened receipt slice
  734. if err := db.Put(blockReceiptsKey(number, hash), bytes); err != nil {
  735. log.Crit("Failed to store block receipts", "err", err)
  736. }
  737. }