> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stablenet.network/llms.txt
> Use this file to discover all available pages before exploring further.

# Storage Architecture

## Purpose and Scope

This document describes the persistent and in-memory storage architecture used by StableNet to maintain blockchain state, blocks, and receipts.\
It covers the layered storage structure from the high-level StateDB caching layer down to the raw database backends, including the Merkle Patricia Trie, caching strategies, and the snapshot system.

For state transitions and EVM execution, see *State Transitions and Gas*.\
For blockchain management and canonical chain maintenance, see *Blockchain Management*.\
For detailed information on the ancient store and data lifecycle, see *Ancient Store and Data Lifecycle*.

## Storage Layer Hierarchy

StableNet’s storage architecture is composed of multiple layers, each providing a different level of abstraction and performance optimization.

## StateDB: State Caching Layer

StateDB is the core interface for reading and modifying blockchain state.\
It is an advanced caching layer that provides journaling-based atomicity guarantees and snapshot-based rollback capabilities.

### StateDB Structure

| Component              | Type                                        | Purpose                           |
| ---------------------- | ------------------------------------------- | --------------------------------- |
| `db`                   | `Database`                                  | Trie database interface           |
| `trie`                 | `Trie`                                      | Account trie root                 |
| `snaps`                | `*snapshot.Tree`                            | Snapshot tree for fast access     |
| `snap`                 | `snapshot.Snapshot`                         | Currently active snapshot         |
| `stateObjects`         | `map[common.Address]*stateObject`           | Active account objects            |
| `stateObjectsPending`  | `map[common.Address]struct{}`               | Finalized but uncommitted objects |
| `stateObjectsDirty`    | `map[common.Address]struct{}`               | Objects modified during execution |
| `stateObjectsDestruct` | `map[common.Address]*types.StateAccount`    | Destructed objects                |
| `accounts`             | `map[common.Hash][]byte`                    | Modified account data             |
| `storages`             | `map[common.Hash]map[common.Hash][]byte`    | Modified storage slots            |
| `accountsOrigin`       | `map[common.Address][]byte`                 | Original account values           |
| `storagesOrigin`       | `map[common.Address]map[common.Hash][]byte` | Original storage values           |
| `journal`              | `*journal`                                  | State change log                  |
| `validRevisions`       | `[]revision`                                | Snapshot revisions                |
| `refund`               | `uint64`                                    | Gas refund counter                |

### State Object Management

Each account is managed as a `stateObject`, which wraps the base `types.StateAccount` and tracks execution-time changes.

| Field            | Type                  | Purpose                           |
| ---------------- | --------------------- | --------------------------------- |
| `address`        | `common.Address`      | Account address                   |
| `addrHash`       | `common.Hash`         | Keccak256(address)                |
| `origin`         | `*types.StateAccount` | Original account data             |
| `data`           | `types.StateAccount`  | Current account data              |
| `trie`           | `Trie`                | Storage trie                      |
| `code`           | `Code`                | Contract bytecode                 |
| `originStorage`  | `Storage`             | Original storage                  |
| `pendingStorage` | `Storage`             | Pending storage (awaiting commit) |
| `dirtyStorage`   | `Storage`             | Modified storage during execution |
| `dirtyCode`      | `bool`                | Code modification flag            |
| `selfDestructed` | `bool`                | Self-destruct marker              |
| `deleted`        | `bool`                | Deletion marker                   |
| `created`        | `bool`                | Created in current transaction    |

### Journaling and Snapshots

StateDB records all state changes in a journal to guarantee rollback capability.\
Each journal entry implements a `revert()` method and includes the following change types:

* `balanceChange`
* `nonceChange`
* `storageChange`
* `codeChange`
* `extraChange`
* `createObjectChange`
* `selfDestructChange`
* `touchChange`
* `addLogChange`

## Merkle Patricia Trie Implementation

The Merkle Patricia Trie (MPT) is the core cryptographic data structure used to store state.\
StableNet supports both hash-based and path-based storage schemes.

### Trie Node Types

| Node Type   | Purpose          | Structure                |
| ----------- | ---------------- | ------------------------ |
| `fullNode`  | 16-way branching | `Children [17]node`      |
| `shortNode` | Path compression | `Key []byte`, `Val node` |
| `valueNode` | Leaf value       | `[]byte`                 |
| `hashNode`  | Hash reference   | `[]byte`                 |

## Storage Schemes: Hash vs Path

StableNet supports two trie storage schemes.

| Scheme      | Key Format | Purpose                     |
| ----------- | ---------- | --------------------------- |
| Hash Scheme | Node hash  | Content-addressed storage   |
| Path Scheme | Trie path  | History and pruning support |

The path scheme enables state history, efficient pruning, and historical state queries.\
The hash scheme is simpler but does not embed history.

## BlockChain Caching Strategy

BlockChain minimizes database access by using multiple LRU caches.

| Cache         | Size | Purpose             |
| ------------- | ---- | ------------------- |
| bodyCache     | 256  | Block bodies        |
| blockCache    | 256  | Full blocks         |
| receiptsCache | 32   | Receipts            |
| txLookupCache | 1024 | Transaction lookup  |
| headerCache   | 512  | Block headers       |
| tdCache       | 1024 | Total difficulty    |
| numberCache   | 2048 | Hash → block number |

## Snapshot System

Snapshots provide a flattened view of state, enabling fast access to accounts and storage without traversing the state trie.

### Snapshot Layers

| Layer       | Purpose        | Storage |
| ----------- | -------------- | ------- |
| `difflayer` | Recent changes | Memory  |
| `disklayer` | Base state     | Disk    |

Snapshot access order is diff → disk → trie fallback.

### Snapshot Configuration

| Field             | Default | Purpose                     |
| ----------------- | ------- | --------------------------- |
| `SnapshotLimit`   | 256MB   | Snapshot cache size         |
| `SnapshotNoBuild` | false   | Disable background building |
| `SnapshotWait`    | true    | Wait on startup             |

## State Commit and Finalization

State changes proceed through modification → finalization → trie update → commit stages.\
The final result is returned as a new state root hash.

## Raw Database and Ancient Store

At the lowest level, a key-value database is used, and old data is migrated to the ancient store.

### Ancient Store Characteristics

* Reduced active database size
* Fast sequential access to historical data
* Enables pruning of the active database
* Supports Era1 archive generation

## Cache Configuration Summary

| Configuration        | Default   | Purpose            |
| -------------------- | --------- | ------------------ |
| `TrieCleanLimit`     | 256MB     | Clean trie cache   |
| `TrieDirtyLimit`     | 256MB     | Dirty trie cache   |
| `TrieTimeLimit`      | 5 minutes | Flush delay        |
| `SnapshotLimit`      | 256MB     | Snapshot cache     |
| `StateHistory`       | 0         | State history      |
| `bodyCacheLimit`     | 256       | Block bodies       |
| `blockCacheLimit`    | 256       | Full blocks        |
| `receiptsCacheLimit` | 32        | Receipts           |
| `txLookupCacheLimit` | 1024      | Transaction lookup |
