database.go 14 KB

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