chain_util_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. "encoding/json"
  19. "io/ioutil"
  20. "math/big"
  21. "os"
  22. "testing"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/core/vm"
  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/rlp"
  30. )
  31. type diffTest struct {
  32. ParentTimestamp uint64
  33. ParentDifficulty *big.Int
  34. CurrentTimestamp uint64
  35. CurrentBlocknumber *big.Int
  36. CurrentDifficulty *big.Int
  37. }
  38. func (d *diffTest) UnmarshalJSON(b []byte) (err error) {
  39. var ext struct {
  40. ParentTimestamp string
  41. ParentDifficulty string
  42. CurrentTimestamp string
  43. CurrentBlocknumber string
  44. CurrentDifficulty string
  45. }
  46. if err := json.Unmarshal(b, &ext); err != nil {
  47. return err
  48. }
  49. d.ParentTimestamp = common.String2Big(ext.ParentTimestamp).Uint64()
  50. d.ParentDifficulty = common.String2Big(ext.ParentDifficulty)
  51. d.CurrentTimestamp = common.String2Big(ext.CurrentTimestamp).Uint64()
  52. d.CurrentBlocknumber = common.String2Big(ext.CurrentBlocknumber)
  53. d.CurrentDifficulty = common.String2Big(ext.CurrentDifficulty)
  54. return nil
  55. }
  56. func TestDifficulty(t *testing.T) {
  57. file, err := os.Open("../tests/files/BasicTests/difficulty.json")
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. defer file.Close()
  62. tests := make(map[string]diffTest)
  63. err = json.NewDecoder(file).Decode(&tests)
  64. if err != nil {
  65. t.Fatal(err)
  66. }
  67. for name, test := range tests {
  68. number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1))
  69. diff := CalcDifficulty(test.CurrentTimestamp, test.ParentTimestamp, number, test.ParentDifficulty)
  70. if diff.Cmp(test.CurrentDifficulty) != 0 {
  71. t.Error(name, "failed. Expected", test.CurrentDifficulty, "and calculated", diff)
  72. }
  73. }
  74. }
  75. // Tests block header storage and retrieval operations.
  76. func TestHeaderStorage(t *testing.T) {
  77. db, _ := ethdb.NewMemDatabase()
  78. // Create a test header to move around the database and make sure it's really new
  79. header := &types.Header{Extra: []byte("test header")}
  80. if entry := GetHeader(db, header.Hash()); entry != nil {
  81. t.Fatalf("Non existent header returned: %v", entry)
  82. }
  83. // Write and verify the header in the database
  84. if err := WriteHeader(db, header); err != nil {
  85. t.Fatalf("Failed to write header into database: %v", err)
  86. }
  87. if entry := GetHeader(db, header.Hash()); entry == nil {
  88. t.Fatalf("Stored header not found")
  89. } else if entry.Hash() != header.Hash() {
  90. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, header)
  91. }
  92. if entry := GetHeaderRLP(db, header.Hash()); entry == nil {
  93. t.Fatalf("Stored header RLP not found")
  94. } else {
  95. hasher := sha3.NewKeccak256()
  96. hasher.Write(entry)
  97. if hash := common.BytesToHash(hasher.Sum(nil)); hash != header.Hash() {
  98. t.Fatalf("Retrieved RLP header mismatch: have %v, want %v", entry, header)
  99. }
  100. }
  101. // Delete the header and verify the execution
  102. DeleteHeader(db, header.Hash())
  103. if entry := GetHeader(db, header.Hash()); entry != nil {
  104. t.Fatalf("Deleted header returned: %v", entry)
  105. }
  106. }
  107. // Tests block body storage and retrieval operations.
  108. func TestBodyStorage(t *testing.T) {
  109. db, _ := ethdb.NewMemDatabase()
  110. // Create a test body to move around the database and make sure it's really new
  111. body := &types.Body{Uncles: []*types.Header{{Extra: []byte("test header")}}}
  112. hasher := sha3.NewKeccak256()
  113. rlp.Encode(hasher, body)
  114. hash := common.BytesToHash(hasher.Sum(nil))
  115. if entry := GetBody(db, hash); entry != nil {
  116. t.Fatalf("Non existent body returned: %v", entry)
  117. }
  118. // Write and verify the body in the database
  119. if err := WriteBody(db, hash, body); err != nil {
  120. t.Fatalf("Failed to write body into database: %v", err)
  121. }
  122. if entry := GetBody(db, hash); entry == nil {
  123. t.Fatalf("Stored body not found")
  124. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(types.Transactions(body.Transactions)) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(body.Uncles) {
  125. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, body)
  126. }
  127. if entry := GetBodyRLP(db, hash); entry == nil {
  128. t.Fatalf("Stored body RLP not found")
  129. } else {
  130. hasher := sha3.NewKeccak256()
  131. hasher.Write(entry)
  132. if calc := common.BytesToHash(hasher.Sum(nil)); calc != hash {
  133. t.Fatalf("Retrieved RLP body mismatch: have %v, want %v", entry, body)
  134. }
  135. }
  136. // Delete the body and verify the execution
  137. DeleteBody(db, hash)
  138. if entry := GetBody(db, hash); entry != nil {
  139. t.Fatalf("Deleted body returned: %v", entry)
  140. }
  141. }
  142. // Tests block storage and retrieval operations.
  143. func TestBlockStorage(t *testing.T) {
  144. db, _ := ethdb.NewMemDatabase()
  145. // Create a test block to move around the database and make sure it's really new
  146. block := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block")})
  147. if entry := GetBlock(db, block.Hash()); entry != nil {
  148. t.Fatalf("Non existent block returned: %v", entry)
  149. }
  150. if entry := GetHeader(db, block.Hash()); entry != nil {
  151. t.Fatalf("Non existent header returned: %v", entry)
  152. }
  153. if entry := GetBody(db, block.Hash()); entry != nil {
  154. t.Fatalf("Non existent body returned: %v", entry)
  155. }
  156. // Write and verify the block in the database
  157. if err := WriteBlock(db, block); err != nil {
  158. t.Fatalf("Failed to write block into database: %v", err)
  159. }
  160. if entry := GetBlock(db, block.Hash()); entry == nil {
  161. t.Fatalf("Stored block not found")
  162. } else if entry.Hash() != block.Hash() {
  163. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  164. }
  165. if entry := GetHeader(db, block.Hash()); entry == nil {
  166. t.Fatalf("Stored header not found")
  167. } else if entry.Hash() != block.Header().Hash() {
  168. t.Fatalf("Retrieved header mismatch: have %v, want %v", entry, block.Header())
  169. }
  170. if entry := GetBody(db, block.Hash()); entry == nil {
  171. t.Fatalf("Stored body not found")
  172. } else if types.DeriveSha(types.Transactions(entry.Transactions)) != types.DeriveSha(block.Transactions()) || types.CalcUncleHash(entry.Uncles) != types.CalcUncleHash(block.Uncles()) {
  173. t.Fatalf("Retrieved body mismatch: have %v, want %v", entry, &types.Body{block.Transactions(), block.Uncles()})
  174. }
  175. // Delete the block and verify the execution
  176. DeleteBlock(db, block.Hash())
  177. if entry := GetBlock(db, block.Hash()); entry != nil {
  178. t.Fatalf("Deleted block returned: %v", entry)
  179. }
  180. if entry := GetHeader(db, block.Hash()); entry != nil {
  181. t.Fatalf("Deleted header returned: %v", entry)
  182. }
  183. if entry := GetBody(db, block.Hash()); entry != nil {
  184. t.Fatalf("Deleted body returned: %v", entry)
  185. }
  186. }
  187. // Tests that partial block contents don't get reassembled into full blocks.
  188. func TestPartialBlockStorage(t *testing.T) {
  189. db, _ := ethdb.NewMemDatabase()
  190. block := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block")})
  191. // Store a header and check that it's not recognized as a block
  192. if err := WriteHeader(db, block.Header()); err != nil {
  193. t.Fatalf("Failed to write header into database: %v", err)
  194. }
  195. if entry := GetBlock(db, block.Hash()); entry != nil {
  196. t.Fatalf("Non existent block returned: %v", entry)
  197. }
  198. DeleteHeader(db, block.Hash())
  199. // Store a body and check that it's not recognized as a block
  200. if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  201. t.Fatalf("Failed to write body into database: %v", err)
  202. }
  203. if entry := GetBlock(db, block.Hash()); entry != nil {
  204. t.Fatalf("Non existent block returned: %v", entry)
  205. }
  206. DeleteBody(db, block.Hash())
  207. // Store a header and a body separately and check reassembly
  208. if err := WriteHeader(db, block.Header()); err != nil {
  209. t.Fatalf("Failed to write header into database: %v", err)
  210. }
  211. if err := WriteBody(db, block.Hash(), &types.Body{block.Transactions(), block.Uncles()}); err != nil {
  212. t.Fatalf("Failed to write body into database: %v", err)
  213. }
  214. if entry := GetBlock(db, block.Hash()); entry == nil {
  215. t.Fatalf("Stored block not found")
  216. } else if entry.Hash() != block.Hash() {
  217. t.Fatalf("Retrieved block mismatch: have %v, want %v", entry, block)
  218. }
  219. }
  220. // Tests block total difficulty storage and retrieval operations.
  221. func TestTdStorage(t *testing.T) {
  222. db, _ := ethdb.NewMemDatabase()
  223. // Create a test TD to move around the database and make sure it's really new
  224. hash, td := common.Hash{}, big.NewInt(314)
  225. if entry := GetTd(db, hash); entry != nil {
  226. t.Fatalf("Non existent TD returned: %v", entry)
  227. }
  228. // Write and verify the TD in the database
  229. if err := WriteTd(db, hash, td); err != nil {
  230. t.Fatalf("Failed to write TD into database: %v", err)
  231. }
  232. if entry := GetTd(db, hash); entry == nil {
  233. t.Fatalf("Stored TD not found")
  234. } else if entry.Cmp(td) != 0 {
  235. t.Fatalf("Retrieved TD mismatch: have %v, want %v", entry, td)
  236. }
  237. // Delete the TD and verify the execution
  238. DeleteTd(db, hash)
  239. if entry := GetTd(db, hash); entry != nil {
  240. t.Fatalf("Deleted TD returned: %v", entry)
  241. }
  242. }
  243. // Tests that canonical numbers can be mapped to hashes and retrieved.
  244. func TestCanonicalMappingStorage(t *testing.T) {
  245. db, _ := ethdb.NewMemDatabase()
  246. // Create a test canonical number and assinged hash to move around
  247. hash, number := common.Hash{0: 0xff}, uint64(314)
  248. if entry := GetCanonicalHash(db, number); entry != (common.Hash{}) {
  249. t.Fatalf("Non existent canonical mapping returned: %v", entry)
  250. }
  251. // Write and verify the TD in the database
  252. if err := WriteCanonicalHash(db, hash, number); err != nil {
  253. t.Fatalf("Failed to write canonical mapping into database: %v", err)
  254. }
  255. if entry := GetCanonicalHash(db, number); entry == (common.Hash{}) {
  256. t.Fatalf("Stored canonical mapping not found")
  257. } else if entry != hash {
  258. t.Fatalf("Retrieved canonical mapping mismatch: have %v, want %v", entry, hash)
  259. }
  260. // Delete the TD and verify the execution
  261. DeleteCanonicalHash(db, number)
  262. if entry := GetCanonicalHash(db, number); entry != (common.Hash{}) {
  263. t.Fatalf("Deleted canonical mapping returned: %v", entry)
  264. }
  265. }
  266. // Tests that head headers and head blocks can be assigned, individually.
  267. func TestHeadStorage(t *testing.T) {
  268. db, _ := ethdb.NewMemDatabase()
  269. blockHead := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block header")})
  270. blockFull := types.NewBlockWithHeader(&types.Header{Extra: []byte("test block full")})
  271. // Check that no head entries are in a pristine database
  272. if entry := GetHeadHeaderHash(db); entry != (common.Hash{}) {
  273. t.Fatalf("Non head header entry returned: %v", entry)
  274. }
  275. if entry := GetHeadBlockHash(db); entry != (common.Hash{}) {
  276. t.Fatalf("Non head block entry returned: %v", entry)
  277. }
  278. // Assign separate entries for the head header and block
  279. if err := WriteHeadHeaderHash(db, blockHead.Hash()); err != nil {
  280. t.Fatalf("Failed to write head header hash: %v", err)
  281. }
  282. if err := WriteHeadBlockHash(db, blockFull.Hash()); err != nil {
  283. t.Fatalf("Failed to write head block hash: %v", err)
  284. }
  285. // Check that both heads are present, and different (i.e. two heads maintained)
  286. if entry := GetHeadHeaderHash(db); entry != blockHead.Hash() {
  287. t.Fatalf("Head header hash mismatch: have %v, want %v", entry, blockHead.Hash())
  288. }
  289. if entry := GetHeadBlockHash(db); entry != blockFull.Hash() {
  290. t.Fatalf("Head block hash mismatch: have %v, want %v", entry, blockFull.Hash())
  291. }
  292. }
  293. func TestMipmapBloom(t *testing.T) {
  294. db, _ := ethdb.NewMemDatabase()
  295. receipt1 := new(types.Receipt)
  296. receipt1.SetLogs(vm.Logs{
  297. &vm.Log{Address: common.BytesToAddress([]byte("test"))},
  298. &vm.Log{Address: common.BytesToAddress([]byte("address"))},
  299. })
  300. receipt2 := new(types.Receipt)
  301. receipt2.SetLogs(vm.Logs{
  302. &vm.Log{Address: common.BytesToAddress([]byte("test"))},
  303. &vm.Log{Address: common.BytesToAddress([]byte("address1"))},
  304. })
  305. WriteMipmapBloom(db, 1, types.Receipts{receipt1})
  306. WriteMipmapBloom(db, 2, types.Receipts{receipt2})
  307. for _, level := range MIPMapLevels {
  308. bloom := GetMipmapBloom(db, 2, level)
  309. if !bloom.Test(new(big.Int).SetBytes([]byte("address1"))) {
  310. t.Error("expected test to be included on level:", level)
  311. }
  312. }
  313. // reset
  314. db, _ = ethdb.NewMemDatabase()
  315. receipt := new(types.Receipt)
  316. receipt.SetLogs(vm.Logs{
  317. &vm.Log{Address: common.BytesToAddress([]byte("test"))},
  318. })
  319. WriteMipmapBloom(db, 999, types.Receipts{receipt1})
  320. receipt = new(types.Receipt)
  321. receipt.SetLogs(vm.Logs{
  322. &vm.Log{Address: common.BytesToAddress([]byte("test 1"))},
  323. })
  324. WriteMipmapBloom(db, 1000, types.Receipts{receipt})
  325. bloom := GetMipmapBloom(db, 1000, 1000)
  326. if bloom.TestBytes([]byte("test")) {
  327. t.Error("test should not have been included")
  328. }
  329. }
  330. func TestMipmapChain(t *testing.T) {
  331. dir, err := ioutil.TempDir("", "mipmap")
  332. if err != nil {
  333. t.Fatal(err)
  334. }
  335. defer os.RemoveAll(dir)
  336. var (
  337. db, _ = ethdb.NewLDBDatabase(dir, 16)
  338. key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  339. addr = crypto.PubkeyToAddress(key1.PublicKey)
  340. addr2 = common.BytesToAddress([]byte("jeff"))
  341. hash1 = common.BytesToHash([]byte("topic1"))
  342. )
  343. defer db.Close()
  344. genesis := WriteGenesisBlockForTesting(db, GenesisAccount{addr, big.NewInt(1000000)})
  345. chain := GenerateChain(genesis, db, 1010, func(i int, gen *BlockGen) {
  346. var receipts types.Receipts
  347. switch i {
  348. case 1:
  349. receipt := types.NewReceipt(nil, new(big.Int))
  350. receipt.SetLogs(vm.Logs{
  351. &vm.Log{
  352. Address: addr,
  353. Topics: []common.Hash{hash1},
  354. },
  355. })
  356. gen.AddUncheckedReceipt(receipt)
  357. receipts = types.Receipts{receipt}
  358. case 1000:
  359. receipt := types.NewReceipt(nil, new(big.Int))
  360. receipt.SetLogs(vm.Logs{&vm.Log{Address: addr2}})
  361. gen.AddUncheckedReceipt(receipt)
  362. receipts = types.Receipts{receipt}
  363. }
  364. // store the receipts
  365. err := PutReceipts(db, receipts)
  366. if err != nil {
  367. t.Fatal(err)
  368. }
  369. WriteMipmapBloom(db, uint64(i+1), receipts)
  370. })
  371. for _, block := range chain {
  372. WriteBlock(db, block)
  373. if err := WriteCanonicalHash(db, block.Hash(), block.NumberU64()); err != nil {
  374. t.Fatalf("failed to insert block number: %v", err)
  375. }
  376. if err := WriteHeadBlockHash(db, block.Hash()); err != nil {
  377. t.Fatalf("failed to insert block number: %v", err)
  378. }
  379. if err := PutBlockReceipts(db, block, block.Receipts()); err != nil {
  380. t.Fatal("error writing block receipts:", err)
  381. }
  382. }
  383. bloom := GetMipmapBloom(db, 0, 1000)
  384. if bloom.TestBytes(addr2[:]) {
  385. t.Error("address was included in bloom and should not have")
  386. }
  387. }