database.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 trie
  17. import (
  18. "sync"
  19. "time"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/metrics"
  24. )
  25. var (
  26. memcacheFlushTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/flush/time", nil)
  27. memcacheFlushNodesMeter = metrics.NewRegisteredMeter("trie/memcache/flush/nodes", nil)
  28. memcacheFlushSizeMeter = metrics.NewRegisteredMeter("trie/memcache/flush/size", nil)
  29. memcacheGCTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/gc/time", nil)
  30. memcacheGCNodesMeter = metrics.NewRegisteredMeter("trie/memcache/gc/nodes", nil)
  31. memcacheGCSizeMeter = metrics.NewRegisteredMeter("trie/memcache/gc/size", nil)
  32. memcacheCommitTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/commit/time", nil)
  33. memcacheCommitNodesMeter = metrics.NewRegisteredMeter("trie/memcache/commit/nodes", nil)
  34. memcacheCommitSizeMeter = metrics.NewRegisteredMeter("trie/memcache/commit/size", nil)
  35. )
  36. // secureKeyPrefix is the database key prefix used to store trie node preimages.
  37. var secureKeyPrefix = []byte("secure-key-")
  38. // secureKeyLength is the length of the above prefix + 32byte hash.
  39. const secureKeyLength = 11 + 32
  40. // DatabaseReader wraps the Get and Has method of a backing store for the trie.
  41. type DatabaseReader interface {
  42. // Get retrieves the value associated with key form the database.
  43. Get(key []byte) (value []byte, err error)
  44. // Has retrieves whether a key is present in the database.
  45. Has(key []byte) (bool, error)
  46. }
  47. // Database is an intermediate write layer between the trie data structures and
  48. // the disk database. The aim is to accumulate trie writes in-memory and only
  49. // periodically flush a couple tries to disk, garbage collecting the remainder.
  50. type Database struct {
  51. diskdb ethdb.Database // Persistent storage for matured trie nodes
  52. nodes map[common.Hash]*cachedNode // Data and references relationships of a node
  53. oldest common.Hash // Oldest tracked node, flush-list head
  54. newest common.Hash // Newest tracked node, flush-list tail
  55. preimages map[common.Hash][]byte // Preimages of nodes from the secure trie
  56. seckeybuf [secureKeyLength]byte // Ephemeral buffer for calculating preimage keys
  57. gctime time.Duration // Time spent on garbage collection since last commit
  58. gcnodes uint64 // Nodes garbage collected since last commit
  59. gcsize common.StorageSize // Data storage garbage collected since last commit
  60. flushtime time.Duration // Time spent on data flushing since last commit
  61. flushnodes uint64 // Nodes flushed since last commit
  62. flushsize common.StorageSize // Data storage flushed since last commit
  63. nodesSize common.StorageSize // Storage size of the nodes cache (exc. flushlist)
  64. preimagesSize common.StorageSize // Storage size of the preimages cache
  65. lock sync.RWMutex
  66. }
  67. // cachedNode is all the information we know about a single cached node in the
  68. // memory database write layer.
  69. type cachedNode struct {
  70. blob []byte // Cached data block of the trie node
  71. parents int // Number of live nodes referencing this one
  72. children map[common.Hash]int // Children referenced by this nodes
  73. flushPrev common.Hash // Previous node in the flush-list
  74. flushNext common.Hash // Next node in the flush-list
  75. }
  76. // NewDatabase creates a new trie database to store ephemeral trie content before
  77. // its written out to disk or garbage collected.
  78. func NewDatabase(diskdb ethdb.Database) *Database {
  79. return &Database{
  80. diskdb: diskdb,
  81. nodes: map[common.Hash]*cachedNode{
  82. {}: {children: make(map[common.Hash]int)},
  83. },
  84. preimages: make(map[common.Hash][]byte),
  85. }
  86. }
  87. // DiskDB retrieves the persistent storage backing the trie database.
  88. func (db *Database) DiskDB() DatabaseReader {
  89. return db.diskdb
  90. }
  91. // Insert writes a new trie node to the memory database if it's yet unknown. The
  92. // method will make a copy of the slice.
  93. func (db *Database) Insert(hash common.Hash, blob []byte) {
  94. db.lock.Lock()
  95. defer db.lock.Unlock()
  96. db.insert(hash, blob)
  97. }
  98. // insert is the private locked version of Insert.
  99. func (db *Database) insert(hash common.Hash, blob []byte) {
  100. // If the node's already cached, skip
  101. if _, ok := db.nodes[hash]; ok {
  102. return
  103. }
  104. db.nodes[hash] = &cachedNode{
  105. blob: common.CopyBytes(blob),
  106. children: make(map[common.Hash]int),
  107. flushPrev: db.newest,
  108. }
  109. // Update the flush-list endpoints
  110. if db.oldest == (common.Hash{}) {
  111. db.oldest, db.newest = hash, hash
  112. } else {
  113. db.nodes[db.newest].flushNext, db.newest = hash, hash
  114. }
  115. db.nodesSize += common.StorageSize(common.HashLength + len(blob))
  116. }
  117. // insertPreimage writes a new trie node pre-image to the memory database if it's
  118. // yet unknown. The method will make a copy of the slice.
  119. //
  120. // Note, this method assumes that the database's lock is held!
  121. func (db *Database) insertPreimage(hash common.Hash, preimage []byte) {
  122. if _, ok := db.preimages[hash]; ok {
  123. return
  124. }
  125. db.preimages[hash] = common.CopyBytes(preimage)
  126. db.preimagesSize += common.StorageSize(common.HashLength + len(preimage))
  127. }
  128. // Node retrieves a cached trie node from memory. If it cannot be found cached,
  129. // the method queries the persistent database for the content.
  130. func (db *Database) Node(hash common.Hash) ([]byte, error) {
  131. // Retrieve the node from cache if available
  132. db.lock.RLock()
  133. node := db.nodes[hash]
  134. db.lock.RUnlock()
  135. if node != nil {
  136. return node.blob, nil
  137. }
  138. // Content unavailable in memory, attempt to retrieve from disk
  139. return db.diskdb.Get(hash[:])
  140. }
  141. // preimage retrieves a cached trie node pre-image from memory. If it cannot be
  142. // found cached, the method queries the persistent database for the content.
  143. func (db *Database) preimage(hash common.Hash) ([]byte, error) {
  144. // Retrieve the node from cache if available
  145. db.lock.RLock()
  146. preimage := db.preimages[hash]
  147. db.lock.RUnlock()
  148. if preimage != nil {
  149. return preimage, nil
  150. }
  151. // Content unavailable in memory, attempt to retrieve from disk
  152. return db.diskdb.Get(db.secureKey(hash[:]))
  153. }
  154. // secureKey returns the database key for the preimage of key, as an ephemeral
  155. // buffer. The caller must not hold onto the return value because it will become
  156. // invalid on the next call.
  157. func (db *Database) secureKey(key []byte) []byte {
  158. buf := append(db.seckeybuf[:0], secureKeyPrefix...)
  159. buf = append(buf, key...)
  160. return buf
  161. }
  162. // Nodes retrieves the hashes of all the nodes cached within the memory database.
  163. // This method is extremely expensive and should only be used to validate internal
  164. // states in test code.
  165. func (db *Database) Nodes() []common.Hash {
  166. db.lock.RLock()
  167. defer db.lock.RUnlock()
  168. var hashes = make([]common.Hash, 0, len(db.nodes))
  169. for hash := range db.nodes {
  170. if hash != (common.Hash{}) { // Special case for "root" references/nodes
  171. hashes = append(hashes, hash)
  172. }
  173. }
  174. return hashes
  175. }
  176. // Reference adds a new reference from a parent node to a child node.
  177. func (db *Database) Reference(child common.Hash, parent common.Hash) {
  178. db.lock.RLock()
  179. defer db.lock.RUnlock()
  180. db.reference(child, parent)
  181. }
  182. // reference is the private locked version of Reference.
  183. func (db *Database) reference(child common.Hash, parent common.Hash) {
  184. // If the node does not exist, it's a node pulled from disk, skip
  185. node, ok := db.nodes[child]
  186. if !ok {
  187. return
  188. }
  189. // If the reference already exists, only duplicate for roots
  190. if _, ok = db.nodes[parent].children[child]; ok && parent != (common.Hash{}) {
  191. return
  192. }
  193. node.parents++
  194. db.nodes[parent].children[child]++
  195. }
  196. // Dereference removes an existing reference from a parent node to a child node.
  197. func (db *Database) Dereference(child common.Hash, parent common.Hash) {
  198. db.lock.Lock()
  199. defer db.lock.Unlock()
  200. nodes, storage, start := len(db.nodes), db.nodesSize, time.Now()
  201. db.dereference(child, parent)
  202. db.gcnodes += uint64(nodes - len(db.nodes))
  203. db.gcsize += storage - db.nodesSize
  204. db.gctime += time.Since(start)
  205. memcacheGCTimeTimer.Update(time.Since(start))
  206. memcacheGCSizeMeter.Mark(int64(storage - db.nodesSize))
  207. memcacheGCNodesMeter.Mark(int64(nodes - len(db.nodes)))
  208. log.Debug("Dereferenced trie from memory database", "nodes", nodes-len(db.nodes), "size", storage-db.nodesSize, "time", time.Since(start),
  209. "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.nodes), "livesize", db.nodesSize)
  210. }
  211. // dereference is the private locked version of Dereference.
  212. func (db *Database) dereference(child common.Hash, parent common.Hash) {
  213. // Dereference the parent-child
  214. node := db.nodes[parent]
  215. node.children[child]--
  216. if node.children[child] == 0 {
  217. delete(node.children, child)
  218. }
  219. // If the child does not exist, it's a previously committed node.
  220. node, ok := db.nodes[child]
  221. if !ok {
  222. return
  223. }
  224. // If there are no more references to the child, delete it and cascade
  225. node.parents--
  226. if node.parents == 0 {
  227. // Remove the node from the flush-list
  228. if child == db.oldest {
  229. db.oldest = node.flushNext
  230. } else {
  231. db.nodes[node.flushPrev].flushNext = node.flushNext
  232. db.nodes[node.flushNext].flushPrev = node.flushPrev
  233. }
  234. // Dereference all children and delete the node
  235. for hash := range node.children {
  236. db.dereference(hash, child)
  237. }
  238. delete(db.nodes, child)
  239. db.nodesSize -= common.StorageSize(common.HashLength + len(node.blob))
  240. }
  241. }
  242. // Cap iteratively flushes old but still referenced trie nodes until the total
  243. // memory usage goes below the given threshold.
  244. func (db *Database) Cap(limit common.StorageSize) error {
  245. // Create a database batch to flush persistent data out. It is important that
  246. // outside code doesn't see an inconsistent state (referenced data removed from
  247. // memory cache during commit but not yet in persistent storage). This is ensured
  248. // by only uncaching existing data when the database write finalizes.
  249. db.lock.RLock()
  250. nodes, storage, start := len(db.nodes), db.nodesSize, time.Now()
  251. batch := db.diskdb.NewBatch()
  252. // db.nodesSize only contains the useful data in the cache, but when reporting
  253. // the total memory consumption, the maintenance metadata is also needed to be
  254. // counted. For every useful node, we track 2 extra hashes as the flushlist.
  255. size := db.nodesSize + common.StorageSize(len(db.nodes)*2*common.HashLength)
  256. // If the preimage cache got large enough, push to disk. If it's still small
  257. // leave for later to deduplicate writes.
  258. flushPreimages := db.preimagesSize > 4*1024*1024
  259. if flushPreimages {
  260. for hash, preimage := range db.preimages {
  261. if err := batch.Put(db.secureKey(hash[:]), preimage); err != nil {
  262. log.Error("Failed to commit preimage from trie database", "err", err)
  263. db.lock.RUnlock()
  264. return err
  265. }
  266. if batch.ValueSize() > ethdb.IdealBatchSize {
  267. if err := batch.Write(); err != nil {
  268. db.lock.RUnlock()
  269. return err
  270. }
  271. batch.Reset()
  272. }
  273. }
  274. }
  275. // Keep committing nodes from the flush-list until we're below allowance
  276. oldest := db.oldest
  277. for size > limit && oldest != (common.Hash{}) {
  278. // Fetch the oldest referenced node and push into the batch
  279. node := db.nodes[oldest]
  280. if err := batch.Put(oldest[:], node.blob); err != nil {
  281. db.lock.RUnlock()
  282. return err
  283. }
  284. // If we exceeded the ideal batch size, commit and reset
  285. if batch.ValueSize() >= ethdb.IdealBatchSize {
  286. if err := batch.Write(); err != nil {
  287. log.Error("Failed to write flush list to disk", "err", err)
  288. db.lock.RUnlock()
  289. return err
  290. }
  291. batch.Reset()
  292. }
  293. // Iterate to the next flush item, or abort if the size cap was achieved. Size
  294. // is the total size, including both the useful cached data (hash -> blob), as
  295. // well as the flushlist metadata (2*hash). When flushing items from the cache,
  296. // we need to reduce both.
  297. size -= common.StorageSize(3*common.HashLength + len(node.blob))
  298. oldest = node.flushNext
  299. }
  300. // Flush out any remainder data from the last batch
  301. if err := batch.Write(); err != nil {
  302. log.Error("Failed to write flush list to disk", "err", err)
  303. db.lock.RUnlock()
  304. return err
  305. }
  306. db.lock.RUnlock()
  307. // Write successful, clear out the flushed data
  308. db.lock.Lock()
  309. defer db.lock.Unlock()
  310. if flushPreimages {
  311. db.preimages = make(map[common.Hash][]byte)
  312. db.preimagesSize = 0
  313. }
  314. for db.oldest != oldest {
  315. node := db.nodes[db.oldest]
  316. delete(db.nodes, db.oldest)
  317. db.oldest = node.flushNext
  318. db.nodesSize -= common.StorageSize(common.HashLength + len(node.blob))
  319. }
  320. if db.oldest != (common.Hash{}) {
  321. db.nodes[db.oldest].flushPrev = common.Hash{}
  322. }
  323. db.flushnodes += uint64(nodes - len(db.nodes))
  324. db.flushsize += storage - db.nodesSize
  325. db.flushtime += time.Since(start)
  326. memcacheFlushTimeTimer.Update(time.Since(start))
  327. memcacheFlushSizeMeter.Mark(int64(storage - db.nodesSize))
  328. memcacheFlushNodesMeter.Mark(int64(nodes - len(db.nodes)))
  329. log.Debug("Persisted nodes from memory database", "nodes", nodes-len(db.nodes), "size", storage-db.nodesSize, "time", time.Since(start),
  330. "flushnodes", db.flushnodes, "flushsize", db.flushsize, "flushtime", db.flushtime, "livenodes", len(db.nodes), "livesize", db.nodesSize)
  331. return nil
  332. }
  333. // Commit iterates over all the children of a particular node, writes them out
  334. // to disk, forcefully tearing down all references in both directions.
  335. //
  336. // As a side effect, all pre-images accumulated up to this point are also written.
  337. func (db *Database) Commit(node common.Hash, report bool) error {
  338. // Create a database batch to flush persistent data out. It is important that
  339. // outside code doesn't see an inconsistent state (referenced data removed from
  340. // memory cache during commit but not yet in persistent storage). This is ensured
  341. // by only uncaching existing data when the database write finalizes.
  342. db.lock.RLock()
  343. start := time.Now()
  344. batch := db.diskdb.NewBatch()
  345. // Move all of the accumulated preimages into a write batch
  346. for hash, preimage := range db.preimages {
  347. if err := batch.Put(db.secureKey(hash[:]), preimage); err != nil {
  348. log.Error("Failed to commit preimage from trie database", "err", err)
  349. db.lock.RUnlock()
  350. return err
  351. }
  352. if batch.ValueSize() > ethdb.IdealBatchSize {
  353. if err := batch.Write(); err != nil {
  354. return err
  355. }
  356. batch.Reset()
  357. }
  358. }
  359. // Move the trie itself into the batch, flushing if enough data is accumulated
  360. nodes, storage := len(db.nodes), db.nodesSize
  361. if err := db.commit(node, batch); err != nil {
  362. log.Error("Failed to commit trie from trie database", "err", err)
  363. db.lock.RUnlock()
  364. return err
  365. }
  366. // Write batch ready, unlock for readers during persistence
  367. if err := batch.Write(); err != nil {
  368. log.Error("Failed to write trie to disk", "err", err)
  369. db.lock.RUnlock()
  370. return err
  371. }
  372. db.lock.RUnlock()
  373. // Write successful, clear out the flushed data
  374. db.lock.Lock()
  375. defer db.lock.Unlock()
  376. db.preimages = make(map[common.Hash][]byte)
  377. db.preimagesSize = 0
  378. db.uncache(node)
  379. memcacheCommitTimeTimer.Update(time.Since(start))
  380. memcacheCommitSizeMeter.Mark(int64(storage - db.nodesSize))
  381. memcacheCommitNodesMeter.Mark(int64(nodes - len(db.nodes)))
  382. logger := log.Info
  383. if !report {
  384. logger = log.Debug
  385. }
  386. logger("Persisted trie from memory database", "nodes", nodes-len(db.nodes)+int(db.flushnodes), "size", storage-db.nodesSize+db.flushsize, "time", time.Since(start)+db.flushtime,
  387. "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.nodes), "livesize", db.nodesSize)
  388. // Reset the garbage collection statistics
  389. db.gcnodes, db.gcsize, db.gctime = 0, 0, 0
  390. db.flushnodes, db.flushsize, db.flushtime = 0, 0, 0
  391. return nil
  392. }
  393. // commit is the private locked version of Commit.
  394. func (db *Database) commit(hash common.Hash, batch ethdb.Batch) error {
  395. // If the node does not exist, it's a previously committed node
  396. node, ok := db.nodes[hash]
  397. if !ok {
  398. return nil
  399. }
  400. for child := range node.children {
  401. if err := db.commit(child, batch); err != nil {
  402. return err
  403. }
  404. }
  405. if err := batch.Put(hash[:], node.blob); err != nil {
  406. return err
  407. }
  408. // If we've reached an optimal batch size, commit and start over
  409. if batch.ValueSize() >= ethdb.IdealBatchSize {
  410. if err := batch.Write(); err != nil {
  411. return err
  412. }
  413. batch.Reset()
  414. }
  415. return nil
  416. }
  417. // uncache is the post-processing step of a commit operation where the already
  418. // persisted trie is removed from the cache. The reason behind the two-phase
  419. // commit is to ensure consistent data availability while moving from memory
  420. // to disk.
  421. func (db *Database) uncache(hash common.Hash) {
  422. // If the node does not exist, we're done on this path
  423. node, ok := db.nodes[hash]
  424. if !ok {
  425. return
  426. }
  427. // Node still exists, remove it from the flush-list
  428. if hash == db.oldest {
  429. db.oldest = node.flushNext
  430. } else {
  431. db.nodes[node.flushPrev].flushNext = node.flushNext
  432. db.nodes[node.flushNext].flushPrev = node.flushPrev
  433. }
  434. // Uncache the node's subtries and remove the node itself too
  435. for child := range node.children {
  436. db.uncache(child)
  437. }
  438. delete(db.nodes, hash)
  439. db.nodesSize -= common.StorageSize(common.HashLength + len(node.blob))
  440. }
  441. // Size returns the current storage size of the memory cache in front of the
  442. // persistent database layer.
  443. func (db *Database) Size() (common.StorageSize, common.StorageSize) {
  444. db.lock.RLock()
  445. defer db.lock.RUnlock()
  446. // db.nodesSize only contains the useful data in the cache, but when reporting
  447. // the total memory consumption, the maintenance metadata is also needed to be
  448. // counted. For every useful node, we track 2 extra hashes as the flushlist.
  449. var flushlistSize = common.StorageSize(len(db.nodes) * 2 * common.HashLength)
  450. return db.nodesSize + flushlistSize, db.preimagesSize
  451. }