2024-08-06 11:29:26 +00:00
|
|
|
# Nimbus
|
|
|
|
# Copyright (c) 2023-2024 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.
|
|
|
|
|
|
|
|
{.used.}
|
|
|
|
|
|
|
|
import
|
|
|
|
std/[json, os, sets, strutils, tables],
|
|
|
|
eth/common,
|
|
|
|
stew/byteutils,
|
|
|
|
results,
|
|
|
|
unittest2,
|
|
|
|
../test_helpers,
|
|
|
|
../../nimbus/db/aristo,
|
|
|
|
../../nimbus/db/aristo/[aristo_desc, aristo_get, aristo_hike, aristo_layers,
|
|
|
|
aristo_part],
|
|
|
|
../../nimbus/db/aristo/aristo_part/part_debug
|
|
|
|
|
|
|
|
type
|
|
|
|
ProofData = ref object
|
2024-10-01 21:03:10 +00:00
|
|
|
chain: seq[seq[byte]]
|
2024-09-11 09:39:45 +00:00
|
|
|
missing: bool
|
2024-08-06 11:29:26 +00:00
|
|
|
error: AristoError
|
|
|
|
hike: Hike
|
|
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# Private helper
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
2024-10-01 21:03:10 +00:00
|
|
|
proc createPartDb(ps: PartStateRef; data: seq[seq[byte]]; info: static[string]) =
|
2024-08-06 11:29:26 +00:00
|
|
|
# Set up production MPT
|
|
|
|
block:
|
|
|
|
let rc = ps.partPut(data, AutomaticPayload)
|
|
|
|
if rc.isErr: raiseAssert info & ": partPut => " & $rc.error
|
|
|
|
|
|
|
|
# Save keys to database
|
Store keys together with node data (#2849)
Currently, computed hash keys are stored in a separate column family
with respect to the MPT data they're generated from - this has several
disadvantages:
* A lot of space is wasted because the lookup key (`RootedVertexID`) is
repeated in both tables - this is 30% of the `AriKey` content!
* rocksdb must maintain in-memory bloom filters and LRU caches for said
keys, doubling its "minimal efficient cache size"
* An extra disk traversal must be made to check for existence of cached
hash key
* Doubles the amount of files on disk due to each column family being
its own set of files
Here, the two CFs are joined such that both key and data is stored in
`AriVtx`. This means:
* we save ~30% disk space on repeated lookup keys
* we save ~2gb of memory overhead that can be used to cache data instead
of indices
* we can skip storing hash keys for MPT leaf nodes - these are trivial
to compute and waste a lot of space - previously they had to present in
the `AriKey` CF to avoid having to look in two tables on the happy path.
* There is a small increase in write amplification because when a hash
value is updated for a branch node, we must write both key and branch
data - previously we would write only the key
* There's a small shift in CPU usage - instead of performing lookups in
the database, hashes for leaf nodes are (re)-computed on the fly
* We can return to slightly smaller on-disk SST files since there's
fewer of them, which should reduce disk traffic a bit
Internally, there are also other advantages:
* when clearing keys, we no longer have to store a zero hash in memory -
instead, we deduce staleness of the cached key from the presence of an
updated VertexRef - this saves ~1gb of mem overhead during import
* hash key cache becomes dedicated to branch keys since leaf keys are no
longer stored in memory, reducing churn
* key computation is a lot faster thanks to the skipped second disk
traversal - a key computation for mainnet can be completed in 11 hours
instead of ~2 days (!) thanks to better cache usage and less read
amplification - with additional improvements to the on-disk format, we
can probably get rid of the initial full traversal method of seeding the
key cache on first start after import
All in all, this PR reduces the size of a mainnet database from 160gb to
110gb and the peak memory footprint during import by ~1-2gb.
2024-11-20 08:56:27 +00:00
|
|
|
# TODO support for partial databases
|
|
|
|
# for (rvid,key) in ps.vkPairs:
|
|
|
|
# ps.db.layersPutKey(rvid, key)
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Make sure all is OK
|
|
|
|
block:
|
|
|
|
let rc = ps.check()
|
|
|
|
if rc.isErr: raiseAssert info & ": check => " & $rc.error
|
|
|
|
|
|
|
|
|
|
|
|
proc preLoadAristoDb(jKvp: JsonNode): PartStateRef =
|
|
|
|
const info = "preLoadAristoDb"
|
|
|
|
let ps = PartStateRef.init AristoDbRef.init()
|
|
|
|
|
|
|
|
# Collect rlp-encodede node blobs
|
2024-10-01 21:03:10 +00:00
|
|
|
var proof: seq[seq[byte]]
|
2024-08-06 11:29:26 +00:00
|
|
|
for (k,v) in jKvp.pairs:
|
|
|
|
let
|
|
|
|
key = hexToSeqByte(k)
|
|
|
|
val = hexToSeqByte(v.getStr())
|
|
|
|
if key.len == 32:
|
2024-10-01 21:03:10 +00:00
|
|
|
doAssert key == val.keccak256.data
|
2024-08-06 11:29:26 +00:00
|
|
|
if val != @[0x80u8]: # Exclude empty item
|
|
|
|
proof.add val
|
|
|
|
|
|
|
|
ps.createPartDb(proof, info)
|
|
|
|
ps
|
|
|
|
|
|
|
|
|
2024-10-16 06:51:38 +00:00
|
|
|
proc collectAddresses(node: JsonNode, collect: var HashSet[Address]) =
|
2024-08-06 11:29:26 +00:00
|
|
|
case node.kind:
|
|
|
|
of JObject:
|
|
|
|
for k,v in node.pairs:
|
|
|
|
if k == "address" and v.kind == JString:
|
2024-10-16 06:51:38 +00:00
|
|
|
collect.incl Address.fromHex v.getStr
|
2024-08-06 11:29:26 +00:00
|
|
|
else:
|
|
|
|
v.collectAddresses collect
|
|
|
|
of JArray:
|
|
|
|
for v in node.items:
|
|
|
|
v.collectAddresses collect
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
|
2024-10-01 21:03:10 +00:00
|
|
|
proc payloadAsBlob(pyl: LeafPayload; ps: PartStateRef): seq[byte] =
|
2024-08-06 11:29:26 +00:00
|
|
|
## Modified function `aristo_serialise.serialise()`.
|
|
|
|
##
|
|
|
|
const info = "payloadAsBlob"
|
|
|
|
case pyl.pType:
|
|
|
|
of AccountData:
|
2024-08-07 13:28:01 +00:00
|
|
|
let key = block:
|
|
|
|
if pyl.stoID.isValid:
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
let rc = ps.db.getKeyRc((VertexID(1),pyl.stoID.vid), {})
|
2024-08-07 13:28:01 +00:00
|
|
|
if rc.isErr:
|
|
|
|
raiseAssert info & ": getKey => " & $rc.error
|
Pre-allocate vids for branches (#2882)
Each branch node may have up to 16 sub-items - currently, these are
given VertexID based when they are first needed leading to a
mostly-random order of vertexid for each subitem.
Here, we pre-allocate all 16 vertex ids such that when a branch subitem
is filled, it already has a vertexid waiting for it. This brings several
important benefits:
* subitems are sorted and "close" in their id sequencing - this means
that when rocksdb stores them, they are likely to end up in the same
data block thus improving read efficiency
* because the ids are consequtive, we can store just the starting id and
a bitmap representing which subitems are in use - this reduces disk
space usage for branches allowing more of them fit into a single disk
read, further improving disk read and caching performance - disk usage
at block 18M is down from 84 to 78gb!
* the in-memory footprint of VertexRef reduced allowing more instances
to fit into caches and less memory to be used overall.
Because of the increased locality of reference, it turns out that we no
longer need to iterate over the entire database to efficiently generate
the hash key database because the normal computation is now faster -
this significantly benefits "live" chain processing as well where each
dirtied key must be accompanied by a read of all branch subitems next to
it - most of the performance benefit in this branch comes from this
locality-of-reference improvement.
On a sample resync, there's already ~20% improvement with later blocks
seeing increasing benefit (because the trie is deeper in later blocks
leading to more benefit from branch read perf improvements)
```
blocks: 18729664, baseline: 190h43m49s, contender: 153h59m0s
Time (total): -36h44m48s, -19.27%
```
Note: clients need to be resynced as the PR changes the on-disk format
R.I.P. little bloom filter - your life in the repo was short but
valuable
2024-12-04 10:42:04 +00:00
|
|
|
rc.value[0][0]
|
2024-08-07 13:28:01 +00:00
|
|
|
else:
|
|
|
|
VOID_HASH_KEY
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
rlp.encode Account(
|
|
|
|
nonce: pyl.account.nonce,
|
|
|
|
balance: pyl.account.balance,
|
2024-10-01 21:03:10 +00:00
|
|
|
storageRoot: key.to(Hash32),
|
2024-08-06 11:29:26 +00:00
|
|
|
codeHash: pyl.account.codeHash)
|
|
|
|
of StoData:
|
|
|
|
rlp.encode pyl.stoData
|
|
|
|
|
|
|
|
|
2024-10-01 21:03:10 +00:00
|
|
|
func asExtension(b: seq[byte]; path: Hash32): seq[byte] =
|
2024-08-06 11:29:26 +00:00
|
|
|
var node = rlpFromBytes b
|
|
|
|
if node.listLen == 17:
|
|
|
|
let nibble = NibblesBuf.fromBytes(path.data)[0]
|
|
|
|
var wr = initRlpWriter()
|
|
|
|
|
|
|
|
wr.startList(2)
|
2024-09-02 14:03:10 +00:00
|
|
|
wr.append NibblesBuf.fromBytes(@[nibble]).slice(1).toHexPrefix(isleaf=false).data()
|
2024-08-06 11:29:26 +00:00
|
|
|
wr.append node.listElem(nibble.int).toBytes
|
|
|
|
wr.finish()
|
|
|
|
|
|
|
|
else:
|
|
|
|
b
|
|
|
|
|
2024-09-11 09:39:45 +00:00
|
|
|
when false:
|
|
|
|
# just keep for potential debugging
|
|
|
|
proc sq(s: string): string =
|
|
|
|
## For long strings print `begin..end` only
|
|
|
|
let n = (s.len + 1) div 2
|
|
|
|
result = if s.len < 20: s else: s[0 .. 5] & ".." & s[s.len-8 .. ^1]
|
|
|
|
result &= "[" & (if 0 < n: "#" & $n else: "") & "]"
|
|
|
|
|
2024-08-06 11:29:26 +00:00
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# Private test functions
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
2024-11-02 09:29:16 +00:00
|
|
|
proc testCreatePortalProof(node: JsonNode, testStatusIMPL: var TestStatus) {.deprecated: "need to be rewritten to use non-generic data".} =
|
|
|
|
block: # TODO remove after rewrite
|
|
|
|
skip
|
|
|
|
return
|
2024-08-06 11:29:26 +00:00
|
|
|
const info = "testCreateProofTwig"
|
|
|
|
|
|
|
|
# Create partial database
|
|
|
|
let ps = node["state"].preLoadAristoDb()
|
|
|
|
|
|
|
|
# Collect addresses from json structure
|
2024-10-16 06:51:38 +00:00
|
|
|
var addresses: HashSet[Address]
|
2024-08-06 11:29:26 +00:00
|
|
|
node.collectAddresses addresses
|
|
|
|
|
|
|
|
# Convert addresses to valid paths (not all addresses might work)
|
2024-10-01 21:03:10 +00:00
|
|
|
var sample: Table[Hash32,ProofData]
|
2024-08-06 11:29:26 +00:00
|
|
|
for a in addresses:
|
|
|
|
let
|
2024-10-01 21:03:10 +00:00
|
|
|
path = a.data.keccak256
|
2024-09-19 08:39:06 +00:00
|
|
|
var hike: Hike
|
|
|
|
let rc = path.hikeUp(VertexID(1), ps.db, Opt.none(VertexRef), hike)
|
2024-08-06 11:29:26 +00:00
|
|
|
sample[path] = ProofData(
|
|
|
|
error: (if rc.isErr: rc.error[1] else: AristoError(0)),
|
2024-09-19 08:39:06 +00:00
|
|
|
hike: hike) # keep `hike` for potential debugging
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Verify that there is somehing to do, at all
|
|
|
|
check 0 < sample.values.toSeq.filterIt(it.error == AristoError 0).len
|
|
|
|
|
|
|
|
# Create proof chains
|
|
|
|
for (path,proof) in sample.pairs:
|
|
|
|
let rc = ps.db.partAccountTwig path
|
2024-09-11 09:39:45 +00:00
|
|
|
if proof.error == AristoError(0):
|
|
|
|
check rc.isOk and rc.value[1] == true
|
|
|
|
proof.chain = rc.value[0]
|
|
|
|
elif proof.error != HikeBranchMissingEdge:
|
|
|
|
# Note that this is a partial data base and in this case the proof for a
|
|
|
|
# non-existing entry might not work properly when the vertex is missing.
|
|
|
|
check rc.isOk and rc.value[1] == false
|
|
|
|
proof.chain = rc.value[0]
|
|
|
|
proof.missing = true
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Verify proof chains
|
|
|
|
for (path,proof) in sample.pairs:
|
2024-09-11 09:39:45 +00:00
|
|
|
if proof.missing:
|
|
|
|
# Proof for missing entries
|
|
|
|
let
|
|
|
|
rVid = proof.hike.root
|
2024-10-01 21:03:10 +00:00
|
|
|
root = ps.db.getKey((rVid,rVid)).to(Hash32)
|
2024-09-11 09:39:45 +00:00
|
|
|
|
|
|
|
block:
|
|
|
|
let rc = proof.chain.partUntwigPath(root, path)
|
|
|
|
check rc.isOk and rc.value.isNone
|
|
|
|
|
|
|
|
# Just for completeness (same a above combined into a single function)
|
2024-10-01 21:03:10 +00:00
|
|
|
check proof.chain.partUntwigPathOk(root, path, Opt.none seq[byte]).isOk
|
2024-09-11 09:39:45 +00:00
|
|
|
|
|
|
|
elif proof.error == AristoError 0:
|
2024-08-06 11:29:26 +00:00
|
|
|
let
|
|
|
|
rVid = proof.hike.root
|
|
|
|
pyl = proof.hike.legs[^1].wp.vtx.lData.payloadAsBlob(ps)
|
|
|
|
|
|
|
|
block:
|
|
|
|
# Use these root and chain
|
|
|
|
let chain = proof.chain
|
|
|
|
|
|
|
|
# Create another partial database from tree
|
|
|
|
let pq = PartStateRef.init AristoDbRef.init()
|
|
|
|
pq.createPartDb(chain, info)
|
|
|
|
|
|
|
|
# Create the same proof again which must result into the same as before
|
|
|
|
block:
|
|
|
|
let rc = pq.db.partAccountTwig path
|
2024-09-11 09:39:45 +00:00
|
|
|
if rc.isOk and rc.value[1] == true:
|
|
|
|
check rc.value[0] == proof.chain
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Verify proof
|
2024-10-01 21:03:10 +00:00
|
|
|
let root = pq.db.getKey((rVid,rVid)).to(Hash32)
|
2024-08-06 11:29:26 +00:00
|
|
|
block:
|
2024-08-07 11:30:55 +00:00
|
|
|
let rc = proof.chain.partUntwigPath(root, path)
|
2024-08-06 11:29:26 +00:00
|
|
|
check rc.isOk
|
|
|
|
if rc.isOk:
|
2024-09-11 09:39:45 +00:00
|
|
|
check rc.value == Opt.some(pyl)
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Just for completeness (same a above combined into a single function)
|
2024-09-11 09:39:45 +00:00
|
|
|
check proof.chain.partUntwigPathOk(root, path, Opt.some pyl).isOk
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# Extension nodes are rare, so there is one created, inserted and the
|
|
|
|
# previous test repeated.
|
|
|
|
block:
|
|
|
|
let
|
|
|
|
ext = proof.chain[0].asExtension(path)
|
|
|
|
tail = @(proof.chain.toOpenArray(1,proof.chain.len-1))
|
|
|
|
chain = @[ext] & tail
|
|
|
|
|
|
|
|
# Create a third partial database from modified proof
|
|
|
|
let pq = PartStateRef.init AristoDbRef.init()
|
|
|
|
pq.createPartDb(chain, info)
|
|
|
|
|
|
|
|
# Re-create proof again
|
|
|
|
block:
|
|
|
|
let rc = pq.db.partAccountTwig path
|
2024-09-11 09:39:45 +00:00
|
|
|
check rc.isOk and rc.value[1] == true
|
|
|
|
if rc.isOk and rc.value[1] == true:
|
|
|
|
check rc.value[0] == chain
|
2024-08-06 11:29:26 +00:00
|
|
|
|
2024-10-01 21:03:10 +00:00
|
|
|
let root = pq.db.getKey((rVid,rVid)).to(Hash32)
|
2024-08-06 11:29:26 +00:00
|
|
|
block:
|
2024-08-07 11:30:55 +00:00
|
|
|
let rc = chain.partUntwigPath(root, path)
|
2024-08-06 11:29:26 +00:00
|
|
|
check rc.isOk
|
|
|
|
if rc.isOk:
|
2024-09-11 09:39:45 +00:00
|
|
|
check rc.value == Opt.some(pyl)
|
2024-08-06 11:29:26 +00:00
|
|
|
|
2024-09-11 09:39:45 +00:00
|
|
|
check chain.partUntwigPathOk(root, path, Opt.some pyl).isOk
|
2024-08-06 11:29:26 +00:00
|
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# Test
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
suite "Encoding & verification of portal proof twigs for Aristo DB":
|
|
|
|
# Piggyback on tracer test suite environment
|
|
|
|
jsonTest("TracerTests", testCreatePortalProof)
|
|
|
|
|
|
|
|
# ------------------------------------------------------------------------------
|
|
|
|
# End
|
|
|
|
# ------------------------------------------------------------------------------
|