Skip to content

levi178u/TEE

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Squirrel x GitUnlock 🐿️

Squirrel

The project is a TEE-powered code marketplace that enables safe buying and selling of proprietary code using confidential computing, AI, and blockchain verification.

Built on NDAI: a 2025 paper showing how Trusted Execution Environments (TEEs) combined with AI agents can solve one of the oldest problems in economics: how do you sell an idea without first giving it away for free?

The Problem

Selling software suffers from the disclosure paradox:

To prove code is valuable, you must reveal it — but once revealed, it can be copied for free.

This leads to:

  • No trust between buyers and sellers
  • High risk of intellectual property theft
  • No safe way to evaluate code before purchase

The Solution

Squirrel x GitUnlock solves this with hardware-enforced escrow: source code lives inside an AMD SEV-SNP encrypted virtual machine. Buyers can interrogate it through an AI & ask about architecture, dependencies, how functions work, etc.. but cannot extract the raw code. The moment a Solana payment confirms, the TEE releases the files. If no deal is reached, the TEE deletes everything. The seller's IP was never actually exposed.


System Architecture Diagram

System Architecture

Workflow Diagram

Workflow

Four Phases —> From the Paper

The NDAI paper defines a five-step mechanism. Squirrel x GitUnlock implements it as four REST-accessible phases:

Phase Paper concept Endpoint What happens
1 · Deposit Seller reveals $\omega$ to T POST /deposit Files encrypted in AMD SEV-SNP RAM before any byte reaches the database.
2 · Inquiry Agents exchange inside T POST /init/chat LLM answers from encrypted codebase; raw code is DLP-gated for non-payers.
3 · Bargain A_B offers $\hat{P}$, A_S checks threshold POST /payment/* Solana TX verified on-chain; payment ledger updated.
4 · Reveal On mutual accept, $\omega$ released POST /reveal Files decrypted in SEV-SNP RAM, returned over TLS, post-payment only.

One Agent or Two? —> How the Paper Maps to This Codebase

The paper describes two agents —> Aₛ (seller's) and A_B (buyer's), and then immediately collapses them:

"We combine the agents {Aᵢ} into a single secure TEE function T." — §3.1

Squirrel is T. One FastAPI server plays both roles inside the same AMD SEV-SNP boundary. This is not a simplification or a shortcut — it is exactly what the paper models. The two agents are conceptually distinct (to capture each party's incentives) but they run inside the same tamper-proof program.

Here is where each agent's specific logic lives in the code:

Aₛ — Seller's agent

  • Receives ω and stores it encrypted: POST /depositdeposit_codebase()encrypt_code()
  • Checks ω̂ = min{ω, Φ}: is_value_within_scope(request.amount) in tee/attestation.py
  • Checks acceptance threshold (rejects if P̂ < asking price): payment.py lamport verification
  • Signals accept and releases ω: POST /reveal after is_payment_confirmed()

A_B — Buyer's agent

  • Evaluates ω̂ inside T without expropriation risk: POST /init decrypts into SEV-SNP RAM, POST /chat queries via FAISS + Groq LLM
  • Cannot carry ω outside the TEE: the 4-layer DLP gate enforces this during evaluation
  • Signals accept by paying: Solana TX is A_B's accept signal
  • Budget cap P̄ = min{ω, Φ}: entry["budget_cap"] = amount in payment.py

The one genuine extension beyond the paper's model is that A_B's evaluation is interactive (multi-turn Q&A) rather than single-shot. The paper says the buyer's agent should "evaluate to its satisfaction" — multi-turn chat is a stronger implementation of that intent than a one-shot evaluation would be.


The Math in the Running System

Two equations from the paper are live in the codebase — not decorative, they actually gate behaviour.

Scope Condition — how much can the TEE protect?

Let $p$ be the probability a breach gets detected, $C$ the penalty for getting caught, $k$ the number of TEEs required to collude, and $\gamma$ the detection amplification exponent. The maximum value the system can credibly protect is:

$$\Phi(k, p, \gamma, C) = \frac{k \cdot (1 - (1-p)^{k^\gamma})}{(1-p)^{k^\gamma}} \cdot C$$

A secret $\omega$ is safe if and only if $\omega \le \Phi$.

With GCP defaults ($k = 3$, $p = 0.005$, $\gamma = 2$, $C = $7.5,\text{B}$), we get $\Phi \approx $1.038,\text{billion}$.

POST /deposit warns the seller if their asking price exceeds $\Phi$. GET /attestation returns the live value as scope_phi_usd. Implemented in tee/attestation.py_compute_phi().

Nash Bargaining —> what is the equilibrium price?

Inside the TEE, the seller's agent and buyer's agent solve a symmetric Nash bargaining problem. With the seller's outside option $\alpha_0\omega$, the equilibrium seller share is:

$$\theta = \frac{1 + \alpha_0}{2}$$

The equilibrium price is $P^* = \theta \cdot \hat{\omega}$. The buyer's budget cap is $\bar{P} = \min{\omega, \Phi}$. The seller discloses $\hat{\omega} = \min{\omega, \Phi}$.

In Squirrel x GitUnlock, Code.amount is the seller's $\omega$. payment.py rejects any transaction where confirmed lamports fall below the asking amount — this is the acceptance threshold that keeps the mechanism incentive-compatible even when AI agent make errors.


What the TEE Guarantees

  • AMD SEV-SNP encrypts the VM's physical memory pages in hardware. The hypervisor cannot read them. GCP's operations team cannot read them. Removing the RAM and reading it gives you ciphertext encrypted with a key inside the CPU die, destroyed on power-off.
  • GCP Secret Manager injects TEE_MASTER_KEY post-attestation via workload identity. It never appears in any config file, log, or shared environment. It lives in RAM until the container exits.
  • vTPM attestation produces a JWT signed by Google's attestation CA. GET /attestation returns this alongside a code_hash — SHA-256 of all server Python files computed at boot. Buyers can verify the code they're trusting matches the published open-source repository.
  • When payment confirms, decrypt_code() runs inside the encrypted address space, the plaintext is returned over TLS, and immediately goes out of scope. It is never written to disk.

Stack

Layer Technology
Frontend Next.js 14 · Auth.js (GitHub OAuth) · Prisma · Tailwind CSS
TEE server FastAPI · Python 3.11 · uvicorn
LLM Groq llama-3.3-70b-versatile or OpenAI via GitHub Models
Embeddings sentence-transformers/all-MiniLM-L6-v2
Vector search FAISS IndexFlatIP — cosine, in-RAM, filtered by code_id
Encryption Fernet AES-128-CBC · PBKDF2-HMAC-SHA256 (480k iterations)
TEE hardware GCP Confidential VM · AMD SEV-SNP · vTPM · Secure Boot
Key management GCP Secret Manager + workload identity
Database PostgreSQL 15 (Prisma schema)
Payments Solana JSON-RPC · Phantom wallet · x402 · mock (dev)
Containers Docker Compose

Project Structure

Squirrel x GitUnlock/
├── server/
│   ├── app.py                  # FastAPI — all 4 NDAI phases as REST endpoints
│   ├── ingest.py               # DB layer — encrypt at deposit, decrypt-in-RAM at read
│   ├── llm.py                  # Groq/OpenAI chain + 4-layer DLP gate
│   ├── vector_db.py            # FAISS vectorstore with code_id metadata_filter
│   ├── crypto_utils.py         # Fernet + PBKDF2 encryption engine
│   ├── payment.py              # Solana RPC · x402 · mock verification
│   ├── tee/
│   │   ├── attestation.py      # vTPM attestation + Φ(k,p,C) scope calculation
│   │   └── key_management.py   # GCP Secret Manager key injection
│   ├── Dockerfile
│   ├── requirements.txt
│   └── .env.example                    
├── frontend/
│   └── app/api/repository/[id]/
│       └── subscribe/route.ts  # Phantom → TEE payment webhook bridge
│   ├── components/
│   │   ├── repository-card.tsx
│   │   ├── theme-provider.tsx
│   │   ├── auth/
│   │   │   └── user-menu.tsx
│   │   ├── solana/
│   │   │   ├── SubscriptionButton.tsx
│   │   │   ├── WalletConnectButton.tsx
│   │   │   └── WalletProvider.tsx
├── deploy/gcp/
│   ├── deploy.sh               # One-command GCP CVM deploy
│   └── README.md
├── seed.ts                     # Prisma seeder
├── docker-compose.yml
├── curl_tests.sh               # Full automated API test suite
└── DOCS.md                    # Deep-dive study guide

1. Configure

git clone https://github.com/levi178u/TEE

server/.env:

GROQ_API_KEY=gsk_...
TEE_MASTER_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(32))")
DATABASE_URL=postgresql://squirrel:squirrel_pass@localhost:5432/squirrel_db

frontend/.env:

AUTH_GITHUB_ID=...
AUTH_GITHUB_SECRET=...
AUTH_SECRET=$(openssl rand -base64 32)
DATABASE_URL=postgresql://squirrel:squirrel_pass@localhost:5432/squirrel_db
NEXT_PUBLIC_CHAT_SERVER_URL=http://localhost:8000

2. Start

docker compose up --build

Wait for ✅ Migration and seeding complete, then:

curl http://localhost:8000/health    # → {"ok": true}
curl http://localhost:8000/code-ids  # → 15 seeded repos
open http://localhost:3000           # Next.js frontend

3. Walk through all four phases

# Phase 1 — Deposit (TEE encrypts before writing to DB)
curl -X POST http://localhost:8000/deposit \
  -H "Content-Type: application/json" \
  -d '{
    "repo_name": "my-algo",
    "amount": 0.5,
    "wallet_address": "YourSolanaWalletAddressHere",
    "files": [{"name":"algo.py","path":"/src","content":"def run(): return 42"}]
  }'
# → {"code_id": "...", "file_count": 1}  — save code_id
 
# Phase 2 — Inquiry (free, DLP-gated)
curl -X POST http://localhost:8000/init \
  -H "Content-Type: application/json" \
  -d '{"code_id":"<CODE_ID>","llm_type":"groq"}'
# → {"session_id": "..."}  — save session_id
 
curl -X POST http://localhost:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"session_id":"<SESSION_ID>","code_id":"<CODE_ID>","question":"How does this work?"}'
# → natural language answer (raw code blocked for non-payers)
 
# Phase 3 — Payment (dev: mock confirm)
curl -X POST http://localhost:8000/payment/request \
  -H "Content-Type: application/json" \
  -d '{"code_id":"<CODE_ID>","buyer_id":"<WALLET>"}'
# → {"payment_id": "..."}  — save payment_id
 
curl -X POST http://localhost:8000/payment/confirm/mock \
  -H "Content-Type: application/json" \
  -d '{"payment_id":"<PAYMENT_ID>"}'
 
# Phase 4 — Reveal (raw files returned post-payment)
curl -X POST http://localhost:8000/reveal \
  -H "Content-Type: application/json" \
  -d '{"code_id":"<CODE_ID>","buyer_id":"<WALLET>"}'
# → {"files": [{"filename": "algo.py", "content": "def run(): return 42"}]}

Run the full automated suite (auto-wires IDs between steps):

chmod +x curl_tests.sh && ./curl_tests.sh

The DLP Gate

Non-paying users get full natural language Q&A but cannot extract source. Four layers enforce this:

  1. Pre-LLM keyword gate —> 34 exact phrases and 7 regex patterns catch requests like show me the code, convert to base64, ignore your instructions. No LLM call is made.
  2. System prompt —> LLM instructed never to output raw code blocks and to emit SQUIRREL_GATED if it suspects a bypass.
  3. Marker check —> If the LLM's response contains SQUIRREL_GATED, it is suppressed.
  4. 40-char sliding window —> Post-response DLP. The answer is scanned against all retrieved chunks. Any 40-character verbatim match triggers suppression. Whitespace and punctuation are normalised first.

Paying users (confirmed Solana TX) bypass all four layers.


TEE Attestation Response

{
  "is_confidential": true,
  "tee_provider": "GCP Confidential VM (AMD SEV-SNP)",
  "code_hash": "<sha256 of server Python files at boot>",
  "scope_phi_usd": 1038283615,
  "tee_params": { "k": 3, "p": 0.005, "gamma": 2.0, "C_usd": 7500000000 },
  "attestation_token_available": true
}

scope_phi_usd is Φ from NDAI Equation-3, live-calculated at boot. In dev mode (GCP_CONFIDENTIAL_VM=false), is_confidential returns false -> as expected.


GCP Deployment (CVM TEE Application)

export PROJECT=your-gcp-project-id
cd deploy/gcp && ./deploy.sh

Creates a n2d-standard-4 Confidential VM (AMD Milan, SEV_SNP, vTPM, Secure Boot), stores TEE_MASTER_KEY in Secret Manager, and prints the attestation report. Machine type must be n2d-standard-* or c3d-* — Intel does not support SEV-SNP.


API Reference

Method Endpoint Phase Description
GET /health Liveness check
GET /repos List repo names
GET /code-ids List code entries with prices and wallets
GET /attestation vTPM report + live Φ scope value
POST /deposit 1 Upload and encrypt source code
POST /init 2 Start a Q&A session
POST /chat 2 Ask a question (DLP-gated)
POST /payment/request 3 Create a payment request
POST /payment/confirm/mock 3 Instant confirm (dev only)
POST /payment/confirm/solana 3 Confirm via Solana JSON-RPC
POST /payment/confirm/x402 3 Confirm via x402 receipt
POST /payment/webhook 3 Phantom → TEE bridge (called by Next.js)
GET /payment/status/{id} 3 Check payment status
POST /reveal 4 Return raw source (post-payment)
DELETE /session/{id} NDAI §4.1 session cleanup

Interactive docs: http://localhost:8000/docs


About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages