database.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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.KeyValueStore.Close(); err != nil {
  40. errs = append(errs, err)
  41. }
  42. if err := frdb.AncientStore.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. if frgenesis, _ := frdb.Ancient(freezerHashTable, 0); !bytes.Equal(kvgenesis, frgenesis) {
  125. return nil, fmt.Errorf("genesis mismatch: %#x (leveldb) != %#x (ancients)", kvgenesis, frgenesis)
  126. }
  127. // Key-value store and freezer belong to the same network. Ensure that they
  128. // are contiguous, otherwise we might end up with a non-functional freezer.
  129. if kvhash, _ := db.Get(headerHashKey(frozen)); len(kvhash) == 0 {
  130. // Subsequent header after the freezer limit is missing from the database.
  131. // Reject startup is the database has a more recent head.
  132. if *ReadHeaderNumber(db, ReadHeadHeaderHash(db)) > frozen-1 {
  133. return nil, fmt.Errorf("gap (#%d) in the chain between ancients and leveldb", frozen)
  134. }
  135. // Database contains only older data than the freezer, this happens if the
  136. // state was wiped and reinited from an existing freezer.
  137. }
  138. // Otherwise, key-value store continues where the freezer left off, all is fine.
  139. // We might have duplicate blocks (crash after freezer write but before key-value
  140. // store deletion, but that's fine).
  141. } else {
  142. // If the freezer is empty, ensure nothing was moved yet from the key-value
  143. // store, otherwise we'll end up missing data. We check block #1 to decide
  144. // if we froze anything previously or not, but do take care of databases with
  145. // only the genesis block.
  146. if ReadHeadHeaderHash(db) != common.BytesToHash(kvgenesis) {
  147. // Key-value store contains more data than the genesis block, make sure we
  148. // didn't freeze anything yet.
  149. if kvblob, _ := db.Get(headerHashKey(1)); len(kvblob) == 0 {
  150. return nil, errors.New("ancient chain segments already extracted, please set --datadir.ancient to the correct path")
  151. }
  152. // Block #1 is still in the database, we're allowed to init a new feezer
  153. }
  154. // Otherwise, the head header is still the genesis, we're allowed to init a new
  155. // feezer.
  156. }
  157. }
  158. // Freezer is consistent with the key-value database, permit combining the two
  159. go frdb.freeze(db)
  160. return &freezerdb{
  161. KeyValueStore: db,
  162. AncientStore: frdb,
  163. }, nil
  164. }
  165. // NewMemoryDatabase creates an ephemeral in-memory key-value database without a
  166. // freezer moving immutable chain segments into cold storage.
  167. func NewMemoryDatabase() ethdb.Database {
  168. return NewDatabase(memorydb.New())
  169. }
  170. // NewMemoryDatabaseWithCap creates an ephemeral in-memory key-value database
  171. // with an initial starting capacity, but without a freezer moving immutable
  172. // chain segments into cold storage.
  173. func NewMemoryDatabaseWithCap(size int) ethdb.Database {
  174. return NewDatabase(memorydb.NewWithCap(size))
  175. }
  176. // NewLevelDBDatabase creates a persistent key-value database without a freezer
  177. // moving immutable chain segments into cold storage.
  178. func NewLevelDBDatabase(file string, cache int, handles int, namespace string) (ethdb.Database, error) {
  179. db, err := leveldb.New(file, cache, handles, namespace)
  180. if err != nil {
  181. return nil, err
  182. }
  183. return NewDatabase(db), nil
  184. }
  185. // NewLevelDBDatabaseWithFreezer creates a persistent key-value database with a
  186. // freezer moving immutable chain segments into cold storage.
  187. func NewLevelDBDatabaseWithFreezer(file string, cache int, handles int, freezer string, namespace string) (ethdb.Database, error) {
  188. kvdb, err := leveldb.New(file, cache, handles, namespace)
  189. if err != nil {
  190. return nil, err
  191. }
  192. frdb, err := NewDatabaseWithFreezer(kvdb, freezer, namespace)
  193. if err != nil {
  194. kvdb.Close()
  195. return nil, err
  196. }
  197. return frdb, nil
  198. }
  199. // InspectDatabase traverses the entire database and checks the size
  200. // of all different categories of data.
  201. func InspectDatabase(db ethdb.Database) error {
  202. it := db.NewIterator()
  203. defer it.Release()
  204. var (
  205. count int64
  206. start = time.Now()
  207. logged = time.Now()
  208. // Key-value store statistics
  209. total common.StorageSize
  210. headerSize common.StorageSize
  211. bodySize common.StorageSize
  212. receiptSize common.StorageSize
  213. tdSize common.StorageSize
  214. numHashPairing common.StorageSize
  215. hashNumPairing common.StorageSize
  216. trieSize common.StorageSize
  217. txlookupSize common.StorageSize
  218. accountSnapSize common.StorageSize
  219. storageSnapSize common.StorageSize
  220. preimageSize common.StorageSize
  221. bloomBitsSize common.StorageSize
  222. cliqueSnapsSize common.StorageSize
  223. // Ancient store statistics
  224. ancientHeaders common.StorageSize
  225. ancientBodies common.StorageSize
  226. ancientReceipts common.StorageSize
  227. ancientHashes common.StorageSize
  228. ancientTds common.StorageSize
  229. // Les statistic
  230. chtTrieNodes common.StorageSize
  231. bloomTrieNodes common.StorageSize
  232. // Meta- and unaccounted data
  233. metadata common.StorageSize
  234. unaccounted common.StorageSize
  235. )
  236. // Inspect key-value database first.
  237. for it.Next() {
  238. var (
  239. key = it.Key()
  240. size = common.StorageSize(len(key) + len(it.Value()))
  241. )
  242. total += size
  243. switch {
  244. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerTDSuffix):
  245. tdSize += size
  246. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerHashSuffix):
  247. numHashPairing += size
  248. case bytes.HasPrefix(key, headerPrefix) && len(key) == (len(headerPrefix)+8+common.HashLength):
  249. headerSize += size
  250. case bytes.HasPrefix(key, headerNumberPrefix) && len(key) == (len(headerNumberPrefix)+common.HashLength):
  251. hashNumPairing += size
  252. case bytes.HasPrefix(key, blockBodyPrefix) && len(key) == (len(blockBodyPrefix)+8+common.HashLength):
  253. bodySize += size
  254. case bytes.HasPrefix(key, blockReceiptsPrefix) && len(key) == (len(blockReceiptsPrefix)+8+common.HashLength):
  255. receiptSize += size
  256. case bytes.HasPrefix(key, txLookupPrefix) && len(key) == (len(txLookupPrefix)+common.HashLength):
  257. txlookupSize += size
  258. case bytes.HasPrefix(key, SnapshotAccountPrefix) && len(key) == (len(SnapshotAccountPrefix)+common.HashLength):
  259. accountSnapSize += size
  260. case bytes.HasPrefix(key, SnapshotStoragePrefix) && len(key) == (len(SnapshotStoragePrefix)+2*common.HashLength):
  261. storageSnapSize += size
  262. case bytes.HasPrefix(key, preimagePrefix) && len(key) == (len(preimagePrefix)+common.HashLength):
  263. preimageSize += size
  264. case bytes.HasPrefix(key, bloomBitsPrefix) && len(key) == (len(bloomBitsPrefix)+10+common.HashLength):
  265. bloomBitsSize += size
  266. case bytes.HasPrefix(key, []byte("clique-")) && len(key) == 7+common.HashLength:
  267. cliqueSnapsSize += size
  268. case bytes.HasPrefix(key, []byte("cht-")) && len(key) == 4+common.HashLength:
  269. chtTrieNodes += size
  270. case bytes.HasPrefix(key, []byte("blt-")) && len(key) == 4+common.HashLength:
  271. bloomTrieNodes += size
  272. case len(key) == common.HashLength:
  273. trieSize += size
  274. default:
  275. var accounted bool
  276. for _, meta := range [][]byte{databaseVerisionKey, headHeaderKey, headBlockKey, headFastBlockKey, fastTrieProgressKey} {
  277. if bytes.Equal(key, meta) {
  278. metadata += size
  279. accounted = true
  280. break
  281. }
  282. }
  283. if !accounted {
  284. unaccounted += size
  285. }
  286. }
  287. count += 1
  288. if count%1000 == 0 && time.Since(logged) > 8*time.Second {
  289. log.Info("Inspecting database", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  290. logged = time.Now()
  291. }
  292. }
  293. // Inspect append-only file store then.
  294. ancients := []*common.StorageSize{&ancientHeaders, &ancientBodies, &ancientReceipts, &ancientHashes, &ancientTds}
  295. for i, category := range []string{freezerHeaderTable, freezerBodiesTable, freezerReceiptTable, freezerHashTable, freezerDifficultyTable} {
  296. if size, err := db.AncientSize(category); err == nil {
  297. *ancients[i] += common.StorageSize(size)
  298. total += common.StorageSize(size)
  299. }
  300. }
  301. // Display the database statistic.
  302. stats := [][]string{
  303. {"Key-Value store", "Headers", headerSize.String()},
  304. {"Key-Value store", "Bodies", bodySize.String()},
  305. {"Key-Value store", "Receipts", receiptSize.String()},
  306. {"Key-Value store", "Difficulties", tdSize.String()},
  307. {"Key-Value store", "Block number->hash", numHashPairing.String()},
  308. {"Key-Value store", "Block hash->number", hashNumPairing.String()},
  309. {"Key-Value store", "Transaction index", txlookupSize.String()},
  310. {"Key-Value store", "Bloombit index", bloomBitsSize.String()},
  311. {"Key-Value store", "Trie nodes", trieSize.String()},
  312. {"Key-Value store", "Trie preimages", preimageSize.String()},
  313. {"Key-Value store", "Account snapshot", accountSnapSize.String()},
  314. {"Key-Value store", "Storage snapshot", storageSnapSize.String()},
  315. {"Key-Value store", "Clique snapshots", cliqueSnapsSize.String()},
  316. {"Key-Value store", "Singleton metadata", metadata.String()},
  317. {"Ancient store", "Headers", ancientHeaders.String()},
  318. {"Ancient store", "Bodies", ancientBodies.String()},
  319. {"Ancient store", "Receipts", ancientReceipts.String()},
  320. {"Ancient store", "Difficulties", ancientTds.String()},
  321. {"Ancient store", "Block number->hash", ancientHashes.String()},
  322. {"Light client", "CHT trie nodes", chtTrieNodes.String()},
  323. {"Light client", "Bloom trie nodes", bloomTrieNodes.String()},
  324. }
  325. table := tablewriter.NewWriter(os.Stdout)
  326. table.SetHeader([]string{"Database", "Category", "Size"})
  327. table.SetFooter([]string{"", "Total", total.String()})
  328. table.AppendBulk(stats)
  329. table.Render()
  330. if unaccounted > 0 {
  331. log.Error("Database contains unaccounted data", "size", unaccounted)
  332. }
  333. return nil
  334. }