# Quick Start: Oracle API Setup

**Complete setup guide for running Kapture with independent oracle service.**

---

## Overview

```
System Operator (You)    Employer              Employee 1            Employee 2
      │                     │                     │                     │
      │ 1. Generate oracle  │                     │                     │
      │    keypair          │                     │                     │
      │                     │                     │                     │
      │ 2. Start oracle     │                     │                     │
      │    service          │                     │                     │
      │    (localhost:5000) │                     │                     │
      │                     │                     │                     │
      │ ◄───────────────────┤ 3. Create vault    │                     │
      │    Get oracle pubkey│    (oracle API)    │                     │
      │                     │                     │                     │
      │                     │ ────────────────────┤ 4. Setup employee  │
      │                     │  Send admin wallet  │    vault           │
      │                     │                     │                     │
      │                     │ ────────────────────┼─────────────────────┤
      │                     │  Send admin wallet  │                     │ 5. Setup employee
      │                     │                     │                     │    vault
      │                     │                     │                     │
      │                     │                     │ 6. Track work       │
      │                     │                     │    (screenshots)    │
      │                     │                     │                     │
      │ ◄───────────────────┼─────────────────────┤ 7. Submit hours    │
      │    Submit to API    │                     │    (to oracle)     │
      │                     │                     │                     │
      │ 8. Verify & sign    │                     │                     │
      │    transaction      │                     │                     │
      │                     │                     │                     │
      └─────────────────────┴─────────────────────┴─────────────────────┘
                                   Blockchain
                            (Solana Smart Contract)
```

---

## Step 1: System Operator Setup (You)

### Install Everything

```bash
# Clone repo
git clone https://github.com/stElmitchay/kapture
cd kapture

# Install main package
pip3 install -e .

# Install oracle dependencies
cd oracle_service
pip3 install -r requirements.txt
cd ..
```

### Generate Oracle Keypair

```bash
python3 -m loggerheads.oracle_secure --generate
```

Output:
```
✅ Oracle keypair generated: /Users/you/.loggerheads/oracle-keypair.json
🔑 Public key: 7xJ9XxQpY8K3RmNvBzH4LtWfE6CqD5Ag2jP1sU9Tx7Vc

⚠️  IMPORTANT: Keep this file secure and NEVER commit to git!
```

### Start Oracle Service

```bash
python3 oracle_service/app.py
```

Output:
```
🔮 KAPTURE ORACLE SERVICE
══════════════════════════════════════════════════════════════════════

✅ Oracle Public Key: 7xJ9XxQpY8K3RmNvBzH4LtWfE6CqD5Ag2jP1sU9Tx7Vc

📡 Starting API server...
   Employers: Use this oracle pubkey when creating vaults
   Employees: Submit hours to this service

══════════════════════════════════════════════════════════════════════

 * Running on http://0.0.0.0:5000
```

**Keep this running!** Leave terminal open.

### Get Your IP Address

If testers are on different machines:

```bash
# macOS
ipconfig getifaddr en0

# Linux
hostname -I | awk '{print $1}'
```

Let's say your IP is: `192.168.1.100`

### Share With Testers

Tell your 3 testers:
- Oracle URL: `http://192.168.1.100:5000`
- They need to set: `export KAPTURE_ORACLE_URL=http://192.168.1.100:5000`

---

## Step 2: Employer Setup

**Employer runs on their machine:**

### Set Oracle URL (if not localhost)

```bash
export KAPTURE_ORACLE_URL=http://192.168.1.100:5000
```

### Setup Solana

```bash
# Create wallet
solana-keygen new

# Switch to devnet
solana config set --url devnet

# Get test SOL
solana airdrop 2
```

### Get Test USDC

Visit: https://spl-token-faucet.com/?token-name=USDC-Dev

Request: 6000 USDC (for 2 employees × 20 days × $150/day)

### Create Vault for Employee 1

```bash
loggerheads
```

Follow prompts:
1. Choose: **Employer**
2. Employee wallet: `<Employee 1's wallet address>`
3. Total USDC: `3000`
4. Daily target: `8` hours
5. Daily unlock: `150` USDC
6. Confirm: **y**

Output:
```
🔮 Connecting to oracle service...
   ✓ Oracle: 7xJ9XxQpY8K3Rm...

✅ VAULT CREATED SUCCESSFULLY!

📤 SEND THIS TO YOUR EMPLOYEE:

  Admin Wallet: 4KcYcbhrgzFgKSD5o76hwEE3BLcAUMtVGxHGMKV6vDiS

  That's all they need! Tell them to:
  1. Run: loggerheads
  2. Choose: Employee
  3. Paste your admin wallet when asked
```

### Create Vault for Employee 2

Repeat same process with Employee 2's wallet address.

---

## Step 3: Employee Setup (Both Employees)

**Each employee runs on their machine:**

### Set Oracle URL (if not localhost)

```bash
export KAPTURE_ORACLE_URL=http://192.168.1.100:5000

# Make permanent (add to ~/.bashrc or ~/.zshrc)
echo 'export KAPTURE_ORACLE_URL=http://192.168.1.100:5000' >> ~/.bashrc
```

### Setup Solana

```bash
# Create wallet
solana-keygen new

# Get your address
solana address
```

**Share this address with employer!**

```bash
# Switch to devnet
solana config set --url devnet

# Get test SOL
solana airdrop 2
```

### Connect to Vault

```bash
loggerheads
```

Follow prompts:
1. Choose: **Employee**
2. Admin wallet: `<Paste employer's wallet>`
3. Auto-submit: **y**
4. Time: `18:00`

Output:
```
✅ Configuration saved!

⏳ Installing auto-submit...
✅ Auto-submit enabled for 18:00 daily

🎉 SETUP COMPLETE!
```

---

## Step 4: Daily Work Flow

### Employee: Start Tracking

```bash
loggerheads start
```

Work normally for 8+ hours. Press Ctrl+C when done.

### Automatic Submission

At 18:00, auto-submit runs automatically:

```
⏰ Auto-Submit Running at 2025-10-27 18:00:00

📊 Hours worked today: 8.5
   Screenshots: 102
   Submitting as: 8.5 hours

📤 Submitting to oracle service...
   ✓ Oracle online: 7xJ9XxQpY8K3Rm...

✅ Success!
📝 Transaction: 5xRt2Qw...
🔍 Explorer: https://explorer.solana.com/tx/5xRt2Qw...?cluster=devnet

💰 Vault Status:
   Unlocked: $150.00 USDC
   Remaining: $2850.00 USDC

💡 You can withdraw: loggerheads withdraw

✅ Auto-submit completed successfully
```

### What Happened Behind the Scenes

1. Employee's client calculated 8.5 hours from screenshots
2. Client POSTed to oracle API with work proof
3. Oracle verified vault exists and trusts this oracle
4. Oracle signed transaction with its keypair (kept secure on server)
5. Oracle submitted to Solana blockchain
6. Smart contract checked oracle signature
7. Smart contract unlocked $150 because 8.5 ≥ 8 hours target
8. Employee received confirmation

### Employee: Check Balance

```bash
loggerheads balance
```

Output:
```
💰 Your Balance

💵 Your Wallet: $0.00

📊 Your Work Contract:
💼 Available to withdraw: $150.00
🔒 Still earning: $2850.00
📋 Total contract: $3000.00
```

### Employee: Withdraw

```bash
loggerheads withdraw
```

Follow prompts to withdraw USDC to your wallet.

---

## Verification & Testing

### Test Oracle API Directly

```bash
# Check health
curl http://192.168.1.100:5000/health

# Get oracle pubkey
curl http://192.168.1.100:5000/oracle-pubkey
```

### Test Submission

```bash
# Manual submission (if auto-submit disabled)
loggerheads submit
```

### Check Vault Status

```bash
loggerheads config
```

---

## Troubleshooting

### "Cannot reach oracle service"

**Problem:**
```
❌ Cannot reach oracle service at http://192.168.1.100:5000
```

**Solutions:**

1. **Check oracle is running:**
   ```bash
   curl http://192.168.1.100:5000/health
   ```

2. **Check firewall:**
   ```bash
   # Allow port 5000
   # macOS: System Preferences → Security & Privacy → Firewall
   # Linux: sudo ufw allow 5000
   ```

3. **Verify URL is correct:**
   ```bash
   echo $KAPTURE_ORACLE_URL
   ```

### "Vault trusts different oracle"

**Problem:**
```
{"error": "Vault trusts different oracle: 9xHw..."}
```

**Solution:**
- Vault was created with different oracle
- Delete vault and recreate with current oracle
- Or update KAPTURE_ORACLE_URL to correct oracle

### "Port already in use"

**Problem:**
```
OSError: [Errno 48] Address already in use
```

**Solution:**
```bash
# Find and kill process using port 5000
lsof -i :5000
kill -9 <PID>

# Or change port in oracle_service/app.py
```

---

## Architecture Benefits

### Why This Is Better

**Old Approach (Shared Keypair):**
```
❌ Oracle keypair shared among users
❌ Any user could fake hours
❌ No real verification
❌ Not production-ready
```

**New Approach (API Service):**
```
✅ Oracle keypair stays on secure server
✅ Users POST to API, oracle verifies
✅ Oracle signs with its own keypair
✅ True independent verification
✅ Production-ready architecture
✅ Matches real blockchain oracles (Chainlink, etc.)
```

### Security Model

```
┌──────────┐                  ┌─────────┐                 ┌──────────────┐
│ EMPLOYEE │──work proof─────>│ ORACLE  │──signed tx─────>│ BLOCKCHAIN   │
│          │  (screenshots)   │ SERVICE │  (verified)     │ (enforces)   │
│          │                  │         │                 │              │
│          │  ❌ NEVER has    │ 🔐 Has  │                 │ ✅ Checks    │
│          │     oracle key   │    key  │                 │    signature │
└──────────┘                  └─────────┘                 └──────────────┘
```

**Trust Model:**
- Employee trusts oracle to verify work fairly
- Employer trusts oracle to prevent fraud
- Oracle is independent from both parties
- Smart contract enforces rules automatically

---

## Next Steps

### After Testing

1. **Save test data** - Don't lose your work
2. **Document issues** - Any bugs or confusing flows
3. **Gather feedback** - What worked, what didn't

### For Production

See `oracle_service/README.md` for:
- Deploying to cloud (AWS, GCP, Heroku)
- Implementing real work verification
- Adding fraud detection
- Setting up monitoring
- Security hardening

---

## Support

**Questions?** See docs/TESTING_GUIDE.md

**Issues?** https://github.com/stElmitchay/loggerheads/issues

**Architecture?** See ARCHITECTURE.md for system design
