alexX512's blog

By alexX512, 8 days ago, translation, In English

I haven't written contests in a long time, but at work I've had some fun tasks lately that made me remember my olympiad days. More specifically, my team is building an Ethereum consensus client, and it needed a persistent segment tree.

In olympiads it's usually written top-down, which isn't great for performance but works fine for contests. So I decided to tune the algorithm by implementing it as a bottom-up segment tree plus a page store on top of it to restore versions. This works pretty well because in Ethereum hashes take a long time to compute, switching to old versions doesn't happen often, updates are randomized, and sequential reads level by level are prefetched quite well by the CPU. So let me tell you what design I ended up with, and at the end I'll drop a link to the Rust implementation.

Problem

Ethereum is a blockchain made of blocks added on top of each other, so it effectively forms a tree. Each block has its own set of state modifications; for simplicity, you can think of the state as a big array of numbers. So every block has its own version of the array, and two versions differ only by the small set of modifications made in their last blocks.

Two forks of the blockchain: almost all data is shared

On top of this data array, we also need to compute a hash of the whole array with SHA-256, like this. The data in the leaves is grouped into 32-byte chunks, and each node above is computed as SHA-256 of its two children, so the root ends up holding the hash of the whole array:

One element changed, so only the hashes on its path to the root are recomputed

So the operations we need are: modifying a single element, recomputing the root hash, and storing versions with switching between them. A pointer-based persistent segment tree does all of this in $$$O(\log n)$$$ per update, but slowly.

Some measurements of what operations cost

When designing this, it's important to keep in mind that hashing two nodes together is pretty slow. Here are measurements of how long hashes and memory reads take. I used one core of a Ryzen 9950X and 64 GB of DDR5-4800 RAM (2 × 32 GB):

Operation Time per pair
Merge 16 hashes at once via SIMD (AVX-512) 14.4 ns
Merge 2 hashes into 1 (SHA-NI) 55 ns
Read a pair from RAM, random order 107 ns
Read pairs from RAM sequentially 2.4 ns

Before computing a hash, we need to read the data from memory. If the data sits in random places, like in a pointer-based persistent tree, then every read is a random memory access: 107 ns per pair, seven times the cost of hashing it with SIMD (14.4 ns per pair). If we read in order instead, the prefetcher loads the data ahead of time, and a pair costs 2.4 ns, six times cheaper than the merge itself. That's why a 128 MB tree, four times bigger than L3, built level by level runs at 14.8 ns per pair, almost the same as the 14.4 ns of the merge alone.

Using a bottom-up segment tree for modifications

The tree is stored exactly like a bottom-up segment tree: root at index 1, children of node v at 2v and 2v + 1, so each level is a contiguous chunk of the array. Since each leaf holds 32 bytes, it contains 4 u64 numbers.

If after $$$k$$$ point updates we walk from each leaf to the root, like in a regular modify, we'll recompute shared parents many times. So let's aggregate the updated leaves into sorted segments and recompute the tree level by level: segment [l, r) turns into the parent segment [l / 2, (r + 1) / 2), adjacent segments get merged, and all of it gets hashed. This way every changed node is hashed exactly once, and $$$k$$$ updates cost $$$O(k \log(n / k))$$$ hashes instead of $$$O(k \log n)$$$.

Recomputing after point updates, level by level

Since we want to make the most of SIMD hashing, when updated nodes go in a big contiguous run, we hash them right in place in the array, from one piece of memory to another. If updates are sparse, we first copy the pairs into a buffer of 16, hash them, and copy the result back. Either way, every AVX-512 call is fully loaded, and only a remainder below 16 goes to SHA-NI.

How to find updated leaves. To remember which leaves changed, we can use a two-level bitset: an array of u64 with one bit per leaf, and a summary array with one bit per word, set if that word has at least one set bit. One summary word covers 4096 leaves, so when collecting updates we just skip empty words entirely.

Two-level bitset of updated leaves

Marking an update is two ORs. And to split a word into segments of ones, three bit operations are enough: lowest = w & -w, remaining = w & (w + lowest), interval = w ^ remaining, so the loop does one iteration per segment, not per bit. Adjacent words are also merged into one segment if there are ones at the boundary, so everything is split into chunks of modifications, which are then used for SIMD hashing.

Splitting a word into segments of ones

Storing versions with pages

We already have a primitive for updates. It's fast enough, but it doesn't support persistence yet. So let's figure out how to build a store of modifications from which we can restore any state.

In a classic persistent segment tree, each node stores itself and references to its children. We can reduce this random-memory-access overhead by representing the tree as small subtrees, each of which stores references to other small subtrees.

In this structure we trade off tree depth (random memory reads) against the number of rewrites of nodes that weren't modified (sequential chunks of memory).

With this design, each row of a page already lies contiguously in the segment tree array, so a page is filled with one memcpy per row.

Each page row is copied in one piece

In effect we get a design similar to the classic version, where we store a tree with pointers, except ours is more optimized for memory access. In the end, modifications of the tree above can be seen as modifications of a smaller tree:

Path copying at page granularity

This works quite well in practice, since switching between versions doesn't happen often, and most of the time we just modify a regular array and save its pages just in case. And since each block in the blockchain usually brings relatively many modifications, this design helps switch to another version much faster when needed.

Complexity

With $$$n$$$ leaves, $$$k$$$ point updates between commits, and pages of $$$B$$$ nodes:

  • Point update: $$$O(1)$$$, a write to the leaf and two ORs.
  • Recompute: $$$O(k \log(n / k))$$$ hashes, 16 at a time.
  • Committing pages: at most $$$k$$$ pages per page level, i.e. $$$O(k \cdot \log n / \log B)$$$.
  • Copying the state: $$$O(1)$$$, since only the root page is needed.
  • Switching versions: we copy only the pages in which the versions differ.

Results

We can compare the results with other implementations in Ethereum consensus clients, which are closer to a classic persistent segment tree. One library is called milhouse, and the other is used in another consensus client; both are written in Rust. For the measurements I used an array of 2.3M elements, since that's how many validators the Ethereum state has. All measurements are on one thread and cover the updates plus the final recomputation of the root hash:

Scenario this tree other client milhouse
Building the tree 14.3 ms 36.0 ms 133 ms
500 random updates 0.36 ms 0.77 ms 6.36 ms
900k updates 16.3 ms 61.2 ms 241 ms
Switching version (1 block apart) + 500 updates 0.43 ms 0.74 ms 6.58 ms
Switching version (4 blocks apart) + 500 updates 1.18 ms 0.74 ms 6.71 ms
Switching version (32 blocks apart) + 500 updates 2.85 ms 0.75 ms 7.14 ms

Switching versions in our implementation can take longer than in the others, because the design is tuned for the real use case, where version switches happen for fewer than 0.15% of blocks, and 99.8% of those are 1 block apart.

Code repository: https://github.com/gattaca-com/silver/tree/main/crates/hashing

Published Rust crate: https://crates.io/crates/silver_state_hashing

If you're interested in more Ethereum-specific details about this library, here's the full post: https://x.com/_alexX512_/status/2125267163691024781

Full text and comments »

  • Vote: I like it
  • +84
  • Vote: I do not like it