# Node Architecture

***

## <sup>High-Level Structure</sup>

```
┌─────────────────────────────────────────────────────────────────────┐
│                       NONOS NODE                                    │
└─────────────────────────────────────────────────────────────────────┘

    ┌─────────────────────────────────────────────────────────────┐
    │                    External Interface                       │
    │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐          │
    │  │  HTTP API   │  │    P2P      │  │  Ethereum   │          │
    │  │ :8420       │  │ :9000       │  │    RPC      │          │
    │  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘          │
    └─────────┼────────────────┼────────────────┼─────────────────┘
              │                │                │
    ┌─────────┼────────────────┼────────────────┼─────────────────┐
    │         ▼                ▼                ▼                 │
    │  ┌─────────────────────────────────────────────────────┐    │
    │  │                  Service Router                     │    │
    │  └──────────────────────┬──────────────────────────────┘    │
    │                         │                                   │
    │  ┌──────────────────────┼──────────────────────────────┐    │
    │  │                      ▼                              │    │
    │  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐    │    │
    │  │  │   ZK    │ │  Cache  │ │ Tracker │ │  Health │    │    │
    │  │  │Identity │ │  Mixer  │ │ Blocker │ │ Beacon  │    │    │
    │  │  └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘    │    │
    │  │       │           │           │           │         │    │
    │  │                Privacy Services Layer               │    │
    │  └──────────────────────┬──────────────────────────────┘    │
    │                         │                                   │
    │  ┌──────────────────────┼──────────────────────────────┐    │
    │  │                      ▼                              │    │
    │  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐    │    │
    │  │  │Kademlia │ │GossipSub│ │  Noise  │ │ Request │    │    │
    │  │  │   DHT   │ │ Topics  │ │Protocol │ │Response │    │    │
    │  │  └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘    │    │
    │  │       │           │           │           │         │    │
    │  │  Network Layer (libp2p)                             │    │
    │  └──────────────────────┬──────────────────────────────┘    │
    │                         │                                   │
    │  ┌──────────────────────┼──────────────────────────────┐    │
    │  │                      ▼                              │    │
    │  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐    │    │
    │  │  │  Stake  │ │ Reward  │ │Contract │ │ Metrics │    │    │
    │  │  │ Manager │ │ Tracker │ │ Client  │ │Collector│    │    │
    │  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘    │    │
    │  │                                                     │    │
    │  │  Economic Layer                                     │    │
    │  └─────────────────────────────────────────────────────┘    │
    │                                                             │
    │                        Core Layer                           │
    └─────────────────────────────────────────────────────────────┘
```

***

### Component Details

#### Core Layer

The foundation of the node providing essential services.

**Node Identity**

```rust
pub struct NodeIdentity {
    /// Ed25519 keypair for P2P authentication
    pub keypair: Keypair,

    /// Derived peer ID
    pub peer_id: PeerId,

    /// secp256k1 key for Ethereum signing
    pub eth_key: SigningKey,

    /// Ethereum address for rewards
    pub reward_address: Address,
}
```

**Purpose**: Provides cryptographic identity for:

* P2P network authentication
* Message signing
* Ethereum transaction signing
* Reward claiming

**State Machine**

```
┌─────────────────────────────────────────────────────────────────────┐
│                     NODE STATE MACHINE                              │
└─────────────────────────────────────────────────────────────────────┘

    ┌───────────┐
    │   INIT    │ ─────► Load config, validate keys
    └─────┬─────┘
          │
          ▼
    ┌───────────┐
    │ STARTING  │ ─────► Initialize services, connect to peers
    └─────┬─────┘
          │
          ▼
    ┌───────────┐      ┌───────────┐
    │  RUNNING  │◄─────│RECONNECTING│
    └─────┬─────┘      └───────────┘
          │                  ▲
          │                  │
          ▼                  │
    ┌───────────┐            │
    │DEGRADED   │────────────┘ (network recovery)
    └─────┬─────┘
          │
          ▼
    ┌───────────┐
    │ STOPPING  │ ─────► Graceful shutdown
    └─────┬─────┘
          │
          ▼
    ┌───────────┐
    │  STOPPED  │
    └───────────┘
```

***

#### Privacy Services Layer

**ZK Identity Service**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    ZK IDENTITY SERVICE                               │
└─────────────────────────────────────────────────────────────────────┘

    Components:
    ┌──────────────────────────────────────────────────────────────┐
    │  ┌─────────────────┐     ┌─────────────────┐                 │
    │  │  Identity Store │     │  Merkle Manager │                 │
    │  │  ─────────────  │     │  ─────────────  │                 │
    │  │  • Encrypted    │     │  • Poseidon     │                 │
    │  │  • Per-identity │     │  • 20 levels    │                 │
    │  │  • Key rotation │     │  • O(log n)     │                 │
    │  └────────┬────────┘     └────────┬────────┘                 │
    │           │                       │                          │
    │           └───────────┬───────────┘                          │
    │                       ▼                                      │
    │           ┌─────────────────────┐                            │
    │           │   Proof Generator   │                            │
    │           │   ─────────────────  │                           │
    │           │   • Membership proof │                           │
    │           │   • Non-membership  │                            │
    │           │   • Batch proofs    │                            │
    │           └─────────────────────┘                            │
    └──────────────────────────────────────────────────────────────┘

    Operations:
    • generate_identity() → Creates new ZK identity
    • prove_membership(id, nullifier) → Generates ZK proof
    • verify_proof(proof, root) → Validates proof
    • rotate_identity(old_id) → Creates new, revokes old
```

**Cache Mixing Service**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    CACHE MIXING SERVICE                             │
└─────────────────────────────────────────────────────────────────────┘

    Request Flow:
                     ┌──────────────┐
                     │Incoming      │
                     │Request       │
                     └──────┬───────┘
                            │
                            ▼
                     ┌──────────────┐
                     │ Key Derivation│
                     │ HKDF(content)│
                     └──────┬───────┘
                            │
              ┌─────────────┼─────────────┐
              │             │             │
              ▼             ▼             ▼
        ┌──────────┐ ┌──────────┐ ┌──────────┐
        │Cache HIT │ │Cache MISS│ │ Mix with │
        │          │ │          │ │ Decoys   │
        └────┬─────┘ └────┬─────┘ └────┬─────┘
             │            │            │
             │            ▼            │
             │     ┌──────────┐       │
             │     │  Fetch   │       │
             │     │ Content  │       │
             │     └────┬─────┘       │
             │          │             │
             └──────────┴─────────────┘
                        │
                        ▼
                 ┌──────────────┐
                 │ AES-GCM      │
                 │ Encrypt      │
                 └──────┬───────┘
                        │
                        ▼
                 ┌──────────────┐
                 │ Store/Return │
                 └──────────────┘

    Encryption:
    • Algorithm: AES-256-GCM
    • Key derivation: HKDF-SHA256
    • Nonce: 12 bytes random
    • AAD: timestamp + content hash
```

**Tracking Blocker**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    TRACKING BLOCKER                                 │
└─────────────────────────────────────────────────────────────────────┘

    Rule Sources:
    ┌────────────────────────────────────────────────────────────────┐
    │  Built-in Lists          │ Update Frequency                    │
    ├──────────────────────────┼─────────────────────────────────────┤
    │  EasyList                │ Daily                               │
    │  EasyPrivacy             │ Daily                               │
    │  Fanboy's Lists          │ Daily                               │
    │  NONOS Custom            │ Continuous                          │
    └──────────────────────────┴─────────────────────────────────────┘

    Blocking Layers:
    ┌─────────────────────────────────────────────────────────────────┐
    │                                                                 │
    │  Layer 1: DNS Blocking                                          │
    │  ├── Block known tracker domains                                │
    │  └── CNAME uncloaking                                           │
    │                                                                 │
    │  Layer 2: URL Filtering                                         │
    │  ├── Pattern matching                                           │
    │  └── Parameter stripping                                        │
    │                                                                 │
    │  Layer 3: Header Modification                                   │
    │  ├── Remove tracking headers                                    │
    │  └── Add privacy headers                                        │
    │                                                                 │
    │  Layer 4: Content Filtering                                     │
    │  ├── Script injection blocking                                  │
    │  └── Beacon/pixel removal                                       │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘
```

#### Network Layer

Based on libp2p for decentralized networking.

**Transport Stack**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    TRANSPORT STACK                                  │
└─────────────────────────────────────────────────────────────────────┘

    ┌────────────────────────────────────────────────────────────────┐
    │  Application Data                                              │
    └────────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌────────────────────────────────────────────────────────────────┐
    │  Yamux Multiplexing                                            │
    │  • Multiple streams per connection                             │
    │  • Flow control                                                │
    │  • Low overhead                                                │
    └────────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌────────────────────────────────────────────────────────────────┐
    │  Noise Protocol (XX Handshake)                                 │
    │  • Mutual authentication                                       │
    │  • Forward secrecy                                             │
    │  • Identity binding                                            │
    └────────────────────────────────────────────────────────────────┘
                                  │
                                  ▼
    ┌────────────────────────────────────────────────────────────────┐
    │  TCP / QUIC Transport                                          │
    │  • Reliable delivery                                           │
    │  • NAT traversal (QUIC)                                        │
    │  • Connection pooling                                          │
    └────────────────────────────────────────────────────────────────┘
```

**Peer Discovery (Kademlia DHT)**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    KADEMLIA DHT                                     │
└─────────────────────────────────────────────────────────────────────┘

    Routing Table:
    ┌──────────────────────────────────────────────────────────────────┐
    │  Distance = XOR(our_id, peer_id)                                 │
    │                                                                  │
    │  k-bucket 0:  [peers at distance 2⁰]       (closest)             │
    │  k-bucket 1:  [peers at distance 2¹]                             │
    │  k-bucket 2:  [peers at distance 2²]                             │
    │  ...                                                             │
    │  k-bucket 255: [peers at distance 2²⁵⁵]    (furthest)            │
    │                                                                  │
    │  Each bucket: up to k peers (default k=20)                       │
    └──────────────────────────────────────────────────────────────────┘

    Operations:
    • FIND_NODE: Locate peers close to an ID
    • PUT_VALUE: Store key-value in DHT
    • GET_VALUE: Retrieve value by key
    • BOOTSTRAP: Initial peer discovery
```

**Message Propagation (GossipSub)**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    GOSSIPSUB TOPICS                                 │
└─────────────────────────────────────────────────────────────────────┘

    Topics:
    ┌─────────────────────────────────────────────────────────────────┐
    │  /nonos/health/1.0.0          │ Health beacon broadcasts        │
    │  /nonos/metrics/1.0.0         │ Quality metrics sharing         │
    │  /nonos/requests/1.0.0        │ Content request routing         │
    │  /nonos/rewards/1.0.0         │ Reward announcements            │
    │  /nonos/identity/1.0.0        │ ZK identity tree updates        │
    └─────────────────────────────────────────────────────────────────┘

    Message Flow:
            ┌─────┐
            │ You │
            └──┬──┘
               │ Publish message
               ▼
        ┌──────────────┐
        │ Local Peers  │ (D_out = 6)
        │ ○ ○ ○ ○ ○ ○  │
        └──────┬───────┘
               │
               ▼
        ┌──────────────┐
        │ Their Peers  │ (fanout)
        │○ ○ ○ ○ ○ ○ ○│
        └──────┬───────┘
               │
               ▼
        ┌──────────────┐
        │ Full Network │ (epidemic spread)
        │○○○○○○○○○○○○○│
        └──────────────┘
```

#### Economic Layer

Manages staking, rewards, and blockchain interactions.

**Stake Manager**

```rust
pub struct StakeManager {
    /// Current staked amount
    pub stake: U256,

    /// Current tier
    pub tier: StakingTier,

    /// Pending operations
    pub pending_deposits: Vec<PendingDeposit>,
    pub pending_withdrawals: Vec<PendingWithdrawal>,

    /// Contract client
    pub contract: StakingContract,
}

impl StakeManager {
    /// Deposit stake
    pub async fn deposit(&mut self, amount: U256) -> Result<TxHash>;

    /// Request withdrawal (starts cooldown)
    pub async fn request_withdrawal(&mut self, amount: U256) -> Result<TxHash>;

    /// Complete withdrawal (after cooldown)
    pub async fn complete_withdrawal(&mut self) -> Result<TxHash>;

    /// Get current tier
    pub fn current_tier(&self) -> StakingTier;
}
```

**Reward Tracker**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    REWARD TRACKER                                   │
└─────────────────────────────────────────────────────────────────────┘

    Epoch Lifecycle:
    ┌─────────────────────────────────────────────────────────────────┐
    │                                                                 │
    │  Day 1       Day 2-6      Day 7        Post-Epoch               │
    │  ─────       ────────     ─────        ──────────               │
    │  Reset  ──► Accumulate ──► Finalize ──► Claim                   │
    │  Metrics    Metrics       Calculate    Available                │
    │                           Rewards                               │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘

    Reward State:
    ┌────────────────────────────────────────────────────────────────┐
    │  pending_rewards: U256     // Unclaimed rewards                │
    │  last_claim_epoch: u64     // Last claimed epoch               │
    │  epoch_quality: [f64; 7]   // Daily quality scores             │
    │  streak_count: u32         // Consecutive good epochs          │
    └────────────────────────────────────────────────────────────────┘
```

**Metrics Collector**

```
┌─────────────────────────────────────────────────────────────────────┐
│                    METRICS COLLECTOR                                │
└─────────────────────────────────────────────────────────────────────┘

    Collected Metrics:
    ┌─────────────────────────────────────────────────────────────────┐
    │  Uptime Metrics                                                 │
    │  ├── online_since: Timestamp                                    │
    │  ├── total_online_time: Duration                                │
    │  └── downtime_events: Vec<DowntimeEvent>                        │
    │                                                                 │
    │  Request Metrics                                                │
    │  ├── total_requests: u64                                        │
    │  ├── successful_requests: u64                                   │
    │  ├── failed_requests: u64                                       │
    │  └── avg_response_time: Duration                                │
    │                                                                 │
    │  Network Metrics                                                │
    │  ├── connected_peers: u32                                       │
    │  ├── bandwidth_in: BytesPerSec                                  │
    │  ├── bandwidth_out: BytesPerSec                                 │
    │  └── latency_histogram: Histogram                               │
    │                                                                 │
    │  Privacy Metrics                                                │
    │  ├── trackers_blocked: u64                                      │
    │  ├── identities_served: u64                                     │
    │  └── cache_operations: u64                                      │
    └─────────────────────────────────────────────────────────────────┘

    Export Formats:
    • Prometheus: /api/metrics/prometheus
    • JSON: /api/metrics
    • Dashboard: nonos dash
```

***

### Data Flow

#### Request Processing

```
┌─────────────────────────────────────────────────────────────────────┐
│                    REQUEST PROCESSING FLOW                          │
└─────────────────────────────────────────────────────────────────────┘

    1. Request Received
       │
       ▼
    2. ┌─────────────────┐
       │ Tracking Check  │──► Block if tracker
       └────────┬────────┘
                │ Pass
                ▼
    3. ┌─────────────────┐
       │  Cache Lookup   │──► Return if cached
       └────────┬────────┘
                │ Miss
                ▼
    4. ┌─────────────────┐
       │  Route Request  │──► Select best node(s)
       └────────┬────────┘
                │
                ▼
    5. ┌─────────────────┐
       │ Encrypt & Send  │──► Noise-encrypted P2P
       └────────┬────────┘
                │
                ▼
    6. ┌─────────────────┐
       │ Await Response  │──► Timeout handling
       └────────┬────────┘
                │
                ▼
    7. ┌─────────────────┐
       │  Cache Result   │──► AES-GCM encryption
       └────────┬────────┘
                │
                ▼
    8. ┌─────────────────┐
       │ Return Response │──► Update metrics
       └─────────────────┘
```

***

### Threading Model

```
┌─────────────────────────────────────────────────────────────────────┐
│                    THREADING MODEL                                  │
└─────────────────────────────────────────────────────────────────────┘

    Tokio Runtime
    ┌─────────────────────────────────────────────────────────────────┐
    │                                                                 │
    │  Main Task                                                      │
    │  └── Coordinator, shutdown handling                             │
    │                                                                 │
    │  API Server (Task)                                              │
    │  └── HTTP request handling, response streaming                  │
    │                                                                 │
    │  P2P Network (Task)                                             │
    │  └── libp2p event loop, connection management                   │
    │                                                                 │
    │  Background Workers (Task Pool)                                 │
    │  ├── Metrics collection                                         │
    │  ├── Cache cleanup                                              │
    │  ├── Health beacon                                              │
    │  └── Reward tracking                                            │
    │                                                                 │
    │  Blocking Pool (for CPU-intensive)                              │
    │  ├── Cryptographic operations                                   │
    │  ├── ZK proof generation                                        │
    │  └── Heavy computations                                         │
    │                                                                 │
    └─────────────────────────────────────────────────────────────────┘
```

***

### Configuration

Key configuration options for node architecture:

```toml
[node]
# Worker thread count (default: CPU cores)
worker_threads = 4

# Maximum concurrent connections
max_connections = 1000

# Request timeout
request_timeout_ms = 30000

[network]
# Connection pool size per peer
connections_per_peer = 2

# DHT replication factor
dht_replication = 20

# GossipSub mesh size
mesh_n = 6
mesh_n_low = 4
mesh_n_high = 12

[cache]
# Maximum cache size
max_size_mb = 256

# Entry TTL
default_ttl_hours = 24

# Cleanup interval
cleanup_interval_minutes = 60
```

***

> **Next**: Configuration Guide for detailed configuration options
