accessors_chain_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rawdb
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "math/big"
  22. "testing"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/params"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "golang.org/x/crypto/sha3"
  28. )
  29. // Tests block header storage and retrieval operations.
  30. func TestHeaderStorage(t *testing.T) {
  31. db := NewMemoryDatabase()
  32. // Create a test header to move around the database and make sure it's really new
  33. header := &types.Header{Number: big.NewInt(42), Extra: []byte("test header")}
  34. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  35. t.Fatalf("Non existent header returned: %v", entry)
  36. }
  37. // Write and verify the header in the database
  38. WriteHeader(db, header)
  39. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry == nil {
  40. t.Fatalf("Stored header not found")
  41. } else if entry.Hash() != header.Hash() {
  42. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  43. }
  44. if entry := ReadHeaderRLP(db, header.Hash(), header.Number.Uint64()); entry == nil {
  45. t.Fatalf("Stored header RLP not found")
  46. } else {
  47. hasher := sha3.NewLegacyKeccak256()
  48. hasher.Write(entry)
  49. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  50. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  51. }
  52. }
  53. // Delete the header and verify the execution
  54. DeleteHeader(db, header.Hash(), header.Number.Uint64())
  55. if entry := ReadHeader(db, header.Hash(), header.Number.Uint64()); entry != nil {
  56. t.Fatalf("Deleted header returned: %v", entry)
  57. }
  58. }
  59. // Tests block body storage and retrieval operations.
  60. func TestBodyStorage(t *testing.T) {
  61. db := NewMemoryDatabase()
  62. // Create a test body to move around the database and make sure it's really new
  63. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  64. hasher := sha3.NewLegacyKeccak256()
  65. rlp.Encode(hasher, body)
  66. hash := common.BytesToHash(hasher.Sum(nil))
  67. if entry := ReadBody(db, hash, 0); entry != nil {
  68. t.Fatalf("Non existent body returned: %v", entry)
  69. }
  70. // Write and verify the body in the database
  71. WriteBody(db, hash, 0, body)
  72. if entry := ReadBody(db, hash, 0); entry == nil {
  73. t.Fatalf("Stored body not found")
  74. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  75. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  76. }
  77. if entry := ReadBodyRLP(db, hash, 0); entry == nil {
  78. t.Fatalf("Stored body RLP not found")
  79. } else {
  80. hasher := sha3.NewLegacyKeccak256()
  81. hasher.Write(entry)
  82. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  83. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  84. }
  85. }
  86. // Delete the body and verify the execution
  87. DeleteBody(db, hash, 0)
  88. if entry := ReadBody(db, hash, 0); entry != nil {
  89. t.Fatalf("Deleted body returned: %v", entry)
  90. }
  91. }
  92. // Tests block storage and retrieval operations.
  93. func TestBlockStorage(t *testing.T) {
  94. db := NewMemoryDatabase()
  95. // Create a test block to move around the database and make sure it's really new
  96. block := types.NewBlockWithHeader(&types.Header{
  97. Extra: []byte("test block"),
  98. UncleHash: types.EmptyUncleHash,
  99. TxHash: types.EmptyRootHash,
  100. ReceiptHash: types.EmptyRootHash,
  101. })
  102. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  103. t.Fatalf("Non existent block returned: %v", entry)
  104. }
  105. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  106. t.Fatalf("Non existent header returned: %v", entry)
  107. }
  108. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  109. t.Fatalf("Non existent body returned: %v", entry)
  110. }
  111. // Write and verify the block in the database
  112. WriteBlock(db, block)
  113. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  114. t.Fatalf("Stored block not found")
  115. } else if entry.Hash() != block.Hash() {
  116. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  117. }
  118. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry == nil {
  119. t.Fatalf("Stored header not found")
  120. } else if entry.Hash() != block.Header().Hash() {
  121. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  122. }
  123. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry == nil {
  124. t.Fatalf("Stored body not found")
  125. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  126. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, block.Body())
  127. }
  128. // Delete the block and verify the execution
  129. DeleteBlock(db, block.Hash(), block.NumberU64())
  130. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  131. t.Fatalf("Deleted block returned: %v", entry)
  132. }
  133. if entry := ReadHeader(db, block.Hash(), block.NumberU64()); entry != nil {
  134. t.Fatalf("Deleted header returned: %v", entry)
  135. }
  136. if entry := ReadBody(db, block.Hash(), block.NumberU64()); entry != nil {
  137. t.Fatalf("Deleted body returned: %v", entry)
  138. }
  139. }
  140. // Tests that partial block contents don't get reassembled into full blocks.
  141. func TestPartialBlockStorage(t *testing.T) {
  142. db := NewMemoryDatabase()
  143. block := types.NewBlockWithHeader(&types.Header{
  144. Extra: []byte("test block"),
  145. UncleHash: types.EmptyUncleHash,
  146. TxHash: types.EmptyRootHash,
  147. ReceiptHash: types.EmptyRootHash,
  148. })
  149. // Store a header and check that it's not recognized as a block
  150. WriteHeader(db, block.Header())
  151. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  152. t.Fatalf("Non existent block returned: %v", entry)
  153. }
  154. DeleteHeader(db, block.Hash(), block.NumberU64())
  155. // Store a body and check that it's not recognized as a block
  156. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  157. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry != nil {
  158. t.Fatalf("Non existent block returned: %v", entry)
  159. }
  160. DeleteBody(db, block.Hash(), block.NumberU64())
  161. // Store a header and a body separately and check reassembly
  162. WriteHeader(db, block.Header())
  163. WriteBody(db, block.Hash(), block.NumberU64(), block.Body())
  164. if entry := ReadBlock(db, block.Hash(), block.NumberU64()); entry == nil {
  165. t.Fatalf("Stored block not found")
  166. } else if entry.Hash() != block.Hash() {
  167. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  168. }
  169. }
  170. // Tests block total difficulty storage and retrieval operations.
  171. func TestTdStorage(t *testing.T) {
  172. db := NewMemoryDatabase()
  173. // Create a test TD to move around the database and make sure it's really new
  174. hash, td := common.Hash{}, big.NewInt(314)
  175. if entry := ReadTd(db, hash, 0); entry != nil {
  176. t.Fatalf("Non existent TD returned: %v", entry)
  177. }
  178. // Write and verify the TD in the database
  179. WriteTd(db, hash, 0, td)
  180. if entry := ReadTd(db, hash, 0); entry == nil {
  181. t.Fatalf("Stored TD not found")
  182. } else if entry.Cmp(td) != 0 {
  183. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  184. }
  185. // Delete the TD and verify the execution
  186. DeleteTd(db, hash, 0)
  187. if entry := ReadTd(db, hash, 0); entry != nil {
  188. t.Fatalf("Deleted TD returned: %v", entry)
  189. }
  190. }
  191. // Tests that canonical numbers can be mapped to hashes and retrieved.
  192. func TestCanonicalMappingStorage(t *testing.T) {
  193. db := NewMemoryDatabase()
  194. // Create a test canonical number and assinged hash to move around
  195. hash, number := common.Hash{0: 0xff}, uint64(314)
  196. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  197. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  198. }
  199. // Write and verify the TD in the database
  200. WriteCanonicalHash(db, hash, number)
  201. if entry := ReadCanonicalHash(db, number); entry == (common.Hash{}) {
  202. t.Fatalf("Stored canonical mapping not found")
  203. } else if entry != hash {
  204. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  205. }
  206. // Delete the TD and verify the execution
  207. DeleteCanonicalHash(db, number)
  208. if entry := ReadCanonicalHash(db, number); entry != (common.Hash{}) {
  209. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  210. }
  211. }
  212. // Tests that head headers and head blocks can be assigned, individually.
  213. func TestHeadStorage(t *testing.T) {
  214. db := NewMemoryDatabase()
  215. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  216. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  217. blockFast := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block fast")})
  218. // Check that no head entries are in a pristine database
  219. if entry := ReadHeadHeaderHash(db); entry != (common.Hash{}) {
  220. t.Fatalf("Non head header entry returned: %v", entry)
  221. }
  222. if entry := ReadHeadBlockHash(db); entry != (common.Hash{}) {
  223. t.Fatalf("Non head block entry returned: %v", entry)
  224. }
  225. if entry := ReadHeadFastBlockHash(db); entry != (common.Hash{}) {
  226. t.Fatalf("Non fast head block entry returned: %v", entry)
  227. }
  228. // Assign separate entries for the head header and block
  229. WriteHeadHeaderHash(db, blockHead.Hash())
  230. WriteHeadBlockHash(db, blockFull.Hash())
  231. WriteHeadFastBlockHash(db, blockFast.Hash())
  232. // Check that both heads are present, and different (i.e. two heads maintained)
  233. if entry := ReadHeadHeaderHash(db); entry != blockHead.Hash() {
  234. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  235. }
  236. if entry := ReadHeadBlockHash(db); entry != blockFull.Hash() {
  237. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  238. }
  239. if entry := ReadHeadFastBlockHash(db); entry != blockFast.Hash() {
  240. t.Fatalf("Fast head block hash mismatch: have %v, want %v", entry, blockFast.Hash())
  241. }
  242. }
  243. // Tests that receipts associated with a single block can be stored and retrieved.
  244. func TestBlockReceiptStorage(t *testing.T) {
  245. db := NewMemoryDatabase()
  246. // Create a live block since we need metadata to reconstruct the receipt
  247. tx1 := types.NewTransaction(1, common.HexToAddress("0x1"), big.NewInt(1), 1, big.NewInt(1), nil)
  248. tx2 := types.NewTransaction(2, common.HexToAddress("0x2"), big.NewInt(2), 2, big.NewInt(2), nil)
  249. body := &types.Body{Transactions: types.Transactions{tx1, tx2}}
  250. // Create the two receipts to manage afterwards
  251. receipt1 := &types.Receipt{
  252. Status: types.ReceiptStatusFailed,
  253. CumulativeGasUsed: 1,
  254. Logs: []*types.Log{
  255. {Address: common.BytesToAddress([]byte{0x11})},
  256. {Address: common.BytesToAddress([]byte{0x01, 0x11})},
  257. },
  258. TxHash: tx1.Hash(),
  259. ContractAddress: common.BytesToAddress([]byte{0x01, 0x11, 0x11}),
  260. GasUsed: 111111,
  261. }
  262. receipt1.Bloom = types.CreateBloom(types.Receipts{receipt1})
  263. receipt2 := &types.Receipt{
  264. PostState: common.Hash{2}.Bytes(),
  265. CumulativeGasUsed: 2,
  266. Logs: []*types.Log{
  267. {Address: common.BytesToAddress([]byte{0x22})},
  268. {Address: common.BytesToAddress([]byte{0x02, 0x22})},
  269. },
  270. TxHash: tx2.Hash(),
  271. ContractAddress: common.BytesToAddress([]byte{0x02, 0x22, 0x22}),
  272. GasUsed: 222222,
  273. }
  274. receipt2.Bloom = types.CreateBloom(types.Receipts{receipt2})
  275. receipts := []*types.Receipt{receipt1, receipt2}
  276. // Check that no receipt entries are in a pristine database
  277. hash := common.BytesToHash([]byte{0x03, 0x14})
  278. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  279. t.Fatalf("non existent receipts returned: %v", rs)
  280. }
  281. // Insert the body that corresponds to the receipts
  282. WriteBody(db, hash, 0, body)
  283. // Insert the receipt slice into the database and check presence
  284. WriteReceipts(db, hash, 0, receipts)
  285. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) == 0 {
  286. t.Fatalf("no receipts returned")
  287. } else {
  288. if err := checkReceiptsRLP(rs, receipts); err != nil {
  289. t.Fatalf(err.Error())
  290. }
  291. }
  292. // Delete the body and ensure that the receipts are no longer returned (metadata can't be recomputed)
  293. DeleteBody(db, hash, 0)
  294. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); rs != nil {
  295. t.Fatalf("receipts returned when body was deleted: %v", rs)
  296. }
  297. // Ensure that receipts without metadata can be returned without the block body too
  298. if err := checkReceiptsRLP(ReadRawReceipts(db, hash, 0), receipts); err != nil {
  299. t.Fatalf(err.Error())
  300. }
  301. // Sanity check that body alone without the receipt is a full purge
  302. WriteBody(db, hash, 0, body)
  303. DeleteReceipts(db, hash, 0)
  304. if rs := ReadReceipts(db, hash, 0, params.TestChainConfig); len(rs) != 0 {
  305. t.Fatalf("deleted receipts returned: %v", rs)
  306. }
  307. }
  308. func checkReceiptsRLP(have, want types.Receipts) error {
  309. if len(have) != len(want) {
  310. return fmt.Errorf("receipts sizes mismatch: have %d, want %d", len(have), len(want))
  311. }
  312. for i := 0; i < len(want); i++ {
  313. rlpHave, err := rlp.EncodeToBytes(have[i])
  314. if err != nil {
  315. return err
  316. }
  317. rlpWant, err := rlp.EncodeToBytes(want[i])
  318. if err != nil {
  319. return err
  320. }
  321. if !bytes.Equal(rlpHave, rlpWant) {
  322. return fmt.Errorf("receipt #%d: receipt mismatch: have %s, want %s", i, hex.EncodeToString(rlpHave), hex.EncodeToString(rlpWant))
  323. }
  324. }
  325. return nil
  326. }