# chainWare Control (CWC) & StackChain™ Master Specification

> **Guiding Principle:** *"Contributors Own It."*  
> Software in chainWare is not speculative or disposable; it is sovereign, bankable property backed by three layers of immutable cryptographic receipts.

---

## 1. Executive Summary

**chainWare Control (CWC)** is a dual-layer sovereign blockchain architecture built for verifiable computing, permanent decentralized storage, and collective software ownership. 

**StackChain™ (`https://stackchain.net`)** is the sovereign Git-native object database and shared library protocol for the chainWare ecosystem. Running on dedicated bare-metal infrastructure (Node 2), StackChain translates Git commits, trees, and blobs into on-chain **Daily Improvement Packages (DIPs)** governed and ratified by the **rDAO** without reliance on centralized corporate gatekeepers (GitHub, Microsoft, AWS).

```mermaid
flowchart TD
    subgraph Git_Client ["Developer Tooling"]
        git["Git CLI / Developer"]
        cwc_id["CWC Identity (Ed25519 / PBKDF2)"]
    end

    subgraph StackChain_Engine ["StackChain.net (Node 2 Bare-Metal)"]
        hub["hub.stackchain.net (Git Object Hub)"]
        l2_pool["466 GB Sovereign SSD Pool"]
        dip_engine["DIP Packaging Engine"]
    end

    subgraph CWC_Dual_Chain ["chainWare Consensus Network"]
        L2["Layer 2: Content & Blob Storage (l2-11 / l2-12)"]
        L1["Layer 1: Settlement & Consensus (l1-11 / l1-12)"]
        rDAO["rDAO Ratification Council"]
    end

    git -->|Authenticated Push| hub
    cwc_id -->|Sign DIP Work| dip_engine
    hub -->|Store Blobs/Trees| l2_pool
    dip_engine -->|1. STORE Content Tx| L2
    dip_engine -->|2. L2_POINTER Index Tx| L1
    L1 -->|Proposal Voting| rDAO
```

---

## 2. The 3-Layer Stacked Receipts in the DIPs

Every code commit and sprint submission in StackChain generates a **Daily Improvement Package (DIP)** containing a three-layer receipt stack:

```mermaid
flowchart LR
    L1R["Layer 1: Engineering Receipt<br><b>Proof of Work & Code Diffs</b>"]
    L2R["Layer 2: Title Receipt<br><b>Provenance, Author, & Tax Lots</b>"]
    L3R["Layer 3: Rent Roll Receipt<br><b>Cumulative Economic Dividends</b>"]

    L1R --> L2R --> L3R
```

### Layer 1: Finished Engineering Receipts (*Proof of Contribution*)
* **Contents:** Exact Git commit SHA-1/SHA-256 hashes, source tree diffs, deterministic compiler outputs, automated unit/integration test logs, and cryptographic documentation hashes.
* **On-Chain Anchor:** Stored in Layer 2 SSD pools under `git:blob:<hash>` and referenced by the Layer 1 block consensus pointer.
* **Purpose:** Provides mathematically indisputable proof that specific engineering work was completed and tested during the sprint.

### Layer 2: Provenance & Title Receipts (*Chain of Title & Tax Lot*)
* **Contents:** The unbroken legal and cryptographic chain of ownership: creator's Ed25519 CWC wallet address (`cw...`), secondary market transfer records, Ethereum USDC multi-sig hashes, and dripWallet escrow authorizations.
* **On-Chain Anchor:** Committed as an immutable `STORE` transaction on Layer 2 and cross-linked via `L2_POINTER` on Layer 1.
* **Purpose:** Establishes unambiguous property title, preventing dilution or copyright ambiguity.

### Layer 3: Cumulative Revenue Receipts (*Economic Rent Roll*)
* **Contents:** Real-time ledger of micro-settlements, transaction fees, and storage tolls accrued across all decentralized applications and protocol components that execute this code.
* **On-Chain Anchor:** Account and escrow balances held in `protocol:escrow:...` and distributed according to rDAO-ratified cap tables.
* **Purpose:** Transforms static open-source software into an income-generating asset that delivers continuous dividends to contributors.

---

## 3. Official On-Chain AI Front-End Programming Reference

*(Scraped and verified directly from Layer 2 Block `212,814`, Tx: `88C0315E57ABA607494907A952834DF840C120CC6ADF5617F618AABA63B7C79D`)*

### 3.1 Network Role & Transaction Types

| Network Layer | Primary Functions | Implemented Transaction Types | Status / Cautions |
| :--- | :--- | :--- | :--- |
| **Layer 1** | Settlement, consensus, coin transfers, escrows, L2 pointers | `CREATOR_INIT_L1`<br>`REGISTER_WALLET`<br>`TRANSFER`<br>`STORAGE_FUND`<br>`L2_POINTER`<br>`ESCROW`<br>`SIGNAL` | `SETTLE` is **FAIL-CLOSED** (reserved until cross-layer inclusion proofs are deployed). |
| **Layer 2** | Content objects, Git blobs, profile media, storage pools | `CREATOR_INIT_L2`<br>`STORE`<br>`DELETE`<br>`SIGNAL` | `STORAGE_CREDIT` is **FAIL-CLOSED** (reserved pending inclusion proofs). |

### 3.2 Transport Protocols

All client interaction routes through the CometBFT JSON-RPC proxy at `/chainware-rpc`:
* **JSON-RPC 2.0:** Standard requests (`status`, `tx`, `block`, `broadcast_tx_sync`).
* **Application Queries:** Executed via CometBFT `abci_query` with path string. Response value is returned as base64-encoded JSON.

```javascript
// Universal CometBFT abci_query Client
async function chainQuery(rpcBase, queryPath) {
  const resp = await fetch(rpcBase.replace(/\/+$/, '') + '/abci_query?path=' + encodeURIComponent('"' + queryPath + '"'));
  const data = await resp.json();
  const rawValue = data?.result?.response?.value;
  if (!rawValue) return null;
  const decodedStr = atob(rawValue);
  try {
    return JSON.parse(decodedStr);
  } catch (e) {
    return decodedStr;
  }
}
```

### 3.3 Complete `queryState()` API Reference

1. **`/state` (L1 & L2):** Returns chain-level application state.
   * `AppVersion`, `Layer` (`layer-1` or `layer-2`), `ChainID`, `Height`, `Initialized`, `CreatorInitialized`, `Decimals` (12), `TxCount`.
2. **`/capabilities` (L1 & L2):** Returns supported transactions and size limits.
   * `MaxTxBytes: 524288` (512 KB), `TransactionTypes`, `CreatorMode`.
3. **`/creator` (L1 & L2):**
   * `initialized`, `manifest_hash`, `manifest`, `creator_tx_hash`.
4. **`/wallet-registration/<address>` (L1):**
   * `{ "registered": boolean, "wallet": "cw..." }`.
5. **`/bootstrap-budget` (L1):**
   * `{ "id": "protocol:budget:initial-bootstrap", "eligible_wallets": 100, "reward_per_wallet": "1000000000000000", "remaining": "..." }`.
6. **`/storage-funding/<txHash>` & `/storage-fundings` (L1):**
   * Queries individual or all storage fundings (`ID`, `Wallet`, `L2ChainID`, `Amount`, `CreatedHeight`, `Status: "LOCKED_PENDING_L2_PROOF"`).
7. **`/l2-pointers` (L1):**
   * The core bridge discovery endpoint: returns all L1 pointers to L2 content (`Hash`, `Signer`, `L2ChainID`, `L2TxHash`, `L2Height`, `Action`, `CreatedHeight`).
8. **`/account/<address>` (L1 & L2):**
   * Returns `{ "balance": "<atomic_integer>", "nonce": <integer> }`.
   * **Rule:** Next transaction nonce MUST equal `account.nonce + 1`.
   * **Decimals:** 12 decimal places ($1\text{ cWc} = 10^{12}\text{ atomic units}$).
9. **`/escrow/<id>` & `/escrows` (L1):**
   * Returns escrow records (`creator`, `amount`, `status: LOCKED`, `payload`).
10. **`/content/<key>` (L2):**
    * Returns stored content payload (`Key`, `Owner`, `CreatedHeight`, `UpdatedHeight`, `Content`). Only the original owner can overwrite or delete.
11. **`/signals` (L1 & L2):**
    * Global event broadcast log (`Hash`, `Signer`, `Height`, `Data`).

---

## 4. Cryptographic Identity & Transaction Specification

### 4.1 50-Word Official CWC Vocabulary
All 24-word recovery seeds are chosen exclusively from this 50-word lowercase dictionary:
```text
amber anchor apple arch arrow atlas autumn bamboo beacon birch 
blue breeze brook cedar circle cloud cobalt comet coral creek 
dawn delta dune eagle earth ember fern field flame forest 
frost galaxy garden glacier gold harbor hazel hill horizon island 
jade lake leaf light maple meadow moon moss north ocean 
olive orbit pine quartz rain river sage silver sky solar 
stone sunrise tide willow
```

### 4.2 Key Derivation Pipeline (WebCrypto)
```javascript
// 1. PBKDF2 Master Seed Derivation (210,000 Iterations)
const material = await crypto.subtle.importKey("raw", enc.encode(seedPhrase), "PBKDF2", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits({
  name: "PBKDF2",
  hash: "SHA-512",
  salt: enc.encode("chainWare Social v5 wallet seed"),
  iterations: 210000
}, material, 256);

// 2. Ed25519 PKCS#8 Construction
const pkcs8Prefix = fromHex("302e020100300506032b657004220420");
const pkcs8Key = concat(pkcs8Prefix, new Uint8Array(bits));
const privateKey = await crypto.subtle.importKey("pkcs8", pkcs8Key, { name: "Ed25519" }, true, ["sign"]);
const jwk = await crypto.subtle.exportKey("jwk", privateKey);

// 3. Wallet Address Derivation: cw + sha256(pubKeyBytes)[0..20]
const pubBytes = b64url(jwk.x);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", pubBytes));
const address = "cw" + hex(digest.slice(0, 20));
```

### 4.3 Canonical Transaction Signing
The signature is **not** computed over the full JSON envelope. It is computed strictly over the canonical signing document:

```json
{
  "version": 1,
  "chain_id": "l1-11",
  "type": "TRANSFER",
  "gas": "0",
  "signer": "cwbabb0435b4af4161797ec58e10dfc8ad6adea2e3",
  "nonce": 1,
  "payload": {
    "action": "SUBMIT_POST",
    "amount": "1000000000000"
  },
  "public_key": "base64_pub_key..."
}
```

* **Rules:**
  1. `payload` JSON keys must be alphabetically sorted and canonicalized.
  2. Escape special HTML characters (`<`, `>`, `&`, `\u2028`, `\u2029`) to match Go's `json.Marshal`.
  3. Sign serialized bytes with Ed25519.
  4. Base64-encode signature and embed in outer envelope.

---

## 5. Bare-Metal Infrastructure & Node Roles

All machines operate on dedicated bare-metal hardware. **Zero Kubernetes (`k3s`) or container virtualization overhead.**

```mermaid
graph TD
    N1["Node 1 (That70sRobot-01)<br><b>68.122.49.138</b><br>• L1/L2 Consensus Validator<br>• SSRT Snapshot Engine<br>• cwc-post Dual Broadcaster"]
    N2["Node 2 (That70sRobot-02)<br><b>68.122.49.139</b><br>• StackChain.net Gateway<br>• hub.stackchain.net (Git Engine)<br>• 466 GB Sovereign SSD Pool"]
    N3["Node 3 (That70sRobot-03)<br><b>68.122.49.143</b><br>• NVIDIA A2 GPU (16 GB VRAM)<br>• Ollama AI Model Synthesis<br>• 80 GB RAM Bare Metal"]

    N1 <-->|Consensus P2P| N2
    N2 <-->|Code Ingestion| N3
    N1 <-->|Telemetry & State| N3
```

### Node 1 (`That70sRobot-01` • `68.122.49.138`)
* **Role:** Active consensus validator for Layer 1 and Layer 2.
* **Storage:** 1.2 TB Sovereign Storage Pool mounted at `/mnt/sovereign-storage-pool/cwc-l2-storage`.
* **Services:**
  * CometBFT Layer 1 (`l1-12`, RPC: `:53057`, P2P: `:53056`).
  * CometBFT Layer 2 (`l2-12`, RPC: `:54057`, P2P: `:54056`).
  * Super Syncing Retrofit Tunnel (SSRT) automated hourly snapshot engine.
  * `cwc-post`: Universal dual-broadcasting CLI tool (publishes simultaneously to v11 and v12).

### Node 2 (`That70sRobot-02` • `68.122.49.139` • `stackchain.net`)
* **Role:** Sovereign Git-native object database, shared protocol library hub, and public StackChain web portal.
* **Storage:** 466 GB dedicated SSD pool (`/var/www/stackchain.net` and `/mnt/sovereign-pool/`).
* **Web Endpoints:**
  * `https://stackchain.net` (Public Web Gateway & CWC Identity Portal).
  * `https://www.stackchain.net` (Canonical mirror).
  * `https://hub.stackchain.net` (Git Smart HTTP & Packfile Engine).
* **Security:** Nginx TLS 1.2/1.3 reverse proxy, Cloudflare Edge, UFW firewall restricted to management IPs.

### Node 3 (`That70sRobot-03` • `68.122.49.143`)
* **Role:** AI synthesis, code analysis, autonomous agents, and model execution.
* **Compute:** NVIDIA A2 Tensor Core GPU (16 GB dedicated VRAM), 80 GB system RAM, Ollama LLM server.

---

## 6. StackChain Developer Workflow

```mermaid
sequenceDiagram
    autonumber
    actor Dev as Developer / AI Agent
    participant Web as StackChain.net UI
    participant Git as hub.stackchain.net
    participant L2 as Layer 2 Storage
    participant L1 as Layer 1 Consensus
    participant rDAO as rDAO Governance

    Dev->>Web: Connect CWC Identity (24-Word Seed)
    Web-->>Dev: Authenticated (Address cw..., Balance, Nonce)
    Dev->>Git: git push origin main (Signed with Ed25519)
    Git->>L2: Store Packfile Blobs & Diffs (STORE)
    Git->>L1: Anchor Commit & Tree Hashes (L2_POINTER)
    Git->>Web: Register Daily Improvement Package (DIP)
    Web->>rDAO: Submit for Ratification
    rDAO-->>Dev: DIP Ratified -> Layer 3 Economic Receipts Accrue
```

---

## 7. Master Endpoint & Directory Index

### Web Applications
* **StackChain Gateway:** [https://stackchain.net](https://stackchain.net)
* **StackChain Git Hub:** [https://hub.stackchain.net](https://hub.stackchain.net)
* **chainWare Public Feed:** [https://diamondthumb.com/cWc/v11/feed/](https://diamondthumb.com/cWc/v11/feed/)
* **chainWare Profiles:** [https://diamondthumb.com/cWc/v11/profiles/](https://diamondthumb.com/cWc/v11/profiles/)
* **chainWare Prospectus:** [https://l1.that70srobot.com/creator/prospectus.html](https://l1.that70srobot.com/creator/prospectus.html)
* **chainWare White Paper:** [https://l1.that70srobot.com/creator/whitepaper.html](https://l1.that70srobot.com/creator/whitepaper.html)

### Active RPC Gateways
* **Node 1 Layer 1 RPC:** `https://l1.that70srobot.com/chainware-rpc`
* **Node 1 Layer 2 RPC:** `https://l2.that70srobot.com/chainware-rpc`
* **Public Network L1 RPC:** `https://l1-11-2.diamondthumb.com/chainware-rpc`
* **Public Network L2 RPC:** `https://l2-11-2.diamondthumb.com/chainware-rpc`

### Operator Commands on Node 1
```bash
# Post directly to both v11 and v12 feeds
cwc-post "Your announcement or update"

# Check SSRT snapshot status
chainware-ssrt status

# Create on-demand SSRT snapshot
chainware-ssrt create
```
