> For the complete documentation index, see [llms.txt](https://parad0xlabs.gitbook.io/parad0xlabs-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://parad0xlabs.gitbook.io/parad0xlabs-docs/nulla-local-compute-mesh/how-it-works.md).

# How It Works

***

## Task Lifecycle

A task moves from requester to verifiable on-chain proof through a fully decentralized auction and execution pipeline. No central server participates at any point.

```mermaid
sequenceDiagram
    participant R as Requester
    participant M as Mesh Peers
    participant TR as Task Router
    participant W as Winning Worker
    participant CL as CreditLedger (SQLite)
    participant S as Solana (SPL Memo)

    R->>M: broadcast_task() — HTTP POST /mesh/bid<br/>payload: TASK_OFFER (task_id, description, budget)
    M-->>R: TaskBid (model_name, estimated_tokens,<br/>credits_requested, Ed25519 sig)
    R->>TR: collect bids, sort cheapest-first
    TR->>TR: classify() waterfall<br/>regex → Ollama fallback
    TR->>TR: build_task_envelope_for_request()<br/>assigns orchestration role
    TR->>CL: escrow_credits_for_task()<br/>debits poster → dispatch_credit_escrow row
    TR->>W: accept_bid() → HTTP POST /mesh/accept
    W->>W: execute inference locally
    W->>W: submit_result()<br/>SHA-256(task_id + result + node_id)
    W->>S: anchor_proof()<br/>SPL Memo instruction (MemoSq4g...)<br/>falls back to DRY_RUN:<hash> if no keypair
    W->>CL: CreditLedger.earn()<br/>records proof_hash in mesh_credit_ledger
    TR->>CL: settle_hive_task_escrow()<br/>release_escrow_to_helper() or refund_escrow_remainder()
    TR-->>R: contribution_proof receipt
```

Peer discovery delegates to `core.discovery_index.list_known_peers()`, falling back to an in-memory list populated by `ping_peer()`. The `dispatch_credit_escrow` row is the canonical record of funds in flight; no double-spend is possible because `spend()` checks balance before writing.

***

## Task Classification

`classify()` is the gatekeeper that routes every task to the correct handler. It runs a priority-ordered regex waterfall across approximately 20 task classes. Only if the input matches nothing and the caller is not a chat UI does it hit a local Ollama endpoint at `POST /v1/chat/completions` with a 4-second hard timeout.

```mermaid
flowchart TD
    IN([Task description string]) --> R1{risky_system_action\nregex match?}
    R1 -->|yes| C1[class: risky_system_action]
    R1 -->|no| R2{debugging\nregex match?}
    R2 -->|yes| C2[class: debugging]
    R2 -->|no| R3{chat_conversation\nregex match?}
    R3 -->|yes| C3[class: chat_conversation]
    R3 -->|no| R4{security_hardening\nregex match?}
    R4 -->|yes| C4[class: security_hardening]
    R4 -->|no| R5{system_design\nregex match?}
    R5 -->|yes| C5[class: system_design]
    R5 -->|no| R6{~15 further regex\nclasses in priority order}
    R6 -->|matched| C6[class: matched_class]
    R6 -->|no match| CHK{caller is\nchat UI?}
    CHK -->|yes| C7[class: chat_conversation\ndefault]
    CHK -->|no| OL[POST /v1/chat/completions\nlocal Ollama — 4s timeout]
    OL -->|response| C8[class: Ollama-classified]
    OL -->|timeout / error| C9[class: unknown\nfallback]
```

The regex waterfall is evaluated in strict priority order; the first match wins. This means a message that contains both debugging and chat signals is classified as `debugging`.

***

## The Anti-Cheat Proof-of-Work

NULLA Local uses a two-phase challenge-response scheme (`core/credits/proof_of_work.py`) that makes result fabrication computationally indistinguishable from doing the actual work. A separate, simpler hash (`SHA-256(task_id + result + node_id)`) is used by the mesh task router for contribution receipts; the scheme below governs credit minting.

```mermaid
sequenceDiagram
    participant I as Issuer
    participant W as Worker
    participant V as Verifier

    I->>I: generate 32-byte random nonce
    I->>I: challenge_hash = SHA-256(nonce)
    I-->>W: ChallengeIssuedTask {challenge_hash, expiry}
    note over W: nonce itself is NOT revealed yet
    W->>W: execute inference → result_bytes
    W->>I: result_hash = SHA-256(result_bytes)
    I-->>W: reveal nonce (raw bytes)
    W->>W: challenge_response = SHA-256(nonce_bytes ‖ result_bytes)
    W->>V: submit {result_hash, challenge_response, task_id}
    V->>V: 1. verify result_hash integrity
    V->>V: 2. verify challenge_response integrity
    V->>V: 3. check replay-attack set (task_id not seen before)
    V->>V: 4. check challenge not expired
    V-->>W: proof accepted / rejected
    W->>S: anchor_proof() → SPL Memo (MemoSq4g...)<br/>or DRY_RUN:<hash> fallback
```

A worker cannot fabricate `challenge_response` without knowing `result_bytes` (pre-image resistance of SHA-256) because the nonce is only revealed after the worker commits to `result_hash`. Replaying a past proof fails the replay-attack set check. The scheme requires no third-party dependencies on the stub path — pure-Python ed25519 and base58 helpers are bundled.

***

## The Two Credit Ledgers

Two independent SQLite ledgers track value at different scopes. They are not synced to each other.

### Ledger 1 — Mesh Node Ledger (`core/mesh/credit_ledger.py`)

Table: `mesh_credit_ledger`

| Column         | Type       | Notes                            |
| -------------- | ---------- | -------------------------------- |
| entry\_id      | INTEGER PK | auto-increment                   |
| node\_id       | TEXT       | peer identifier                  |
| direction      | TEXT       | CHECK IN ('earn', 'spend')       |
| task\_id       | TEXT       | links to task                    |
| amount         | INTEGER    | credit units                     |
| recipient      | TEXT       | destination node                 |
| proof\_hash    | TEXT       | 64-char hex, validated on earn() |
| metadata\_json | TEXT       | arbitrary structured data        |
| created\_at    | TEXT       | ISO timestamp                    |

Indexes on `node_id`, `task_id`, `proof_hash`. `balance()` is a single aggregate: `SUM(earn) - SUM(spend)`. `spend()` checks balance before writing — no overdraft. `earn()` validates the 64-character hex `proof_hash` as a precondition.

`export_proof_bundle()` serializes all entries oldest-first with a per-entry `bundle_hash` for tamper detection. The bundle format is designed for submission to a DNA x402 receipt endpoint or sale on the NULL credit market.

### Ledger 2 — Swarm/Hive Ledger (`core/credit_ledger.py`)

Table: `compute_credit_ledger` (created by storage migrations)

`LEDGER_MODE = "simulated"` is hardcoded. **This ledger does not settle on-chain in the current build.** All settlement is in-process only.

Tracks per-peer balances via signed `amount` rows (positive = award, negative = debit/escrow).

Full escrow lifecycle:

```mermaid
sequenceDiagram
    participant P as Poster
    participant L as Hive Ledger
    participant H as Helper(s)

    P->>L: escrow_credits_for_task()<br/>debit poster → dispatch_credit_escrow row
    L->>L: task dispatched to helpers
    alt outcome == "solved"
        L->>H: release_escrow_to_helper()<br/>100% of escrow split equally among helpers
    else outcome == "partial"
        L->>H: release_escrow_to_helper()<br/>50% of escrow split equally
        L->>P: refund_escrow_remainder()<br/>50% returned to poster
    else task cancelled / no result
        L->>P: refund_escrow_remainder()<br/>100% returned to poster
    end
```

Free-tier fallback: nodes with zero credits receive 24 NULL/day (governance-tunable via `policy_engine`), capped at 12 per dispatch.

***

## Hardware Detection and Routing

`HardwareProbe.probe()` in `core/compute/rental_market.py` runs real system calls to classify the node before any bid is accepted. A parallel probe in `core/hardware_tier.py` maps the same data to Ollama model tier selection.

```mermaid
flowchart TD
    START([HardwareProbe.probe()]) --> CPU[psutil\nCPU core count + RAM GB]
    START --> GPU{nvidia-smi\navailable?}
    GPU -->|yes| NVID[nvidia-smi --query-gpu=name,memory.total\nparse VRAM]
    GPU -->|no| APPL{platform.machine()\nplatform.processor()}
    APPL -->|arm64 / Apple| MPS[Apple Silicon MPS\nVRAM skipped — unified memory\nestimate_tps → 55 t/s]
    APPL -->|other| CPUONLY[CPU-only\n12 t/s scaled by core count]
    NVID --> BENCH[hard-coded benchmark map\nRTX 3090 7B → 100 t/s\nRTX 4090 → 170 t/s\nA100/H100 → 200 t/s]
    CPU --> SIZE[model size class\n7b / 13b / 34b / 70b by substring]
    BENCH --> TIER[hardware_tier.py\ntitan / heavy / mid / base / lite / nano\nQwen2.5 Ollama tier assignment]
    MPS --> TIER
    CPUONLY --> TIER
    SIZE --> TIER
```

### Latency-Based Fraud Detection

After tier assignment, every inference response is timed. Exceeding the tier threshold is treated as a fraud signal and triggers a score slash:

| Tier          | Max allowed latency | Action on breach           |
| ------------- | ------------------- | -------------------------- |
| gpu\_elite    | 500 ms              | fraud signal + score slash |
| gpu\_basic    | 2,500 ms            | fraud signal + score slash |
| cpu\_advanced | 6,000 ms            | fraud signal + score slash |
| cpu\_basic    | 15,000 ms           | fraud signal + score slash |

A node claiming `gpu_elite` hardware but responding in 800 ms will be downgraded automatically.

***

## Status Table

| Component                                                                       | Status                          | Notes                                                                                                                                             |
| ------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| Mesh task auction (`core/mesh/task_router.py`)                                  | **Live**                        | Full bid-accept-execute cycle over HTTP; no central server                                                                                        |
| Task classification — regex waterfall (`classify()`)                            | **Live**                        | \~20 classes, priority-ordered, deterministic                                                                                                     |
| Task classification — Ollama fallback                                           | **Live**                        | POST /v1/chat/completions, 4s timeout; requires local Ollama running                                                                              |
| Mesh credit ledger (`core/mesh/credit_ledger.py`)                               | **Live**                        | SQLite, balance-checked spend, proof\_hash-validated earn, tamper-evident export                                                                  |
| Swarm/hive credit ledger (`core/credit_ledger.py`)                              | **Simulated**                   | `LEDGER_MODE = "simulated"` hardcoded; no on-chain settlement in current build                                                                    |
| Proof-of-work challenge-response (`core/credits/proof_of_work.py`)              | **Live (stub anchor)**          | Two-phase hash scheme is fully implemented; `anchor_proof()` sends SPL Memo if `SOLANA_DEPLOYER_KEYPAIR` is set, otherwise emits `DRY_RUN:<hash>` |
| Hardware probe (`core/compute/rental_market.py` — `HardwareProbe`)              | **Live**                        | Real psutil, nvidia-smi, platform calls; hard-coded TPS benchmarks                                                                                |
| Compute rental market (`core/compute/rental_market.py` — `ComputeRentalMarket`) | **Stub**                        | `discover_rentals()` searches local dict only; no network broadcast; single-tenant session                                                        |
| x402 payment client (`core/x402/client.py`)                                     | **Stub (wired, not triggered)** | STUB mode is the default everywhere; DEVNET/MAINNET paths are implemented but no production caller passes an `X402Config` instance                |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://parad0xlabs.gitbook.io/parad0xlabs-docs/nulla-local-compute-mesh/how-it-works.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
