> {
// Create isolated instance
let instance = self.create_instance(wasm_module)?;
// Set resource limits
instance.set_memory_limit(self.max_memory);
instance.set_fuel(self.max_execution_time);
// Execute with timeout
let result = tokio::time::timeout(
Duration::from_secs(30),
instance.call("execute", input)
).await??;
Ok(result)
}
}
```
---
## 7. API Design
### 7.1 Contributor API (Website Owners)
```javascript
// Initialize as a contributor
const node = await EdgeNet.init({
// Identity
siteId: 'my-site-123', // Your unique identifier
privateKey: localStorage.getItem('edgenet_key'), // Persistent identity
// Contribution settings
contribution: {
cpuLimit: 0.3, // Max 30% CPU when idle
memoryLimit: 256 * 1024 * 1024, // 256MB max
bandwidthLimit: 1024 * 1024, // 1MB/s max
tasks: ['vectors', 'embeddings', 'encryption'], // Allowed task types
},
// Idle detection
idle: {
focusRequired: false, // Contribute even when focused
minIdleTime: 5000, // 5s before considering idle
respectBattery: true, // Reduce on battery power
},
// Network
relays: [
'https://gun-manhattan.herokuapp.com/gun',
'wss://relay.edgenet.dev',
],
// Callbacks
onCredit: (credits, total) => {
console.log(`Earned ${credits}, total: ${total}`);
},
onTask: (task) => {
console.log(`Processing: ${task.type}`);
},
onError: (error) => {
console.error('EdgeNet error:', error);
},
});
// Check status
console.log(node.stats());
// { credits: 1250, tasksCompleted: 847, uptime: 3600, reputation: 0.95 }
// Pause/resume contribution
node.pause();
node.resume();
// Disconnect
node.disconnect();
```
### 7.2 Consumer API (Task Submitters)
```javascript
// Submit tasks to the network
const result = await EdgeNet.submit({
type: 'embedding',
payload: {
texts: ['Hello world', 'How are you?'],
model: 'minilm',
},
options: {
priority: 'high', // 'low' | 'normal' | 'high'
redundancy: 3, // Workers for verification
maxCredits: 10, // Max credits willing to pay
timeout: 30000, // 30s timeout
},
});
console.log(result);
// {
// embeddings: [[0.1, 0.2, ...], [0.3, 0.4, ...]],
// cost: 5,
// workers: ['node-1', 'node-2', 'node-3'],
// verified: true
// }
// Batch submission
const results = await EdgeNet.submitBatch([
{ type: 'vector_search', payload: { query: [...], k: 10 } },
{ type: 'semantic_match', payload: { task: 'write code', agents: [...] } },
{ type: 'encryption', payload: { data: [...], key: [...] } },
]);
```
### 7.3 Dashboard Widget
```javascript
// Embed a contribution dashboard
EdgeNet.createWidget({
container: '#edgenet-widget',
theme: 'dark',
showCredits: true,
showStats: true,
showLeaderboard: true,
});
```
```html
┌────────────────────────────────────┐
│ EdgeNet Contributor │
├────────────────────────────────────┤
│ Credits: 1,250 │
│ Tasks: 847 completed │
│ Rank: #1,234 of 50,000 │
│ Uptime: 12h 34m │
│ │
│ [■■■■■■■□□□] 70% CPU donated │
│ │
│ Multiplier: 4.2x (early adopter) │
└────────────────────────────────────┘
```
---
## 8. Implementation Plan
### Phase 1: Core Infrastructure (Week 1-2)
| Task | Description | Files |
|------|-------------|-------|
| 1.1 | Project setup, Cargo.toml, package.json | `Cargo.toml`, `package.json` |
| 1.2 | Identity system (Ed25519 + WASM bindings) | `src/identity.rs` |
| 1.3 | Credit ledger (CRDT implementation) | `src/credits/ledger.rs` |
| 1.4 | Web Worker pool manager | `pkg/worker-pool.js` |
| 1.5 | Basic P2P via GUN.js | `src/network/gun.rs`, `pkg/network.js` |
### Phase 2: Task System (Week 3-4)
| Task | Description | Files |
|------|-------------|-------|
| 2.1 | Task queue (submit, claim, complete) | `src/tasks/queue.rs` |
| 2.2 | Task executor (sandboxed WASM) | `src/tasks/executor.rs` |
| 2.3 | Vector operations (from edge-wasm) | `src/tasks/vectors.rs` |
| 2.4 | Encryption tasks | `src/tasks/crypto.rs` |
| 2.5 | Result verification system | `src/tasks/verify.rs` |
### Phase 3: Credit System (Week 5-6)
| Task | Description | Files |
|------|-------------|-------|
| 3.1 | Contribution curve calculation | `src/credits/curve.rs` |
| 3.2 | Credit transfer protocol | `src/credits/transfer.rs` |
| 3.3 | Stake/slash mechanics | `src/credits/stake.rs` |
| 3.4 | Balance sync (CRDT merge) | `src/credits/sync.rs` |
| 3.5 | Anti-sybil measures | `src/security/sybil.rs` |
### Phase 4: Integration (Week 7-8)
| Task | Description | Files |
|------|-------------|-------|
| 4.1 | JavaScript API wrapper | `pkg/edge-net.js` |
| 4.2 | CDN build (minified, tree-shaken) | `pkg/edge-net.min.js` |
| 4.3 | Dashboard widget | `pkg/widget.js` |
| 4.4 | Example applications | `examples/` |
| 4.5 | Documentation | `README.md` |
### Phase 5: Testing & Launch (Week 9-10)
| Task | Description | Files |
|------|-------------|-------|
| 5.1 | Unit tests (Rust) | `tests/` |
| 5.2 | Integration tests (Browser) | `tests/browser/` |
| 5.3 | Load testing (simulated network) | `tests/load/` |
| 5.4 | Security audit | `SECURITY.md` |
| 5.5 | npm publish | CI/CD |
---
## 9. Package Structure
```
examples/edge-net/
├── Cargo.toml # Rust workspace config
├── Cargo.lock
├── README.md # Package documentation
├── DESIGN.md # This file
├── LICENSE # MIT
│
├── src/ # Rust source
│ ├── lib.rs # Main entry point
│ │
│ ├── identity/ # Identity management
│ │ ├── mod.rs
│ │ ├── keypair.rs # Ed25519 keypairs
│ │ └── fingerprint.rs # Browser fingerprinting
│ │
│ ├── credits/ # Credit system
│ │ ├── mod.rs
│ │ ├── ledger.rs # CRDT ledger
│ │ ├── curve.rs # Contribution curve
│ │ ├── transfer.rs # Credit transfers
│ │ ├── stake.rs # Staking mechanics
│ │ └── sync.rs # Balance synchronization
│ │
│ ├── tasks/ # Task execution
│ │ ├── mod.rs
│ │ ├── queue.rs # Task queue
│ │ ├── executor.rs # Sandboxed executor
│ │ ├── vectors.rs # Vector operations
│ │ ├── embeddings.rs # Embedding generation
│ │ ├── crypto.rs # Encryption tasks
│ │ └── verify.rs # Result verification
│ │
│ ├── network/ # P2P networking
│ │ ├── mod.rs
│ │ ├── discovery.rs # Peer discovery
│ │ ├── gun.rs # GUN.js bridge
│ │ └── protocol.rs # Wire protocol
│ │
│ ├── scheduler/ # Work scheduling
│ │ ├── mod.rs
│ │ ├── idle.rs # Idle detection
│ │ ├── throttle.rs # CPU throttling
│ │ └── priority.rs # Task prioritization
│ │
│ └── security/ # Security measures
│ ├── mod.rs
│ ├── sybil.rs # Anti-sybil
│ ├── sandbox.rs # WASM sandbox
│ └── audit.rs # Audit logging
│
├── pkg/ # Built JavaScript package
│ ├── package.json # npm package config
│ ├── edge-net.js # Main entry (ESM)
│ ├── edge-net.min.js # Minified for CDN
│ ├── edge-net.d.ts # TypeScript definitions
│ ├── edge-net_bg.wasm # WASM binary
│ ├── edge-net_bg.wasm.d.ts # WASM types
│ ├── worker.js # Web Worker
│ ├── worker-pool.js # Worker pool manager
│ ├── network.js # GUN.js integration
│ ├── widget.js # Dashboard widget
│ ├── widget.css # Widget styles
│ └── README.md # npm README
│
├── examples/ # Example applications
│ ├── contributor.html # Simple contributor
│ ├── consumer.html # Task consumer
│ ├── dashboard.html # Full dashboard
│ ├── chatbot.html # Distributed chatbot
│ └── vector-search.html # Distributed search
│
├── tests/ # Tests
│ ├── unit/ # Rust unit tests
│ ├── integration/ # Integration tests
│ ├── browser/ # Browser tests (Playwright)
│ └── load/ # Load tests
│
└── scripts/ # Build scripts
├── build.sh # Build WASM + JS
├── bundle.sh # Create CDN bundle
└── publish.sh # Publish to npm
```
---
## 10. Performance Targets
### 10.1 Metrics
| Metric | Target | Rationale |
|--------|--------|-----------|
| **WASM Load Time** | < 100ms | Minimal impact on page load |
| **Memory Usage** | < 50MB idle | Won't impact browser |
| **CPU Usage (Idle)** | < 5% | Unnoticeable when not contributing |
| **CPU Usage (Active)** | Configurable 10-50% | User control |
| **Task Latency** | < 100ms (local) | Responsive feel |
| **Network Overhead** | < 10KB/min | Minimal bandwidth |
| **Credit Sync** | < 1s eventual | Fast balance updates |
| **Task Throughput** | 100+ tasks/min | Useful compute |
### 10.2 Bundle Size
| Component | Size | Notes |
|-----------|------|-------|
| Core WASM | ~200KB | Compressed |
| JavaScript | ~30KB | Minified + gzipped |
| Worker | ~10KB | Separate chunk |
| Widget | ~15KB | Optional |
| **Total (min)** | **~230KB** | Core only |
| **Total (full)** | **~255KB** | With widget |
### 10.3 Scalability
```
Network Size Task Throughput P2P Connections Credit Sync
──────────── ─────────────── ─────────────── ───────────
100 nodes 1K tasks/min ~5 per node < 1s
1K nodes 10K tasks/min ~10 per node < 2s
10K nodes 100K tasks/min ~20 per node < 5s
100K nodes 1M tasks/min ~30 per node < 10s
1M nodes 10M tasks/min ~50 per node < 30s
```
---
## Appendix A: Contribution Curve Derivation
The contribution curve follows an exponential decay:
```
R(x) = 1 + (M - 1) * e^(-x/D)
Where:
R(x) = Reward multiplier at network compute level x
M = Maximum multiplier for genesis contributors (10x)
D = Decay constant (1,000,000 CPU-hours)
x = Total network CPU-hours contributed
Derivation:
- At x=0: R(0) = 1 + 9*1 = 10x (maximum reward)
- At x=D: R(D) = 1 + 9/e ≈ 4.3x (36.8% of bonus remaining)
- At x=2D: R(2D) = 1 + 9/e² ≈ 2.2x
- At x→∞: R(∞) → 1x (baseline reward)
Properties:
- Smooth decay (no cliff)
- Never goes below 1x
- Predictable for planning
- Fair to late adopters (still get baseline)
```
---
## Appendix B: CRDT Ledger Specification
```rust
// G-Set: Grow-only set of credit events
struct CreditEvent {
id: Uuid,
from: NodeId,
to: NodeId,
amount: u64,
reason: CreditReason,
timestamp: u64,
signature: Signature,
}
enum CreditReason {
TaskCompleted { task_id: Uuid },
UptimeReward { hours: f32 },
Referral { referee: NodeId },
Stake { direction: StakeDirection },
Transfer { memo: String },
}
// LWW-Register: Last-writer-wins for reputation
struct ReputationRegister {
node: NodeId,
score: f32, // 0.0 - 1.0
timestamp: u64,
evidence: Vec,
}
// Merge function (associative, commutative, idempotent)
fn merge(a: &Ledger, b: &Ledger) -> Ledger {
Ledger {
events: a.events.union(&b.events), // G-Set merge
reputation: merge_lww(&a.reputation, &b.reputation),
}
}
```
---
## Appendix C: Security Considerations
### C.1 Browser Fingerprinting (Privacy-Preserving)
```javascript
// Generate anonymous uniqueness score without tracking
async function generateAnonymousFingerprint() {
const components = [
// Hardware signals
navigator.hardwareConcurrency,
screen.width * screen.height,
// WebGL (hashed)
hashWebGLRenderer(),
// Audio (hashed)
hashAudioContext(),
// Canvas (hashed)
hashCanvas(),
];
// Hash all components together
const fingerprint = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(components.join('|'))
);
// Only use for uniqueness, not tracking
return bufferToHex(fingerprint);
}
```
### C.2 Task Payload Encryption
All task payloads are encrypted end-to-end:
1. Submitter generates ephemeral X25519 keypair
2. Task encrypted with contributor's public key
3. Only assigned contributor can decrypt
4. Result encrypted with submitter's public key
5. Network only sees encrypted blobs
### C.3 WASM Sandbox Restrictions
- No network access (fetch, WebSocket, etc.)
- No filesystem access
- No DOM access
- Memory limited to configured maximum
- Execution time limited with fuel metering
- Only pure computation allowed
---
## Next Steps
1. **Review this design** - Gather feedback on architecture
2. **Create project structure** - Set up Cargo workspace and npm package
3. **Implement core identity** - Start with Ed25519 + WASM bindings
4. **Build task executor** - Sandboxed WASM execution
5. **Integrate P2P** - GUN.js for task queue and credit sync
6. **Test with real sites** - Deploy beta to willing participants