database.go 15 KB

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