database.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. "errors"
  20. "fmt"
  21. "os"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/ethdb/leveldb"
  27. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/olekukonko/tablewriter"
  30. )
  31. // freezerdb is a database wrapper that enabled freezer data retrievals.
  32. type freezerdb struct {
  33. ethdb.KeyValueStore
  34. ethdb.AncientStore
  35. }
  36. // Close implements io.Closer, closing both the fast key-value store as well as
  37. // the slow ancient tables.
  38. func (frdb *freezerdb) Close() error {
  39. var errs []error
  40. if err := frdb.AncientStore.Close(); err != nil {
  41. errs = append(errs, err)
  42. }
  43. if err := frdb.KeyValueStore.Close(); err != nil {
  44. errs = append(errs, err)
  45. }
  46. if len(errs) != 0 {
  47. return fmt.Errorf("%v", errs)
  48. }
  49. return nil
  50. }
  51. // Freeze is a helper method used for external testing to trigger and block until
  52. // a freeze cycle completes, without having to sleep for a minute to trigger the
  53. // automatic background run.
  54. func (frdb *freezerdb) Freeze(threshold uint64) error {
  55. if frdb.AncientStore.(*freezer).readonly {
  56. return errReadOnly
  57. }
  58. // Set the freezer threshold to a temporary value
  59. defer func(old uint64) {
  60. atomic.StoreUint64(&frdb.AncientStore.(*freezer).threshold, old)
  61. }(atomic.LoadUint64(&frdb.AncientStore.(*freezer).threshold))
  62. atomic.StoreUint64(&frdb.AncientStore.(*freezer).threshold, threshold)
  63. // Trigger a freeze cycle and block until it's done
  64. trigger := make(chan struct{}, 1)
  65. frdb.AncientStore.(*freezer).trigger <- trigger
  66. <-trigger
  67. return nil
  68. }
  69. // nofreezedb is a database wrapper that disables freezer data retrievals.
  70. type nofreezedb struct {
  71. ethdb.KeyValueStore
  72. }
  73. // HasAncient returns an error as we don't have a backing chain freezer.
  74. func (db *nofreezedb) HasAncient(kind string, number uint64) (bool, error) {
  75. return false, errNotSupported
  76. }
  77. // Ancient returns an error as we don't have a backing chain freezer.
  78. func (db *nofreezedb) Ancient(kind string, number uint64) ([]byte, error) {
  79. return nil, errNotSupported
  80. }
  81. // Ancients returns an error as we don't have a backing chain freezer.
  82. func (db *nofreezedb) Ancients() (uint64, error) {
  83. return 0, errNotSupported
  84. }
  85. // AncientSize returns an error as we don't have a backing chain freezer.
  86. func (db *nofreezedb) AncientSize(kind string) (uint64, error) {
  87. return 0, errNotSupported
  88. }
  89. // AppendAncient returns an error as we don't have a backing chain freezer.
  90. func (db *nofreezedb) AppendAncient(number uint64, hash, header, body, receipts, td []byte) error {
  91. return errNotSupported
  92. }
  93. // TruncateAncients returns an error as we don't have a backing chain freezer.
  94. func (db *nofreezedb) TruncateAncients(items uint64) error {
  95. return errNotSupported
  96. }
  97. // Sync returns an error as we don't have a backing chain freezer.
  98. func (db *nofreezedb) Sync() error {
  99. return errNotSupported
  100. }
  101. // NewDatabase creates a high level database on top of a given key-value data
  102. // store without a freezer moving immutable chain segments into cold storage.
  103. func NewDatabase(db ethdb.KeyValueStore) ethdb.Database {
  104. return &nofreezedb{
  105. KeyValueStore: db,
  106. }
  107. }
  108. // NewDatabaseWithFreezer creates a high level database on top of a given key-
  109. // value data store with a freezer moving immutable chain segments into cold
  110. // storage.
  111. func NewDatabaseWithFreezer(db ethdb.KeyValueStore, freezer string, namespace string, readonly bool) (ethdb.Database, error) {
  112. // Create the idle freezer instance
  113. frdb, err := newFreezer(freezer, namespace, readonly)
  114. if err != nil {
  115. return nil, err
  116. }
  117. // Since the freezer can be stored separately from the user's key-value database,
  118. // there's a fairly high probability that the user requests invalid combinations
  119. // of the freezer and database. Ensure that we don't shoot ourselves in the foot
  120. // by serving up conflicting data, leading to both datastores getting corrupted.
  121. //
  122. // - If both the freezer and key-value store is empty (no genesis), we just
  123. // initialized a new empty freezer, so everything's fine.
  124. // - If the key-value store is empty, but the freezer is not, we need to make
  125. // sure the user's genesis matches the freezer. That will be checked in the
  126. // blockchain, since we don't have the genesis block here (nor should we at
  127. // this point care, the key-value/freezer combo is valid).
  128. // - If neither the key-value store nor the freezer is empty, cross validate
  129. // the genesis hashes to make sure they are compatible. If they are, also
  130. // ensure that there's no gap between the freezer and sunsequently leveldb.
  131. // - If the key-value store is not empty, but the freezer is we might just be
  132. // upgrading to the freezer release, or we might have had a small chain and
  133. // not frozen anything yet. Ensure that no blocks are missing yet from the
  134. // key-value store, since that would mean we already had an old freezer.
  135. // If the genesis hash is empty, we have a new key-value store, so nothing to
  136. // validate in this method. If, however, the genesis hash is not nil, compare
  137. // it to the freezer content.
  138. if kvgenesis, _ := db.Get(headerHashKey(0)); len(kvgenesis) > 0 {
  139. if frozen, _ := frdb.Ancients(); frozen > 0 {
  140. // If the freezer already contains something, ensure that the genesis blocks
  141. // match, otherwise we might mix up freezers across chains and destroy both
  142. // the freezer and the key-value store.
  143. frgenesis, err := frdb.Ancient(freezerHashTable, 0)
  144. if err != nil {
  145. return nil, fmt.Errorf("failed to retrieve genesis from ancient %v", err)
  146. } else if !bytes.Equal(kvgenesis, frgenesis) {
  147. return nil, fmt.Errorf("genesis mismatch: %#x (leveldb) != %#x (ancients)", kvgenesis, frgenesis)
  148. }
  149. // Key-value store and freezer belong to the same network. Ensure that they
  150. // are contiguous, otherwise we might end up with a non-functional freezer.
  151. if kvhash, _ := db.Get(headerHashKey(frozen)); len(kvhash) == 0 {
  152. // Subsequent header after the freezer limit is missing from the database.
  153. // Reject startup is the database has a more recent head.
  154. if *ReadHeaderNumber(db, ReadHeadHeaderHash(db)) > frozen-1 {
  155. return nil, fmt.Errorf("gap (#%d) in the chain between ancients and leveldb", frozen)
  156. }
  157. // Database contains only older data than the freezer, this happens if the
  158. // state was wiped and reinited from an existing freezer.
  159. }
  160. // Otherwise, key-value store continues where the freezer left off, all is fine.
  161. // We might have duplicate blocks (crash after freezer write but before key-value
  162. // store deletion, but that's fine).
  163. } else {
  164. // If the freezer is empty, ensure nothing was moved yet from the key-value
  165. // store, otherwise we'll end up missing data. We check block #1 to decide
  166. // if we froze anything previously or not, but do take care of databases with
  167. // only the genesis block.
  168. if ReadHeadHeaderHash(db) != common.BytesToHash(kvgenesis) {
  169. // Key-value store contains more data than the genesis block, make sure we
  170. // didn't freeze anything yet.
  171. if kvblob, _ := db.Get(headerHashKey(1)); len(kvblob) == 0 {
  172. return nil, errors.New("ancient chain segments already extracted, please set --datadir.ancient to the correct path")
  173. }
  174. // Block #1 is still in the database, we're allowed to init a new feezer
  175. }
  176. // Otherwise, the head header is still the genesis, we're allowed to init a new
  177. // feezer.
  178. }
  179. }
  180. // Freezer is consistent with the key-value database, permit combining the two
  181. if !frdb.readonly {
  182. go frdb.freeze(db)
  183. }
  184. return &freezerdb{
  185. KeyValueStore: db,
  186. AncientStore: frdb,
  187. }, nil
  188. }
  189. // NewMemoryDatabase creates an ephemeral in-memory key-value database without a
  190. // freezer moving immutable chain segments into cold storage.
  191. func NewMemoryDatabase() ethdb.Database {
  192. return NewDatabase(memorydb.New())
  193. }
  194. // NewMemoryDatabaseWithCap creates an ephemeral in-memory key-value database
  195. // with an initial starting capacity, but without a freezer moving immutable
  196. // chain segments into cold storage.
  197. func NewMemoryDatabaseWithCap(size int) ethdb.Database {
  198. return NewDatabase(memorydb.NewWithCap(size))
  199. }
  200. // NewLevelDBDatabase creates a persistent key-value database without a freezer
  201. // moving immutable chain segments into cold storage.
  202. func NewLevelDBDatabase(file string, cache int, handles int, namespace string, readonly bool) (ethdb.Database, error) {
  203. db, err := leveldb.New(file, cache, handles, namespace, readonly)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return NewDatabase(db), nil
  208. }
  209. // NewLevelDBDatabaseWithFreezer creates a persistent key-value database with a
  210. // freezer moving immutable chain segments into cold storage.
  211. func NewLevelDBDatabaseWithFreezer(file string, cache int, handles int, freezer string, namespace string, readonly bool) (ethdb.Database, error) {
  212. kvdb, err := leveldb.New(file, cache, handles, namespace, readonly)
  213. if err != nil {
  214. return nil, err
  215. }
  216. frdb, err := NewDatabaseWithFreezer(kvdb, freezer, namespace, readonly)
  217. if err != nil {
  218. kvdb.Close()
  219. return nil, err
  220. }
  221. return frdb, nil
  222. }
  223. type counter uint64
  224. func (c counter) String() string {
  225. return fmt.Sprintf("%d", c)
  226. }
  227. func (c counter) Percentage(current uint64) string {
  228. return fmt.Sprintf("%d", current*100/uint64(c))
  229. }
  230. // stat stores sizes and count for a parameter
  231. type stat struct {
  232. size common.StorageSize
  233. count counter
  234. }
  235. // Add size to the stat and increase the counter by 1
  236. func (s *stat) Add(size common.StorageSize) {
  237. s.size += size
  238. s.count++
  239. }
  240. func (s *stat) Size() string {
  241. return s.size.String()
  242. }
  243. func (s *stat) Count() string {
  244. return s.count.String()
  245. }
  246. // InspectDatabase traverses the entire database and checks the size
  247. // of all different categories of data.
  248. func InspectDatabase(db ethdb.Database, keyPrefix, keyStart []byte) error {
  249. it := db.NewIterator(keyPrefix, keyStart)
  250. defer it.Release()
  251. var (
  252. count int64
  253. start = time.Now()
  254. logged = time.Now()
  255. // Key-value store statistics
  256. headers stat
  257. bodies stat
  258. receipts stat
  259. tds stat
  260. numHashPairings stat
  261. hashNumPairings stat
  262. tries stat
  263. codes stat
  264. txLookups stat
  265. accountSnaps stat
  266. storageSnaps stat
  267. preimages stat
  268. bloomBits stat
  269. cliqueSnaps stat
  270. // Ancient store statistics
  271. ancientHeadersSize common.StorageSize
  272. ancientBodiesSize common.StorageSize
  273. ancientReceiptsSize common.StorageSize
  274. ancientTdsSize common.StorageSize
  275. ancientHashesSize common.StorageSize
  276. // Les statistic
  277. chtTrieNodes stat
  278. bloomTrieNodes stat
  279. // Meta- and unaccounted data
  280. metadata stat
  281. unaccounted stat
  282. shutdownInfo stat
  283. // Totals
  284. total common.StorageSize
  285. )
  286. // Inspect key-value database first.
  287. for it.Next() {
  288. var (
  289. key = it.Key()
  290. size = common.StorageSize(len(key) + len(it.Value()))
  291. )
  292. total += size
  293. switch {
  294. case bytes.HasPrefix(key, headerPrefix) && len(key) == (len(headerPrefix)+8+common.HashLength):
  295. headers.Add(size)
  296. case bytes.HasPrefix(key, blockBodyPrefix) && len(key) == (len(blockBodyPrefix)+8+common.HashLength):
  297. bodies.Add(size)
  298. case bytes.HasPrefix(key, blockReceiptsPrefix) && len(key) == (len(blockReceiptsPrefix)+8+common.HashLength):
  299. receipts.Add(size)
  300. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerTDSuffix):
  301. tds.Add(size)
  302. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerHashSuffix):
  303. numHashPairings.Add(size)
  304. case bytes.HasPrefix(key, headerNumberPrefix) && len(key) == (len(headerNumberPrefix)+common.HashLength):
  305. hashNumPairings.Add(size)
  306. case len(key) == common.HashLength:
  307. tries.Add(size)
  308. case bytes.HasPrefix(key, CodePrefix) && len(key) == len(CodePrefix)+common.HashLength:
  309. codes.Add(size)
  310. case bytes.HasPrefix(key, txLookupPrefix) && len(key) == (len(txLookupPrefix)+common.HashLength):
  311. txLookups.Add(size)
  312. case bytes.HasPrefix(key, SnapshotAccountPrefix) && len(key) == (len(SnapshotAccountPrefix)+common.HashLength):
  313. accountSnaps.Add(size)
  314. case bytes.HasPrefix(key, SnapshotStoragePrefix) && len(key) == (len(SnapshotStoragePrefix)+2*common.HashLength):
  315. storageSnaps.Add(size)
  316. case bytes.HasPrefix(key, preimagePrefix) && len(key) == (len(preimagePrefix)+common.HashLength):
  317. preimages.Add(size)
  318. case bytes.HasPrefix(key, bloomBitsPrefix) && len(key) == (len(bloomBitsPrefix)+10+common.HashLength):
  319. bloomBits.Add(size)
  320. case bytes.HasPrefix(key, BloomBitsIndexPrefix):
  321. bloomBits.Add(size)
  322. case bytes.HasPrefix(key, []byte("clique-")) && len(key) == 7+common.HashLength:
  323. cliqueSnaps.Add(size)
  324. case bytes.HasPrefix(key, []byte("cht-")) ||
  325. bytes.HasPrefix(key, []byte("chtIndexV2-")) ||
  326. bytes.HasPrefix(key, []byte("chtRootV2-")): // Canonical hash trie
  327. chtTrieNodes.Add(size)
  328. case bytes.HasPrefix(key, []byte("blt-")) ||
  329. bytes.HasPrefix(key, []byte("bltIndex-")) ||
  330. bytes.HasPrefix(key, []byte("bltRoot-")): // Bloomtrie sub
  331. bloomTrieNodes.Add(size)
  332. case bytes.Equal(key, uncleanShutdownKey):
  333. shutdownInfo.Add(size)
  334. default:
  335. var accounted bool
  336. for _, meta := range [][]byte{
  337. databaseVersionKey, headHeaderKey, headBlockKey, headFastBlockKey, lastPivotKey,
  338. fastTrieProgressKey, snapshotDisabledKey, snapshotRootKey, snapshotJournalKey,
  339. snapshotGeneratorKey, snapshotRecoveryKey, txIndexTailKey, fastTxLookupLimitKey,
  340. uncleanShutdownKey, badBlockKey,
  341. } {
  342. if bytes.Equal(key, meta) {
  343. metadata.Add(size)
  344. accounted = true
  345. break
  346. }
  347. }
  348. if !accounted {
  349. unaccounted.Add(size)
  350. }
  351. }
  352. count++
  353. if count%1000 == 0 && time.Since(logged) > 8*time.Second {
  354. log.Info("Inspecting database", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  355. logged = time.Now()
  356. }
  357. }
  358. // Inspect append-only file store then.
  359. ancientSizes := []*common.StorageSize{&ancientHeadersSize, &ancientBodiesSize, &ancientReceiptsSize, &ancientHashesSize, &ancientTdsSize}
  360. for i, category := range []string{freezerHeaderTable, freezerBodiesTable, freezerReceiptTable, freezerHashTable, freezerDifficultyTable} {
  361. if size, err := db.AncientSize(category); err == nil {
  362. *ancientSizes[i] += common.StorageSize(size)
  363. total += common.StorageSize(size)
  364. }
  365. }
  366. // Get number of ancient rows inside the freezer
  367. ancients := counter(0)
  368. if count, err := db.Ancients(); err == nil {
  369. ancients = counter(count)
  370. }
  371. // Display the database statistic.
  372. stats := [][]string{
  373. {"Key-Value store", "Headers", headers.Size(), headers.Count()},
  374. {"Key-Value store", "Bodies", bodies.Size(), bodies.Count()},
  375. {"Key-Value store", "Receipt lists", receipts.Size(), receipts.Count()},
  376. {"Key-Value store", "Difficulties", tds.Size(), tds.Count()},
  377. {"Key-Value store", "Block number->hash", numHashPairings.Size(), numHashPairings.Count()},
  378. {"Key-Value store", "Block hash->number", hashNumPairings.Size(), hashNumPairings.Count()},
  379. {"Key-Value store", "Transaction index", txLookups.Size(), txLookups.Count()},
  380. {"Key-Value store", "Bloombit index", bloomBits.Size(), bloomBits.Count()},
  381. {"Key-Value store", "Contract codes", codes.Size(), codes.Count()},
  382. {"Key-Value store", "Trie nodes", tries.Size(), tries.Count()},
  383. {"Key-Value store", "Trie preimages", preimages.Size(), preimages.Count()},
  384. {"Key-Value store", "Account snapshot", accountSnaps.Size(), accountSnaps.Count()},
  385. {"Key-Value store", "Storage snapshot", storageSnaps.Size(), storageSnaps.Count()},
  386. {"Key-Value store", "Clique snapshots", cliqueSnaps.Size(), cliqueSnaps.Count()},
  387. {"Key-Value store", "Singleton metadata", metadata.Size(), metadata.Count()},
  388. {"Key-Value store", "Shutdown metadata", shutdownInfo.Size(), shutdownInfo.Count()},
  389. {"Ancient store", "Headers", ancientHeadersSize.String(), ancients.String()},
  390. {"Ancient store", "Bodies", ancientBodiesSize.String(), ancients.String()},
  391. {"Ancient store", "Receipt lists", ancientReceiptsSize.String(), ancients.String()},
  392. {"Ancient store", "Difficulties", ancientTdsSize.String(), ancients.String()},
  393. {"Ancient store", "Block number->hash", ancientHashesSize.String(), ancients.String()},
  394. {"Light client", "CHT trie nodes", chtTrieNodes.Size(), chtTrieNodes.Count()},
  395. {"Light client", "Bloom trie nodes", bloomTrieNodes.Size(), bloomTrieNodes.Count()},
  396. }
  397. table := tablewriter.NewWriter(os.Stdout)
  398. table.SetHeader([]string{"Database", "Category", "Size", "Items"})
  399. table.SetFooter([]string{"", "Total", total.String(), " "})
  400. table.AppendBulk(stats)
  401. table.Render()
  402. if unaccounted.size > 0 {
  403. log.Error("Database contains unaccounted data", "size", unaccounted.size, "count", unaccounted.count)
  404. }
  405. return nil
  406. }