proofnest 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,585 +0,0 @@
1
- # Architecture Patterns: PROOFNEST Trust/Proof Infrastructure
2
-
3
- **Domain:** Trust infrastructure for AI decisions
4
- **Researched:** 2026-02-03
5
- **Focus:** Integration patterns for existing Python+Go architecture
6
-
7
- ---
8
-
9
- ## Executive Summary
10
-
11
- PROOFNEST has a solid dual-layer architecture: **Python Core** (FastAPI REST) for proof primitives and **Go Blockchain** (HotStuff-2 BFT) for immutable anchoring. The integration challenge is not redesign but **bridging** these layers for:
12
-
13
- 1. Enterprise API patterns (multi-tenant, rate-limited)
14
- 2. AI agent authentication (machine-to-machine, delegation)
15
- 3. Real-time Hub (WebSocket, event-driven feeds)
16
- 4. Scaling proof verification (batch, Merkle trees)
17
-
18
- **Key Recommendation:** Build an **API Gateway layer** between clients and the Python Core, not a replacement.
19
-
20
- ---
21
-
22
- ## Existing Architecture (DO NOT REDESIGN)
23
-
24
- ### Current Component Map
25
-
26
- ```
27
- CLIENTS
28
- |
29
- +----------------+----------------+
30
- | |
31
- [Enterprise] [AI-Human Hub]
32
- | |
33
- v v
34
- +================================================================+
35
- | API GATEWAY (NEW) |
36
- | - Multi-tenant routing |
37
- | - Rate limiting per tenant |
38
- | - AI agent authentication |
39
- | - WebSocket upgrade for Hub |
40
- +================================================================+
41
- |
42
- v
43
- +================================================================+
44
- | PYTHON CORE (proofnest_core) |
45
- | Port: 8200 |
46
- | - FastAPI REST API |
47
- | - PROOF primitive (claim + evidence + identity + signature) |
48
- | - DID:PN registry with key rotation |
49
- | - Consensus engine (in-memory validators) |
50
- | - SQLite persistence |
51
- | - Bitcoin anchor service (mock) |
52
- | - Blockchain client (JSON-RPC to Go chain) |
53
- +================================================================+
54
- |
55
- v
56
- +================================================================+
57
- | GO BLOCKCHAIN (proofnest_v2/chain) |
58
- | Port: 26657 (JSON-RPC) |
59
- | - HotStuff-2 BFT consensus (~36K LOC) |
60
- | - Dilithium3 post-quantum signatures |
61
- | - libp2p P2P with Kademlia DHT |
62
- | - TxType.PROOF for proof submissions |
63
- | - ~2s block time, ~4s finality |
64
- | - Go SDK for direct integration |
65
- +================================================================+
66
- ```
67
-
68
- ### Current Data Flow
69
-
70
- ```
71
- 1. PROOF Creation:
72
- Client -> POST /v1/proofs -> Python Core -> SQLite
73
- |
74
- v (if consensus)
75
- Validators -> Vote -> QuorumCertificate
76
- |
77
- v (if anchoring)
78
- Go Blockchain (TxType.PROOF)
79
-
80
- 2. PROOF Verification:
81
- Client -> GET /v1/proofs/{id}/verify -> Python Core
82
- |
83
- v
84
- Go Blockchain (verify_proof_on_chain)
85
- ```
86
-
87
- ### Current Authentication
88
-
89
- - **X-API-Key header** or **api_key query param**
90
- - Public endpoints: `/`, `/health`, `/v1/proofs/{id}`, `/v1/proofs/{id}/verify`, `/v1/chain/status`
91
- - Protected endpoints: All POST operations (create identity, proof, validator, vote)
92
-
93
- ---
94
-
95
- ## Integration Architecture Recommendations
96
-
97
- ### Layer 1: API Gateway (HIGH PRIORITY)
98
-
99
- **Why:** Current Python Core lacks multi-tenancy, rate limiting, and AI-specific auth flows.
100
-
101
- **Recommendation:** Deploy **Kong Gateway** or **Traefik** in front of Python Core.
102
-
103
- | Pattern | Implementation | Rationale |
104
- |---------|----------------|-----------|
105
- | Multi-tenant routing | `X-Tenant-ID` header | Isolate enterprise customers |
106
- | Rate limiting | Per-tenant, per-endpoint | Prevent abuse, fair usage |
107
- | AI agent auth | OAuth2 Client Credentials | Machine-to-machine without humans |
108
- | Request logging | Tenant + agent context | Audit trail for enterprise |
109
-
110
- **Component Boundaries:**
111
-
112
- | Component | Responsibility | Communicates With |
113
- |-----------|----------------|-------------------|
114
- | API Gateway | Auth, rate limit, routing | Clients, Python Core |
115
- | Python Core | PROOF lifecycle, DID registry | API Gateway, Go Blockchain |
116
- | Go Blockchain | Immutable anchoring, consensus | Python Core (RPC) |
117
-
118
- **Configuration Pattern:**
119
-
120
- ```yaml
121
- # Kong declarative config example
122
- services:
123
- - name: proofnest-core
124
- url: http://localhost:8200
125
- routes:
126
- - name: enterprise-route
127
- paths: ["/v1"]
128
- headers:
129
- X-Tenant-ID: ["~*"] # Required header
130
- plugins:
131
- - name: rate-limiting
132
- config:
133
- minute: 100
134
- policy: redis
135
- identifier: header
136
- header_name: X-Tenant-ID
137
- - name: oauth2
138
- config:
139
- scopes_required: [proof:create, identity:read]
140
- ```
141
-
142
- **Confidence:** HIGH (Kong and Traefik are proven for this pattern)
143
-
144
- **Sources:**
145
- - [Kong Multi-Tenancy Guide](https://konghq.com/blog/enterprise/multi-tenancy)
146
- - [Azure API Management Multitenant](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/service/api-management)
147
-
148
- ---
149
-
150
- ### Layer 2: AI Agent Authentication
151
-
152
- **Why:** Traditional OAuth2 assumes human in the loop. AI agents need machine-to-machine (M2M) flows with delegation semantics.
153
-
154
- **Recommendation:** Implement **OAuth2 Client Credentials + Agent-ID Tokens**
155
-
156
- **Authentication Flow:**
157
-
158
- ```
159
- 1. AGENT REGISTRATION (one-time):
160
- Agent Owner -> POST /v1/agents/register
161
- {
162
- "agent_name": "my-ai-agent",
163
- "owner_did": "did:pn:human:abc123",
164
- "capabilities": ["proof:create", "proof:read"],
165
- "max_proof_rate": 100 // per minute
166
- }
167
- Response: { "client_id": "...", "client_secret": "..." }
168
-
169
- 2. TOKEN REQUEST (per-session):
170
- Agent -> POST /oauth/token
171
- {
172
- "grant_type": "client_credentials",
173
- "client_id": "...",
174
- "client_secret": "...",
175
- "scope": "proof:create proof:read"
176
- }
177
- Response: {
178
- "access_token": "...", // JWT with agent_id, owner_did, scopes
179
- "token_type": "Bearer",
180
- "expires_in": 3600
181
- }
182
-
183
- 3. API CALLS (authenticated):
184
- Agent -> POST /v1/proofs
185
- Headers:
186
- Authorization: Bearer <access_token>
187
- X-Agent-ID: <agent_did> // Agent's DID:PN identity
188
- ```
189
-
190
- **Agent Identity Lifecycle:**
191
-
192
- ```
193
- 1. CREATION:
194
- - Owner (human/org) registers agent
195
- - Agent gets DID:PN identity (did:pn:agent:xxx)
196
- - Agent gets OAuth2 credentials (client_id/secret)
197
-
198
- 2. OPERATION:
199
- - Agent authenticates via Client Credentials
200
- - Agent creates PROOFs as issuer
201
- - All PROOFs link back to agent DID
202
-
203
- 3. DELEGATION (optional):
204
- - Human delegates authority to agent
205
- - Agent acts "on behalf of" human
206
- - PROOF includes both agent_did AND delegator_did
207
-
208
- 4. REVOCATION:
209
- - Owner revokes agent credentials
210
- - All future auth fails
211
- - Historical PROOFs remain valid (immutable)
212
- ```
213
-
214
- **Key Design Decisions:**
215
-
216
- | Decision | Choice | Why |
217
- |----------|--------|-----|
218
- | Agent identity | DID:PN (same as humans) | Unified identity model |
219
- | Auth mechanism | OAuth2 Client Credentials | Industry standard for M2M |
220
- | Token format | JWT with custom claims | Stateless verification |
221
- | Delegation | PROOF of type DELEGATION | Auditable on-chain |
222
-
223
- **Confidence:** HIGH (OAuth2 M2M is well-established, Agent-ID is emerging standard)
224
-
225
- **Sources:**
226
- - [Stytch: Agent-to-Agent OAuth Guide](https://stytch.com/blog/agent-to-agent-oauth-guide/)
227
- - [Microsoft: OAuth Must Evolve for AI Agents](https://techcommunity.microsoft.com/blog/microsoft-entra-blog/the-future-of-ai-agents%E2%80%94and-why-oauth-must-evolve/3827391)
228
- - [AWS Cognito: Empower AI Agents](https://aws.amazon.com/blogs/security/empower-ai-agents-with-user-context-using-amazon-cognito/)
229
-
230
- ---
231
-
232
- ### Layer 3: AI-Human Hub Architecture
233
-
234
- **Why:** Hub needs real-time feeds, threading, reactions - not request-response.
235
-
236
- **Recommendation:** Event-driven architecture with **WebSocket + Redis Pub/Sub + Kafka (optional)**
237
-
238
- **Hub Data Model (extends PROOF):**
239
-
240
- ```
241
- POST (thread starter):
242
- - proof_type: CLAIM
243
- - claim: "The AI decision was correct"
244
- - metadata: {
245
- "hub_type": "post",
246
- "visibility": "public" | "tenant" | "private",
247
- "attachments": ["proof:xxx", "proof:yyy"]
248
- }
249
-
250
- REPLY (thread response):
251
- - proof_type: CLAIM
252
- - previous_proof: <parent_post_id> // Thread link
253
- - metadata: {
254
- "hub_type": "reply",
255
- "thread_root": <root_post_id>
256
- }
257
-
258
- REACTION (lightweight signal):
259
- - proof_type: ATTESTATION
260
- - subject: <target_post_did>
261
- - claim: "thumbs_up" | "verified" | "disputed"
262
- - metadata: {
263
- "hub_type": "reaction"
264
- }
265
- ```
266
-
267
- **Real-Time Architecture:**
268
-
269
- ```
270
- +------------------+ +-----------------+ +------------------+
271
- | WebSocket | | Redis Pub/Sub | | Python Core |
272
- | Endpoint |<--->| |<--->| (PROOF CRUD) |
273
- +------------------+ +-----------------+ +------------------+
274
- ^ ^ |
275
- | | v
276
- | | +------------------+
277
- [Browsers] [Multiple | SQLite/Postgres |
278
- [Mobile Apps] WS Servers] +------------------+
279
- [AI Agents] |
280
- v
281
- +------------------+
282
- | Go Blockchain |
283
- +------------------+
284
- ```
285
-
286
- **Component Flow:**
287
-
288
- ```
289
- 1. CLIENT CONNECTS:
290
- Client -> WebSocket /ws/hub?token=<jwt>
291
- Server -> Validate JWT, extract tenant_id, agent_id
292
- Server -> Subscribe to Redis channels:
293
- - hub:<tenant_id>:all
294
- - hub:<tenant_id>:thread:<thread_id> (if watching thread)
295
- - hub:agent:<agent_id>:notifications
296
-
297
- 2. POST CREATION:
298
- Client -> WS message: {"type": "create_post", "data": {...}}
299
- Server -> Create PROOF via Python Core
300
- Server -> PUBLISH to Redis: hub:<tenant_id>:all
301
- All subscribers -> Receive real-time update
302
-
303
- 3. FEED DELIVERY:
304
- Redis subscriber -> WS message: {"type": "new_post", "data": {...}}
305
- Client -> Renders in feed
306
- ```
307
-
308
- **WebSocket Message Protocol:**
309
-
310
- ```json
311
- // Client -> Server
312
- {"type": "subscribe", "channel": "hub:tenant123:all"}
313
- {"type": "create_post", "data": {"claim": "...", "visibility": "public"}}
314
- {"type": "create_reply", "parent_id": "proof:xxx", "data": {...}}
315
- {"type": "react", "target_id": "proof:xxx", "reaction": "verified"}
316
-
317
- // Server -> Client
318
- {"type": "subscribed", "channel": "hub:tenant123:all"}
319
- {"type": "new_post", "data": {"proof_id": "...", "issuer": "...", ...}}
320
- {"type": "new_reply", "thread_id": "...", "data": {...}}
321
- {"type": "new_reaction", "target_id": "...", "reaction": "...", "count": 42}
322
- ```
323
-
324
- **Scaling Considerations:**
325
-
326
- | At Scale | Solution |
327
- |----------|----------|
328
- | 100 users | Single WS server, in-memory pub/sub |
329
- | 10K users | Redis Pub/Sub, multiple WS servers |
330
- | 1M users | Kafka for durability, dedicated feed service |
331
-
332
- **Confidence:** MEDIUM-HIGH (Pattern is proven, specifics need validation)
333
-
334
- **Sources:**
335
- - [InfoQ: Serverless WebSockets for Real-Time Messaging](https://www.infoq.com/articles/serverless-websockets-realtime-messaging/)
336
- - [Kafka + WebSockets + React](https://medium.com/@akshat.available/real-time-event-driven-architecture-with-kafka-websockets-and-react-b4698361e68a)
337
-
338
- ---
339
-
340
- ### Layer 4: Proof Verification Scaling
341
-
342
- **Why:** As PROOF volume grows, verification becomes bottleneck.
343
-
344
- **Recommendation:** Implement **batch verification with Merkle proofs**
345
-
346
- **Current Flow (per-proof):**
347
-
348
- ```
349
- Verify(proof_id):
350
- 1. Fetch PROOF from SQLite
351
- 2. Verify signature (Dilithium3 - slow!)
352
- 3. Verify hash matches
353
- 4. Optionally: verify_proof_on_chain (RPC to Go)
354
- ```
355
-
356
- **Scaled Flow (batch):**
357
-
358
- ```
359
- BatchVerify([proof_id1, proof_id2, ...]):
360
- 1. Fetch PROOFs from SQLite (batch query)
361
- 2. Build Merkle tree of proof_hashes
362
- 3. Verify Merkle root against chain (single RPC)
363
- 4. Return: { verified: true, merkle_root: "...", proofs: [...] }
364
- ```
365
-
366
- **Merkle Tree Integration:**
367
-
368
- ```
369
- PROOF Submission:
370
- 1. Collect PROOFs in mempool (Python Core)
371
- 2. Every N seconds OR M proofs: create batch
372
- 3. Build Merkle tree: root = hash(hash(p1) + hash(p2) + ...)
373
- 4. Submit batch to Go Blockchain (single TX with merkle_root)
374
- 5. Store merkle_proof for each PROOF
375
-
376
- PROOF Verification:
377
- 1. Client requests verify(proof_id)
378
- 2. Lookup PROOF and its merkle_proof
379
- 3. Verify merkle_proof against on-chain root
380
- 4. O(log n) verification instead of O(1) chain RPC
381
- ```
382
-
383
- **Database Schema Extension:**
384
-
385
- ```sql
386
- -- Add to proofs table
387
- ALTER TABLE proofs ADD COLUMN batch_id TEXT;
388
- ALTER TABLE proofs ADD COLUMN merkle_index INTEGER;
389
- ALTER TABLE proofs ADD COLUMN merkle_proof JSON; -- Array of sibling hashes
390
-
391
- -- New batches table
392
- CREATE TABLE proof_batches (
393
- batch_id TEXT PRIMARY KEY,
394
- merkle_root TEXT NOT NULL,
395
- chain_tx_hash TEXT,
396
- chain_height INTEGER,
397
- proof_count INTEGER,
398
- created_at INTEGER,
399
- confirmed_at INTEGER
400
- );
401
- ```
402
-
403
- **Performance Expectations:**
404
-
405
- | Metric | Per-Proof | Batched (1000 proofs) |
406
- |--------|-----------|----------------------|
407
- | Chain RPCs | 1 per proof | 1 per batch |
408
- | Verification time | ~50ms | ~5ms per proof |
409
- | Storage overhead | 0 | ~1KB merkle_proof |
410
-
411
- **Confidence:** HIGH (Merkle trees are standard, pattern from rollups)
412
-
413
- **Sources:**
414
- - [Reilabs: Scaling Sparse Merkle Trees](https://reilabs.io/blog/scaling-sparse-merkle-trees-to-billions-of-keys-with-largesmt/)
415
- - [Designing Blockchain: Merkle Trees and State Verification](https://prodsens.live/2026/01/15/designing-blockchain-4-merkle-trees-and-state-verification/)
416
-
417
- ---
418
-
419
- ## Build Order (Dependencies)
420
-
421
- **Phase 1: Foundation (Week 1-2)**
422
-
423
- ```
424
- 1. API Gateway deployment
425
- - Kong or Traefik in front of Python Core
426
- - Basic rate limiting
427
- - X-Tenant-ID routing
428
-
429
- Dependencies: None
430
- Blocks: Everything else
431
-
432
- 2. Database migration (SQLite -> PostgreSQL)
433
- - Production persistence
434
- - Connection pooling
435
-
436
- Dependencies: None
437
- Blocks: Hub, Scaling
438
- ```
439
-
440
- **Phase 2: AI Agent Auth (Week 3-4)**
441
-
442
- ```
443
- 3. OAuth2 Client Credentials
444
- - Token endpoint in Python Core
445
- - JWT generation/validation
446
-
447
- Dependencies: API Gateway
448
-
449
- 4. Agent identity lifecycle
450
- - Agent registration endpoint
451
- - Agent DID:PN creation
452
- - Delegation PROOF type
453
-
454
- Dependencies: OAuth2
455
- ```
456
-
457
- **Phase 3: Hub Core (Week 5-6)**
458
-
459
- ```
460
- 5. WebSocket endpoint
461
- - Connection handling
462
- - JWT validation on connect
463
- - Basic subscribe/publish
464
-
465
- Dependencies: Agent Auth
466
-
467
- 6. Redis Pub/Sub integration
468
- - Cross-server broadcasting
469
- - Channel management
470
-
471
- Dependencies: WebSocket endpoint
472
-
473
- 7. Hub PROOF extensions
474
- - Post/Reply/Reaction types
475
- - Thread linking
476
- - Visibility controls
477
-
478
- Dependencies: Redis Pub/Sub
479
- ```
480
-
481
- **Phase 4: Scaling (Week 7-8)**
482
-
483
- ```
484
- 8. Batch verification
485
- - Merkle tree implementation
486
- - Batch submission to chain
487
- - Merkle proof storage
488
-
489
- Dependencies: Hub Core
490
-
491
- 9. Performance optimization
492
- - Connection pooling
493
- - Query optimization
494
- - Caching layer
495
-
496
- Dependencies: Batch verification
497
- ```
498
-
499
- ---
500
-
501
- ## Anti-Patterns to Avoid
502
-
503
- ### Anti-Pattern 1: Bypassing Python Core
504
-
505
- **What:** Clients connect directly to Go Blockchain for speed
506
- **Why bad:** Loses PROOF lifecycle, consensus, DID validation
507
- **Instead:** All PROOF operations through Python Core; Go is storage layer
508
-
509
- ### Anti-Pattern 2: Stateful WebSocket Servers
510
-
511
- **What:** Storing user state in WS server memory
512
- **Why bad:** Can't scale horizontally, single point of failure
513
- **Instead:** Redis for all shared state, WS servers are stateless
514
-
515
- ### Anti-Pattern 3: Synchronous Chain Verification
516
-
517
- **What:** Calling Go Blockchain RPC in every API request
518
- **Why bad:** 50ms+ latency per call, creates bottleneck
519
- **Instead:** Batch verification, Merkle proofs, async confirmation
520
-
521
- ### Anti-Pattern 4: API Key Per-Agent
522
-
523
- **What:** Generating static API keys for each AI agent
524
- **Why bad:** No expiration, no scope, hard to revoke
525
- **Instead:** OAuth2 tokens with expiration, scopes, revocation
526
-
527
- ---
528
-
529
- ## Technology Decisions Summary
530
-
531
- | Layer | Recommended | Alternatives | Why |
532
- |-------|-------------|--------------|-----|
533
- | API Gateway | Kong | Traefik, NGINX+ | Best multi-tenant support |
534
- | AI Auth | OAuth2 + JWT | PASETO, mTLS | Industry standard, tooling |
535
- | Real-time | WebSocket + Redis | SSE, gRPC streams | Bidirectional, proven |
536
- | Message bus | Redis Pub/Sub | Kafka | Simpler ops, sufficient scale |
537
- | Batch verification | Custom Merkle | Hyperledger | Control, no extra deps |
538
- | Database | PostgreSQL | Keep SQLite | Production-grade |
539
-
540
- ---
541
-
542
- ## Confidence Assessment
543
-
544
- | Area | Level | Reason |
545
- |------|-------|--------|
546
- | API Gateway patterns | HIGH | Standard enterprise pattern, proven tools |
547
- | AI Agent auth | HIGH | OAuth2 M2M is well-documented, emerging standards |
548
- | Hub real-time | MEDIUM-HIGH | Pattern proven, specifics need tuning |
549
- | Merkle batch verification | HIGH | Standard blockchain scaling technique |
550
- | Overall integration | MEDIUM-HIGH | Existing code is clean, integration points clear |
551
-
552
- ---
553
-
554
- ## Open Questions for Phase-Specific Research
555
-
556
- 1. **Hub thread depth:** How deep can thread nesting go before UX degrades?
557
- 2. **Batch size optimization:** What's optimal batch size for Merkle trees?
558
- 3. **Agent rate limits:** Per-agent or per-owner limits for enterprise?
559
- 4. **Cross-tenant visibility:** Can agents from tenant A see tenant B posts?
560
- 5. **Offline agents:** How to handle proofs from agents that later go offline?
561
-
562
- ---
563
-
564
- ## Sources
565
-
566
- **Multi-Tenant API Patterns:**
567
- - [Kong Multi-Tenancy Guide](https://konghq.com/blog/enterprise/multi-tenancy)
568
- - [Azure API Management Multitenant](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/service/api-management)
569
- - [AWS Multi-Tenant APIs](https://aws.amazon.com/blogs/compute/managing-multi-tenant-apis-using-amazon-api-gateway/)
570
-
571
- **AI Agent Authentication:**
572
- - [Stytch: Agent-to-Agent OAuth](https://stytch.com/blog/agent-to-agent-oauth-guide/)
573
- - [Microsoft: OAuth Evolution for AI](https://techcommunity.microsoft.com/blog/microsoft-entra-blog/the-future-of-ai-agents%E2%80%94and-why-oauth-must-evolve/3827391)
574
- - [WorkOS: Securing AI Agents](https://workos.com/blog/securing-ai-agents)
575
- - [Composio: AI Agent Infrastructure Guide](https://composio.dev/blog/secure-ai-agent-infrastructure-guide)
576
-
577
- **Real-Time Architecture:**
578
- - [InfoQ: Serverless WebSockets](https://www.infoq.com/articles/serverless-websockets-realtime-messaging/)
579
- - [Kafka + WebSockets + React](https://medium.com/@akshat.available/real-time-event-driven-architecture-with-kafka-websockets-and-react-b4698361e68a)
580
- - [Event Sourcing with CQRS and WebSockets](https://resources.fenergo.com/engineering-at-fenergo/working-with-event-sourcing-cqrs-and-web-sockets-on-aws)
581
-
582
- **Merkle Tree Scaling:**
583
- - [Reilabs: LargeSMT](https://reilabs.io/blog/scaling-sparse-merkle-trees-to-billions-of-keys-with-largesmt/)
584
- - [Designing Blockchain: Merkle Trees](https://prodsens.live/2026/01/15/designing-blockchain-4-merkle-trees-and-state-verification/)
585
- - [Adaptive Merkle Trees (ScienceDirect)](https://www.sciencedirect.com/science/article/pii/S2542660524002567)