mirror of
https://github.com/status-im/nimbus-eth1.git
synced 2025-03-03 21:30:53 +00:00
* aristo: fork support via layers/txframes This change reorganises how the database is accessed: instead holding a "current frame" in the database object, a dag of frames is created based on the "base frame" held in `AristoDbRef` and all database access happens through this frame, which can be thought of as a consistent point-in-time snapshot of the database based on a particular fork of the chain. In the code, "frame", "transaction" and "layer" is used to denote more or less the same thing: a dag of stacked changes backed by the on-disk database. Although this is not a requirement, in practice each frame holds the change set of a single block - as such, the frame and its ancestors leading up to the on-disk state represents the state of the database after that block has been applied. "committing" means merging the changes to its parent frame so that the difference between them is lost and only the cumulative changes remain - this facility enables frames to be combined arbitrarily wherever they are in the dag. In particular, it becomes possible to consolidate a set of changes near the base of the dag and commit those to disk without having to re-do the in-memory frames built on top of them - this is useful for "flattening" a set of changes during a base update and sending those to storage without having to perform a block replay on top. Looking at abstractions, a side effect of this change is that the KVT and Aristo are brought closer together by considering them to be part of the "same" atomic transaction set - the way the code gets organised, applying a block and saving it to the kvt happens in the same "logical" frame - therefore, discarding the frame discards both the aristo and kvt changes at the same time - likewise, they are persisted to disk together - this makes reasoning about the database somewhat easier but has the downside of increased memory usage, something that perhaps will need addressing in the future. Because the code reasons more strictly about frames and the state of the persisted database, it also makes it more visible where ForkedChain should be used and where it is still missing - in particular, frames represent a single branch of history while forkedchain manages multiple parallel forks - user-facing services such as the RPC should use the latter, ie until it has been finalized, a getBlock request should consider all forks and not just the blocks in the canonical head branch. Another advantage of this approach is that `AristoDbRef` conceptually becomes more simple - removing its tracking of the "current" transaction stack simplifies reasoning about what can go wrong since this state now has to be passed around in the form of `AristoTxRef` - as such, many of the tests and facilities in the code that were dealing with "stack inconsistency" are now structurally prevented from happening. The test suite will need significant refactoring after this change. Once this change has been merged, there are several follow-ups to do: * there's no mechanism for keeping frames up to date as they get committed or rolled back - TODO * naming is confused - many names for the same thing for legacy reason * forkedchain support is still missing in lots of code * clean up redundant logic based on previous designs - in particular the debug and introspection code no longer makes sense * the way change sets are stored will probably need revisiting - because it's a stack of changes where each frame must be interrogated to find an on-disk value, with a base distance of 128 we'll at minimum have to perform 128 frame lookups for *every* database interaction - regardless, the "dag-like" nature will stay * dispose and commit are poorly defined and perhaps redundant - in theory, one could simply let the GC collect abandoned frames etc, though it's likely an explicit mechanism will remain useful, so they stay for now More about the changes: * `AristoDbRef` gains a `txRef` field (todo: rename) that "more or less" corresponds to the old `balancer` field * `AristoDbRef.stack` is gone - instead, there's a chain of `AristoTxRef` objects that hold their respective "layer" which has the actual changes * No more reasoning about "top" and "stack" - instead, each `AristoTxRef` can be a "head" that "more or less" corresponds to the old single-history `top` notion and its stack * `level` still represents "distance to base" - it's computed from the parent chain instead of being stored * one has to be careful not to use frames where forkedchain was intended - layers are only for a single branch of history! * fix layer vtop after rollback * engine fix * Fix test_txpool * Fix test_rpc * Fix copyright year * fix simulator * Fix copyright year * Fix copyright year * Fix tracer * Fix infinite recursion bug * Remove aristo and kvt empty files * Fic copyright year * Fix fc chain_kvt * ForkedChain refactoring * Fix merge master conflict * Fix copyright year * Reparent txFrame * Fix test * Fix txFrame reparent again * Cleanup and fix test * UpdateBase bugfix and fix test * Fixe newPayload bug discovered by hive * Fix engine api fcu * Clean up call template, chain_kvt, andn txguid * Fix copyright year * work around base block loading issue * Add test * Fix updateHead bug * Fix updateBase bug * Change func commitBase to proc commitBase * Touch up and fix debug mode crash --------- Co-authored-by: jangko <jangko128@gmail.com>
183 lines
5.8 KiB
Nim
183 lines
5.8 KiB
Nim
# nimbus-eth1
|
|
# Copyright (c) 2023-2025 Status Research & Development GmbH
|
|
# Licensed under either of
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
|
|
# http://www.apache.org/licenses/LICENSE-2.0)
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or
|
|
# http://opensource.org/licenses/MIT)
|
|
# at your option. This file may not be copied, modified, or distributed
|
|
# except according to those terms.
|
|
|
|
## Aristo DB -- a Patricia Trie with labeled edges
|
|
## ===============================================
|
|
##
|
|
## These data structures allow to overlay the *Patricia Trie* with *Merkel
|
|
## Trie* hashes. See the `README.md` in the `aristo` folder for documentation.
|
|
##
|
|
## Some semantic explanations;
|
|
##
|
|
## * HashKey, NodeRef etc. refer to the standard/legacy `Merkle Patricia Tree`
|
|
## * VertexID, VertexRef, etc. refer to the `Aristo Trie`
|
|
##
|
|
{.push raises: [].}
|
|
|
|
import
|
|
std/[hashes, sets, tables],
|
|
eth/common/hashes,
|
|
results,
|
|
./aristo_constants,
|
|
./aristo_desc/[desc_error, desc_identifiers, desc_nibbles, desc_structural],
|
|
minilru
|
|
|
|
|
|
from ./aristo_desc/desc_backend
|
|
import BackendRef
|
|
|
|
# Not auto-exporting backend
|
|
export
|
|
tables, aristo_constants, desc_error, desc_identifiers, desc_nibbles,
|
|
desc_structural, minilru, hashes
|
|
|
|
type
|
|
AristoTxRef* = ref object
|
|
## Transaction descriptor
|
|
db*: AristoDbRef ## Database descriptor
|
|
parent*: AristoTxRef ## Previous transaction
|
|
layer*: LayerRef
|
|
|
|
AristoDbRef* = ref object
|
|
## Three tier database object supporting distributed instances.
|
|
backend*: BackendRef ## Backend database (may well be `nil`)
|
|
|
|
txRef*: AristoTxRef ## Bottom-most in-memory frame
|
|
|
|
accLeaves*: LruCache[Hash32, VertexRef]
|
|
## Account path to payload cache - accounts are frequently accessed by
|
|
## account path when contracts interact with them - this cache ensures
|
|
## that we don't have to re-traverse the storage trie for every such
|
|
## interaction
|
|
## TODO a better solution would probably be to cache this in a type
|
|
## exposed to the high-level API
|
|
|
|
stoLeaves*: LruCache[Hash32, VertexRef]
|
|
## Mixed account/storage path to payload cache - same as above but caches
|
|
## the full lookup of storage slots
|
|
|
|
# Debugging data below, might go away in future
|
|
xMap*: Table[HashKey,RootedVertexID] ## For pretty printing/debugging
|
|
|
|
Leg* = object
|
|
## For constructing a `VertexPath`
|
|
wp*: VidVtxPair ## Vertex ID and data ref
|
|
nibble*: int8 ## Next vertex selector for `Branch` (if any)
|
|
|
|
Hike* = object
|
|
## Trie traversal path
|
|
root*: VertexID ## Handy for some fringe cases
|
|
legs*: ArrayBuf[NibblesBuf.high + 1, Leg] ## Chain of vertices and IDs
|
|
tail*: NibblesBuf ## Portion of non completed path
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# Public helpers
|
|
# ------------------------------------------------------------------------------
|
|
|
|
template mixUp*(accPath, stoPath: Hash32): Hash32 =
|
|
# Insecure but fast way of mixing the values of two hashes, for the purpose
|
|
# of quick lookups - this is certainly not a good idea for general Hash32
|
|
# values but account paths are generated from accounts which would be hard
|
|
# to create pre-images for, for the purpose of collisions with a particular
|
|
# storage slot
|
|
var v {.noinit.}: Hash32
|
|
for i in 0..<v.data.len:
|
|
# `+` wraps leaving all bits used
|
|
v.data[i] = accPath.data[i] + stoPath.data[i]
|
|
v
|
|
|
|
func getOrVoid*[W](tab: Table[W,VertexRef]; w: W): VertexRef =
|
|
tab.getOrDefault(w, VertexRef(nil))
|
|
|
|
func getOrVoid*[W](tab: Table[W,NodeRef]; w: W): NodeRef =
|
|
tab.getOrDefault(w, NodeRef(nil))
|
|
|
|
func getOrVoid*[W](tab: Table[W,HashKey]; w: W): HashKey =
|
|
tab.getOrDefault(w, VOID_HASH_KEY)
|
|
|
|
func getOrVoid*[W](tab: Table[W,RootedVertexID]; w: W): RootedVertexID =
|
|
tab.getOrDefault(w, default(RootedVertexID))
|
|
|
|
func getOrVoid*[W](tab: Table[W,HashSet[RootedVertexID]]; w: W): HashSet[RootedVertexID] =
|
|
tab.getOrDefault(w, default(HashSet[RootedVertexID]))
|
|
|
|
# --------
|
|
|
|
func isValid*(vtx: VertexRef): bool =
|
|
vtx != VertexRef(nil)
|
|
|
|
func isValid*(nd: NodeRef): bool =
|
|
nd != NodeRef(nil)
|
|
|
|
func isValid*(pid: PathID): bool =
|
|
pid != VOID_PATH_ID
|
|
|
|
func isValid*(layer: LayerRef): bool =
|
|
layer != LayerRef(nil)
|
|
|
|
func isValid*(root: Hash32): bool =
|
|
root != emptyRoot
|
|
|
|
func isValid*(key: HashKey): bool =
|
|
assert key.len != 32 or key.to(Hash32).isValid
|
|
0 < key.len
|
|
|
|
func isValid*(vid: VertexID): bool =
|
|
vid != VertexID(0)
|
|
|
|
func isValid*(rvid: RootedVertexID): bool =
|
|
rvid.vid.isValid and rvid.root.isValid
|
|
|
|
func isValid*(sqv: HashSet[RootedVertexID]): bool =
|
|
sqv.len > 0
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# Public functions, miscellaneous
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# Hash set helper
|
|
func hash*(db: AristoDbRef): Hash =
|
|
## Table/KeyedQueue/HashSet mixin
|
|
cast[pointer](db).hash
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# Public helpers
|
|
# ------------------------------------------------------------------------------
|
|
|
|
iterator rstack*(tx: AristoTxRef): (LayerRef, int) =
|
|
# Stack in reverse order
|
|
var tx = tx
|
|
|
|
var i = 0
|
|
while tx != nil:
|
|
let level = if tx.parent == nil: -1 else: i
|
|
yield (tx.layer, level)
|
|
tx = tx.parent
|
|
|
|
proc deltaAtLevel*(db: AristoTxRef, level: int): LayerRef =
|
|
if level == -2:
|
|
nil
|
|
elif level == -1:
|
|
db.db.txRef.layer
|
|
else:
|
|
var
|
|
frame = db
|
|
level = level
|
|
|
|
while level > 0:
|
|
frame = frame.parent
|
|
level -= 1
|
|
|
|
frame.layer
|
|
|
|
# ------------------------------------------------------------------------------
|
|
# End
|
|
# ------------------------------------------------------------------------------
|