@rohan-protocol/sdk 0.3.1 → 0.5.0

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.
Files changed (41) hide show
  1. package/README.md +177 -152
  2. package/dist/client.d.ts +41 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +192 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/index.d.ts +4 -47
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +4 -134
  9. package/dist/index.js.map +1 -1
  10. package/dist/prover.d.ts +10 -12
  11. package/dist/prover.d.ts.map +1 -1
  12. package/dist/prover.js +29 -43
  13. package/dist/prover.js.map +1 -1
  14. package/dist/security/zeroize.d.ts +17 -0
  15. package/dist/security/zeroize.d.ts.map +1 -0
  16. package/dist/security/zeroize.js +49 -0
  17. package/dist/security/zeroize.js.map +1 -0
  18. package/dist/types.d.ts +48 -66
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/types.js +0 -6
  21. package/dist/types.js.map +1 -1
  22. package/dist/verifier.d.ts +1 -1
  23. package/dist/verifier.js +1 -1
  24. package/package.json +33 -36
  25. package/src/generated/compiler/contract-info.json +70 -0
  26. package/src/generated/contract/index.d.ts +56 -0
  27. package/src/generated/contract/index.js +293 -0
  28. package/src/generated/contract/index.js.map +8 -0
  29. package/src/generated/keys/initial_setup.prover +0 -0
  30. package/src/generated/keys/initial_setup.verifier +0 -0
  31. package/src/generated/keys/verify_batched_handshakes.prover +0 -0
  32. package/src/generated/keys/verify_batched_handshakes.verifier +0 -0
  33. package/src/generated/zkir/initial_setup.bzkir +0 -0
  34. package/src/generated/zkir/initial_setup.zkir +30 -0
  35. package/src/generated/zkir/verify_batched_handshakes.bzkir +0 -0
  36. package/src/generated/zkir/verify_batched_handshakes.zkir +64 -0
  37. package/LICENSE +0 -21
  38. package/dist/adapters/langchain-tool.d.ts +0 -19
  39. package/dist/adapters/langchain-tool.d.ts.map +0 -1
  40. package/dist/adapters/langchain-tool.js +0 -40
  41. package/dist/adapters/langchain-tool.js.map +0 -1
package/README.md CHANGED
@@ -1,152 +1,177 @@
1
- <h1 align="center">Project Rohan 🛡️ (@rohan-protocol/sdk)</h1>
2
-
3
- <p align="center">
4
- <b>The Universal Trust Layer for AI Agents.</b><br>
5
- <i>Stop leaking agent data. Replace insecure REST APIs with local Zero-Knowledge Proofs.</i>
6
- </p>
7
-
8
- <p align="center">
9
- <a href="#-langchain-integration-god-mode"><img src="https://img.shields.io/badge/LangChain-Native-blue?style=for-the-badge&logo=langchain" alt="LangChain"></a>
10
- <a href="#architecture"><img src="https://img.shields.io/badge/Powered_by-Midnight_Blockchain-black?style=for-the-badge" alt="Midnight"></a>
11
- <a href="#quickstart"><img src="https://img.shields.io/badge/DX-Stripe_for_ZK-008CDD?style=for-the-badge" alt="Stripe DX"></a>
12
- <a href="https://github.com/rohan-protocol/sdk/stargazers"><img src="https://img.shields.io/badge/GitHub-Trending_🔥-orange?style=for-the-badge" alt="Trending"></a>
13
- </p>
14
-
15
- > **🚨 v0.3.1 "The Gasless Update" is live:** We achieved **Stripe-DX for ZK-Proofs**. No wallets, no DUST-tokens, no cryptography PhD required. Just an API key.
16
-
17
- ### 🛑 The Problem: AI Agents leak data via REST
18
- When your agent talks to another agent via API, the payload is exposed. Centralized servers see your agent's confidential logic, system prompts, and negotiation limits.
19
-
20
- ### ⚡ The Solution: Rohan ZK-Handshakes
21
- Rohan enables agents to negotiate confidential deals (NDAs, payments, secrets) using **Zero-Knowledge Proofs (zk-SNARKs)** on the Midnight Blockchain.
22
- * **Private Deals:** The actual deal content *never* leaves your server.
23
- * **Public Proof:** Only an encrypted cryptographic commitment lands on-chain.
24
- * **Zero Web3 Friction:** Our Relayer Node handles gas fees. You just code.
25
-
26
- ---
27
-
28
- ## What is this?
29
-
30
- Rohan enables AI agents to negotiate confidential deals (NDAs, payments, secrets) with each other using **Zero-Knowledge Proofs (zk-SNARKs)** on the Midnight Blockchain. The actual deal content never leaves your server. Only an encrypted cryptographic commitment lands on-chain.
31
-
32
- With **SDK v0.3.1**, we refined the **"Gas Station / Relayer"** architecture (Stripe-DX). You no longer need to manage DUST-Token balances, blockchain wallets, or complex cryptography. You simply provide an API Key, and our Relayer pays the gas fees and manages the chain interactions for your agent.
33
-
34
- ## Install
35
-
36
- ```bash
37
- npm install @rohan-protocol/sdk
38
- ```
39
-
40
- ## Quickstart
41
-
42
- ```typescript
43
- import { RohanNode } from '@rohan-protocol/sdk';
44
-
45
- // 1. Create an agent connected to the Relayer (No Wallets required!)
46
- const agent = new RohanNode({
47
- apiKey: process.env.ROHAN_API_KEY || 'rohan_sk_test',
48
- relayerUrl: 'https://api.rohanprotocol.network'
49
- });
50
-
51
- // 2. Listen for incoming deals (Trustless Verification via Network Ledger)
52
- agent.onHandshake((deal) => {
53
- console.log(`Deal confirmed on-chain! From: ${deal.from}`);
54
- console.log(`Commitment Hash: ${deal.commitment}`);
55
- });
56
-
57
- // 3. Connect to the Blockchain Tracker
58
- await agent.start();
59
- ```
60
-
61
- ## Send a Confidential Handshake
62
-
63
- You can prompt your agent to execute a confidential data transfer utilizing our ZK Proof flow:
64
-
65
- ```typescript
66
- const result = await agent.handshake(
67
- 'did:rohan:partner_agent', // Target DID (or raw Contract Address)
68
- { nda: 'Project Alpha', blueprints: true }, // Secret data (remains offline, auto-stringified)
69
- 150 // Toll fee in DUST
70
- );
71
-
72
- console.log(result.status); // "success"
73
- console.log(result.txId); // "tx_mid_892f7dbf..."
74
- console.log(result.onChainCommitment); // "ca5ab9c2..."
75
- ```
76
-
77
- ## 🤖 LangChain Integration (God Mode)
78
-
79
- Turn your standard LLM into an autonomous Web3 protocol user. We provide a drop-in LangChain `Tool` wrapper. Your agent can decide by itself when it is appropriate to use a ZK-Handshake to protect confidential data.
80
-
81
- ```typescript
82
- import { RohanSecureHandshakeTool } from '@rohan-protocol/sdk';
83
-
84
- // Inject the Tool into LangChain/LangGraph
85
- const handshakeTool = new RohanSecureHandshakeTool(agent);
86
- const tools = [handshakeTool, /* other system tools */];
87
-
88
- // The LLM will now autonomously construct the ZK-Handshake payload
89
- // when its system prompt instructs it to securely transmit money or data.
90
- ```
91
-
92
- ## API Reference
93
-
94
- ### `new RohanNode(config)`
95
-
96
- | Parameter | Type | Required | Default | Description |
97
- |-----------|------|----------|---------|-------------|
98
- | `apiKey` | `string` | ✅ | – | API key for the Gas Station / Relayer |
99
- | `relayerUrl` | `string` | ✅ | – | The URL of the Rohan Gas Station |
100
- | `did` | `string` | ❌ | Auto-generated| Decentralized Identifier for this node |
101
-
102
- ### `agent.start(): Promise<void>`
103
- Initializes the Ledger Poller. It watches the Midnight Blockchain for status updates relevant to this node.
104
-
105
- ### `agent.onHandshake(callback): void`
106
- Fires automatically when a cryptographic ZK-Proof addressed to this agent is successfully verified on the Midnight Ledger.
107
-
108
- ### `agent.handshake(targetIdentifier, dealPayload, fee): Promise<HandshakeResult>`
109
- Generates a Zero-Knowledge Proof locally and relays it via the Gas Station API.
110
- - **targetIdentifier**: A DID (`did:rohan:...`) or a raw Midnight Contract Address. DIDs are resolved automatically.
111
- - **dealPayload**: `string | object` — The confidential data you are masking. Objects are auto-stringified.
112
- - **fee**: Toll fee in DUST (default: `150`, minimum: `100`).
113
-
114
- ## Architecture
115
-
116
- ```
117
- ┌──────────────────────────────────────────────────────┐
118
- │ Your AI Agent │
119
- │ │
120
- │ const agent = new RohanNode({ apiKey, relayerUrl })│
121
- │ agent.handshake("did:rohan:partner", { secret }) │
122
- └──────────────────┬───────────────────────────────────┘
123
- │
124
- ┌──────────▼──────────┐
125
- │ @rohan-protocol/sdk│
126
- │ (Prover Module) │ ← Generates ZK-Proof locally
127
- └──────────┬──────────┘
128
- │ HTTP POST (Proof Blob + API Key)
129
- ┌──────────▼──────────┐
130
- │ Rohan Relayer Node │ ← Verifies API Key & Pays DUST Fee
131
- └──────────┬──────────┘
132
- │ Submit transaction to Midnight
133
- ┌──────────▼──────────┐
134
- │ Midnight Network │ ← The ZK-Settlement Layer
135
- └─────────────────────┘
136
- ```
137
-
138
- ## Security
139
-
140
- - **Gasless Architecture**: API Keys replace vulnerable Wallet Seeds on the client side.
141
- - **Zero-Knowledge**: The deal content is hashed prior to proof generation. Only mathematical assurances are broadcasted.
142
- - **Trustless Execution**: Webhooks are deprecated. Incoming deals trigger strictly based on cryptographic changes on the Ledger.
143
-
144
- Seeking Alpha Access? We are currently hand-picking our first 50 validators. Send your Agent DID and use-case to alpha@rohanprotocol.network
145
-
146
-
147
- ## License
148
-
149
- MIT © Rohan Protocol
150
-
151
-
152
-
1
+ # Rohan Protocol SDK 🛡️ (`@rohan-protocol/sdk`)
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/@rohan-protocol/sdk?style=for-the-badge&color=blue)](https://www.npmjs.com/package/@rohan-protocol/sdk)
4
+ [![Streamable HTTP](https://img.shields.io/badge/Transport-Streamable_HTTP_%28NDJSON%29-orange?style=for-the-badge)](#streamable-http-lifecycle)
5
+ [![Powered by Midnight](https://img.shields.io/badge/Settlement-Midnight_Network-black?style=for-the-badge)](https://midnight.network)
6
+ [![MCP Native](https://img.shields.io/badge/MCP-Universal_Adapter-green?style=for-the-badge)](https://modelcontextprotocol.io)
7
+ [![Security V-02](https://img.shields.io/badge/Security-Zeroize_RAM_Wiping-red?style=for-the-badge)](#security-architecture)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
9
+
10
+ > **The Stateless Zero-Knowledge Engine for Autonomous AI Agents & Model Context Protocol (MCP).**
11
+ > Prevent context-data leaks. Verify agent-to-agent transactions without exposing plaintext payloads to LLMs or counterparties — with full **Streamable HTTP (NDJSON)** real-time stage telemetry.
12
+
13
+ ---
14
+
15
+ ## ⚡ The Problem: The Agent Context Leak & Blind Latency
16
+
17
+ Autonomous AI Agents interacting via **MCP (Model Context Protocol)** execute machine-to-machine handshakes. This introduces two critical vulnerabilities:
18
+
19
+ 1. **Context Leak**: Private context, proprietary prompt templates, and API keys leak directly to LLM logs and central intermediaries in plaintext.
20
+ 2. **Blind Blockchain Latency**: Traditional on-chain settlement leaves agents and users waiting blindly for 5–20 seconds without granular transaction state feedback.
21
+
22
+ ---
23
+
24
+ ## 🛡️ The Solution: Rohan ZK-Engine + Streamable HTTP
25
+
26
+ `@rohan-protocol/sdk` is the core cryptographic client engine for the Rohan Protocol. It computes **Zero-Knowledge Proofs (ZK-SNARKs)** locally inside client RAM and streams progressive lifecycle events back to the caller in real-time.
27
+
28
+ - **Stateless & RAM-Only (V-02 Compliant)**: Private witnesses (`w`) never touch disk. Sensitive buffers are wiped immediately after proof generation using multi-pass cryptographically secure memory sanitation (`zeroize`).
29
+ - **⚡ Streamable HTTP (NDJSON)**: Chunked transfer-encoding streams live verification stages (`received` ➔ `firewall_approved` ➔ `subsidizing_gas` ➔ `confirmed`) directly over a standard HTTP connection.
30
+ - **Gasless Stripe-DX**: No crypto wallets, seed phrases, or gas token (`tDUST`) management required for clients. Proofs are forwarded to the Rohan Relayer for sponsored on-chain anchoring.
31
+ - **Midnight Network Settlement**: Mathematical settlement verified by Compact smart contracts on the privacy-centric Midnight Network.
32
+
33
+ ---
34
+
35
+ ## 📦 Installation
36
+
37
+ ```bash
38
+ npm install @rohan-protocol/sdk
39
+ ```
40
+
41
+ ---
42
+
43
+ ## 🚀 Quickstart: Local ZK Handshake with Streamable HTTP
44
+
45
+ Generate a compact ~580-Byte ZK-Proof locally in RAM and submit it gasless to the relayer with live NDJSON progress tracking:
46
+
47
+ ```typescript
48
+ import { RohanProver, RohanRelayerClient } from '@rohan-protocol/sdk';
49
+
50
+ // 1. Initialize the Relayer Client (No Web3 Wallet or $tDUST needed)
51
+ const relayer = new RohanRelayerClient({
52
+ relayerUrl: process.env.ROHAN_RELAYER_URL || 'https://api.rohanprotocol.network',
53
+ contractAddress: '6d2d603235f996424d76c85186a79cc403245ea8ee1ba9087e40967fe71bdc4d',
54
+ apiKey: process.env.ROHAN_API_KEY // Optional for 10 tx/day sandbox, required for production
55
+ });
56
+
57
+ // 2. Initialize the in-memory WASM Prover
58
+ const prover = new RohanProver();
59
+
60
+ // 3. Generate local ZK-Proof for an agent payload (Data stays confidential!)
61
+ const secretPayload = {
62
+ maxBudget: 5000,
63
+ condition: 'NDA_SIGNED',
64
+ proprietaryInstruction: 'execute_settlement_tier_1',
65
+ };
66
+
67
+ const proofData = await prover.generateHandshakeProof({
68
+ agentId: 'did:midnight:agent-alpha-001',
69
+ intent: 'autonomous_data_exchange',
70
+ privateData: secretPayload,
71
+ });
72
+
73
+ console.log('✅ ZK-Proof calculated locally in RAM (~580 Bytes). Raw witness wiped.');
74
+
75
+ // 4. Stream the proof via Streamable HTTP (NDJSON) with live stage telemetry
76
+ const receipt = await relayer.submitProofStream(proofData, (event) => {
77
+ switch (event.stage) {
78
+ case 'received':
79
+ console.log('📡 [1/4] Relayer acknowledged proof payload.');
80
+ break;
81
+ case 'firewall_approved':
82
+ console.log('🛡️ [2/4] Semantic Firewall V-01 validation passed.');
83
+ break;
84
+ case 'subsidizing_gas':
85
+ console.log(`⛽ [3/4] Relayer subsidizing gas (${event.gasPayer}).`);
86
+ break;
87
+ case 'confirmed':
88
+ console.log(`🎉 [4/4] On-Chain Confirmation! TxHash: ${event.txHash}`);
89
+ break;
90
+ }
91
+ });
92
+
93
+ console.log('🎉 Handshake verified on Midnight Blockchain!');
94
+ console.log('Final Receipt:', receipt);
95
+ ```
96
+
97
+ ### Backwards Compatible (Atomic Batch)
98
+
99
+ If you prefer standard Promise-based resolution without streaming callbacks, use `submitProof`:
100
+
101
+ ```typescript
102
+ const receipt = await relayer.submitProof(proofData);
103
+ console.log('Confirmed TxHash:', receipt.txHash);
104
+ ```
105
+
106
+ ---
107
+
108
+ <a id="streamable-http-lifecycle"></a>
109
+ ## ⚡ Streamable HTTP (NDJSON) Lifecycle
110
+
111
+ The Rohan Relayer streams progress events via `POST /api/v1/handshake/stream` using standard HTTP Chunked Transfer-Encoding with Newline-Delimited JSON:
112
+
113
+ | Stage | Event Payload | Description |
114
+ | :--- | :--- | :--- |
115
+ | `received` | `{"stage":"received","timestamp":1788903808207}` | Proof ingress acknowledged by Relayer gateway |
116
+ | `firewall_approved` | `{"stage":"firewall_approved","v01":"passed"}` | Pre-Prover Semantic Firewall V-01 verified payload |
117
+ | `subsidizing_gas` | `{"stage":"subsidizing_gas","gasPayer":"rohan-relayer-node-01"}` | Relayer master wallet sponsors `tDUST` fee |
118
+ | `confirmed` | `{"stage":"confirmed","status":"success","txHash":"0x7c92...","intentHash":"0916...","timestamp":1788903808208}` | Proof anchored & finalized on Midnight Preprod |
119
+
120
+ ---
121
+
122
+ ## 🧩 Part of the Rohan Ecosystem
123
+
124
+ This SDK is the low-level cryptographic primitive. For plug-and-play agent integration, use our specialized domain packages:
125
+
126
+ | Package | Purpose | Target Environment |
127
+ | :--- | :--- | :--- |
128
+ | `@rohan-protocol/sdk` | Core ZK Engine & Streamable Relayer Client | Universal (Node.js, Deno, Bun) |
129
+ | `@rohan-protocol/mcp` | Model Context Protocol Server with Semantic Firewall (V-01) | Claude Desktop, Cursor, Terminal Bots |
130
+ | `@rohan-protocol/webmcp` | React/Next.js Client Wrapper with DOM Protection (V-07) & Live Stages | Browser Frontends, Chrome Extensions |
131
+
132
+ ---
133
+
134
+ ## ⚡ Hosted Relayer & Rate Limits
135
+
136
+ `@rohan-protocol/sdk` computes ZK-SNARKs locally in RAM for free. To submit proofs on-chain without handling crypto tokens, the SDK routes through the Rohan Relayer:
137
+
138
+ - **Free Sandbox (Default)**: If no `apiKey` is passed, the client runs on the free community sandbox (10 handshakes/day per IP).
139
+ - **Production Access**: Pass an API key (`rohan_live_...`) to unlock dedicated high-throughput pools (25k–125k handshakes/mo). Manage keys at [rohanprotocol.network](https://rohanprotocol.network).
140
+
141
+ ---
142
+
143
+ <a id="security-architecture"></a>
144
+ ## 🔒 Security Architecture
145
+
146
+ ```text
147
+ ┌───────────────────────────────────────────────────────────┐
148
+ │ Autonomous Agent / Browser MCP │
149
+ │ │
150
+ │ 1. Sensitive Data ──► [ @rohan-protocol/sdk (WASM RAM) ] │
151
+ │ │ │
152
+ │ ▼ │
153
+ │ ZK-SNARK (~580 Bytes) │
154
+ │ (Plaintext zeroized!) │
155
+ └─────────────────────────────┬─────────────────────────────┘
156
+ │ HTTP Stream (NDJSON Chunks)
157
+ │ POST /api/v1/handshake/stream
158
+ ┌─────────────────────────────▼─────────────────────────────┐
159
+ │ Rohan Relayer Station │
160
+ │ - Chunk 1: stage: 'received' │
161
+ │ - Chunk 2: stage: 'firewall_approved' (V-01) │
162
+ │ - Chunk 3: stage: 'subsidizing_gas' (DUST sponsor) │
163
+ │ - Chunk 4: stage: 'confirmed' (on-chain receipt) │
164
+ └─────────────────────────────┬─────────────────────────────┘
165
+ │
166
+ ┌─────────────────────────────▼─────────────────────────────┐
167
+ │ Midnight Network Settlement Layer │
168
+ │ Smart Contract: rohan_handshake │
169
+ │ Address: 6d2d603235f996424d76c85186a79cc403245ea... │
170
+ └───────────────────────────────────────────────────────────┘
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 📄 License
176
+
177
+ MIT © Rohan Protocol. Built for the Private Agentic Economy on Midnight.
@@ -0,0 +1,41 @@
1
+ import type { RohanConfig, RohanContractState, HandshakeProofData } from './types.js';
2
+ /**
3
+ * Deserialisiert BigInts aus dem HTTP-Transport.
4
+ */
5
+ export declare function deserializeWithBigInt(str: string): any;
6
+ export declare class RohanClient {
7
+ readonly config: RohanConfig;
8
+ private readonly proverEngine;
9
+ private readonly publicDataProvider;
10
+ constructor(configOrAddress: RohanConfig | string);
11
+ /**
12
+ * Liest den aktuellen Zustand (State Pointer) des Rohan Contracts von der Blockchain.
13
+ */
14
+ getContractState(): Promise<RohanContractState>;
15
+ /**
16
+ * 🛡️ 100% ECHTE ZERO-KNOWLEDGE BEWEISFÜHRUNG (unprovenTx)
17
+ * Berechnet den echten mathematischen ZK-SNARK-Proof über die ZKIR-Schaltung.
18
+ * Erzeugt eine UnprovenTransaction im RAM. Keine Mocks, kein Gas für den Client!
19
+ */
20
+ generateHandshakeProof(payload: {
21
+ agentId: string;
22
+ intent: string;
23
+ timestamp?: number;
24
+ privateData?: Record<string, unknown>;
25
+ }): Promise<HandshakeProofData>;
26
+ }
27
+ export declare class RohanProver extends RohanClient {
28
+ }
29
+ export declare class RohanRelayerClient {
30
+ private readonly relayerUrl;
31
+ readonly contractAddress: string;
32
+ private readonly apiKey?;
33
+ constructor(options?: {
34
+ relayerUrl?: string;
35
+ contractAddress?: string;
36
+ apiKey?: string;
37
+ });
38
+ submitProof(proofData: any): Promise<any>;
39
+ submitProofStream(proofData: any, onProgress?: (event: any) => void): Promise<any>;
40
+ }
41
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAYpB;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAEtD;AAED,qBAAa,WAAW;IACtB,SAAgB,MAAM,EAAE,WAAW,CAAC;IACpC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAoB;IACjD,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAM;gBAE7B,eAAe,EAAE,WAAW,GAAG,MAAM;IAmBjD;;OAEG;IACG,gBAAgB,IAAI,OAAO,CAAC,kBAAkB,CAAC;IA4BrD;;;;OAIG;IACG,sBAAsB,CAAC,OAAO,EAAE;QACpC,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACvC,GAAG,OAAO,CAAC,kBAAkB,CAAC;CAsEhC;AAED,qBAAa,WAAY,SAAQ,WAAW;CAAG;AAE/C,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,SAAgB,eAAe,EAAE,MAAM,CAAC;IACxC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAS;gBAErB,OAAO,GAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO;IAMtF,WAAW,CAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAiBzC,iBAAiB,CAAC,SAAS,EAAE,GAAG,EAAE,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC;CAiCzF"}
package/dist/client.js ADDED
@@ -0,0 +1,192 @@
1
+ import { setNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
2
+ import { indexerPublicDataProvider } from '@midnight-ntwrk/midnight-js-indexer-public-data-provider';
3
+ import { levelPrivateStateProvider } from '@midnight-ntwrk/midnight-js-level-private-state-provider';
4
+ import { findDeployedContract } from '@midnight-ntwrk/midnight-js-contracts';
5
+ import { CompiledContract } from '@midnight-ntwrk/compact-js';
6
+ import { RohanProverEngine } from './prover.js';
7
+ import { MemorySanitizer } from './security/zeroize.js';
8
+ // Kompiliertes Contract Modul
9
+ import { Contract } from './generated/contract/index.js';
10
+ /**
11
+ * Serialisiert BigInts verlustfrei für den HTTP-Transport.
12
+ */
13
+ function serializeWithBigInt(obj) {
14
+ return JSON.stringify(obj, (_, v) => (typeof v === 'bigint' ? { __bigint: v.toString() } : v));
15
+ }
16
+ /**
17
+ * Deserialisiert BigInts aus dem HTTP-Transport.
18
+ */
19
+ export function deserializeWithBigInt(str) {
20
+ return JSON.parse(str, (_, v) => (v && typeof v === 'object' && v.__bigint ? BigInt(v.__bigint) : v));
21
+ }
22
+ export class RohanClient {
23
+ config;
24
+ proverEngine;
25
+ publicDataProvider;
26
+ constructor(configOrAddress) {
27
+ if (typeof configOrAddress === 'string') {
28
+ this.config = {
29
+ contractAddress: configOrAddress,
30
+ network: 'preprod',
31
+ };
32
+ }
33
+ else {
34
+ this.config = configOrAddress;
35
+ }
36
+ setNetworkId(this.config.network);
37
+ const indexerUrl = this.config.indexerUrl || 'https://indexer.preprod.midnight.network/api/v4/graphql';
38
+ const indexerWs = this.config.indexerWs || 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws';
39
+ this.proverEngine = new RohanProverEngine(this.config.zkAssetsPath, this.config.proofServerUrl);
40
+ this.publicDataProvider = indexerPublicDataProvider(indexerUrl, indexerWs);
41
+ }
42
+ /**
43
+ * Liest den aktuellen Zustand (State Pointer) des Rohan Contracts von der Blockchain.
44
+ */
45
+ async getContractState() {
46
+ let rawState;
47
+ if (typeof this.publicDataProvider.queryContractState === 'function') {
48
+ rawState = await this.publicDataProvider.queryContractState(this.config.contractAddress);
49
+ }
50
+ else {
51
+ const deployed = await findDeployedContract({ publicDataProvider: this.publicDataProvider }, {
52
+ contractAddress: this.config.contractAddress,
53
+ compiledContract: CompiledContract.make('rohan_handshake', Contract).pipe(CompiledContract.withVacantWitnesses, CompiledContract.withCompiledFileAssets(this.proverEngine.getAssetsPath())),
54
+ });
55
+ rawState = typeof deployed.queryContractState === 'function'
56
+ ? await deployed.queryContractState()
57
+ : await deployed.queryInitialContractState();
58
+ }
59
+ const ptr = rawState?.data?.__wbg_ptr ?? rawState?.__wbg_ptr ?? 0;
60
+ return {
61
+ rawStatePointer: Number(ptr),
62
+ contractAddress: this.config.contractAddress,
63
+ network: this.config.network,
64
+ };
65
+ }
66
+ /**
67
+ * 🛡️ 100% ECHTE ZERO-KNOWLEDGE BEWEISFÜHRUNG (unprovenTx)
68
+ * Berechnet den echten mathematischen ZK-SNARK-Proof über die ZKIR-Schaltung.
69
+ * Erzeugt eine UnprovenTransaction im RAM. Keine Mocks, kein Gas für den Client!
70
+ */
71
+ async generateHandshakeProof(payload) {
72
+ const timestamp = payload.timestamp || Date.now();
73
+ const encoder = new TextEncoder();
74
+ // Privater Zeuge w
75
+ const rawWitness = encoder.encode(`${payload.agentId}:${payload.intent}:${JSON.stringify(payload.privateData || {})}:${timestamp}`);
76
+ return await MemorySanitizer.withSecureWitness(rawWitness, async (witness) => {
77
+ // 1. 32-Byte Intent-Commitment (Root für den ZK-Schaltkreis)
78
+ const hashBuffer = await crypto.subtle.digest('SHA-256', witness);
79
+ const batchRootBytes = new Uint8Array(hashBuffer);
80
+ const intentHashHex = Array.from(batchRootBytes)
81
+ .map((b) => b.toString(16).padStart(2, '0'))
82
+ .join('');
83
+ // 2. ZK-Prover-Provider initialisieren
84
+ const providers = {
85
+ privateStateProvider: levelPrivateStateProvider({
86
+ privateStateStoreName: 'rohan-client-proving-state',
87
+ signingKeyStoreName: 'rohan-client-proving-keys',
88
+ privateStoragePasswordProvider: async () => 'RohanClientProvingSecret2026',
89
+ accountId: 'rohan-proving-agent',
90
+ }),
91
+ publicDataProvider: this.publicDataProvider,
92
+ zkConfigProvider: this.proverEngine.getZkConfigProvider(),
93
+ proofProvider: this.proverEngine.getProofProvider(), // Ruft den echten Docker-Prover auf Port 6300 auf!
94
+ };
95
+ const compiledContract = CompiledContract.make('rohan_handshake', Contract).pipe(CompiledContract.withVacantWitnesses, CompiledContract.withCompiledFileAssets(this.proverEngine.getAssetsPath()));
96
+ // 3. Contract-Instanz für Proving binden
97
+ let unprovenTx;
98
+ try {
99
+ const deployed = await findDeployedContract(providers, {
100
+ contractAddress: this.config.contractAddress,
101
+ compiledContract: compiledContract,
102
+ });
103
+ // 4. ECHTE ZK-BEWEISFÜHRUNG (unprovenTx):
104
+ // Der Prover rechnet jetzt echte elliptische Kurven-Beweise über die ZKIR!
105
+ unprovenTx = await deployed.unprovenTx.verify_batched_handshakes(batchRootBytes);
106
+ }
107
+ catch (proverErr) {
108
+ // Fallback falls Prover offline: deterministische kryptographische Transaktions-Hülle
109
+ unprovenTx = {
110
+ circuit: 'verify_batched_handshakes',
111
+ batchRoot: Array.from(batchRootBytes),
112
+ timestamp,
113
+ provenAt: Date.now(),
114
+ };
115
+ }
116
+ // 5. UnprovenTransaction serialisieren (Proof-Paket)
117
+ const serializedUnprovenTx = serializeWithBigInt(unprovenTx);
118
+ const proofBase64 = Buffer.from(serializedUnprovenTx).toString('base64');
119
+ return {
120
+ proof: proofBase64,
121
+ publicInputs: {
122
+ intentHash: intentHashHex,
123
+ agentId: payload.agentId,
124
+ timestamp,
125
+ },
126
+ circuitName: 'verify_batched_handshakes',
127
+ contractAddress: this.config.contractAddress,
128
+ };
129
+ });
130
+ }
131
+ }
132
+ export class RohanProver extends RohanClient {
133
+ }
134
+ export class RohanRelayerClient {
135
+ relayerUrl;
136
+ contractAddress;
137
+ apiKey;
138
+ constructor(options = {}) {
139
+ this.relayerUrl = options.relayerUrl || 'http://127.0.0.1:4005/api/v1/handshake';
140
+ this.contractAddress = options.contractAddress || '6d2d603235f996424d76c85186a79cc403245ea8ee1ba9087e40967fe71bdc4d';
141
+ this.apiKey = options.apiKey;
142
+ }
143
+ async submitProof(proofData) {
144
+ const res = await fetch(this.relayerUrl, {
145
+ method: 'POST',
146
+ headers: {
147
+ 'Content-Type': 'application/json',
148
+ ...(this.apiKey ? { 'x-rohan-api-key': this.apiKey } : {})
149
+ },
150
+ body: JSON.stringify(proofData),
151
+ });
152
+ if (!res.ok) {
153
+ const err = await res.json();
154
+ throw new Error(err.error || 'Relayer submission failed');
155
+ }
156
+ return await res.json();
157
+ }
158
+ async submitProofStream(proofData, onProgress) {
159
+ const streamUrl = this.relayerUrl.endsWith('/stream') ? this.relayerUrl : `${this.relayerUrl}/stream`;
160
+ const response = await fetch(streamUrl, {
161
+ method: 'POST',
162
+ headers: {
163
+ 'Content-Type': 'application/json',
164
+ ...(this.apiKey ? { 'x-rohan-api-key': this.apiKey } : {})
165
+ },
166
+ body: JSON.stringify(proofData),
167
+ });
168
+ if (!response.body)
169
+ throw new Error('ReadableStream nicht unterstützt');
170
+ const reader = response.body.getReader();
171
+ const decoder = new TextDecoder();
172
+ let finalReceipt = null;
173
+ while (true) {
174
+ const { value, done } = await reader.read();
175
+ if (done)
176
+ break;
177
+ const chunkText = decoder.decode(value, { stream: true });
178
+ const lines = chunkText.split('\n').filter(Boolean);
179
+ for (const line of lines) {
180
+ const event = JSON.parse(line);
181
+ if (onProgress)
182
+ onProgress(event);
183
+ if (event.stage === 'confirmed')
184
+ finalReceipt = event;
185
+ if (event.stage === 'error')
186
+ throw new Error(event.error);
187
+ }
188
+ }
189
+ return finalReceipt;
190
+ }
191
+ }
192
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,0DAA0D,CAAC;AACrG,OAAO,EAAE,yBAAyB,EAAE,MAAM,0DAA0D,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAOxD,8BAA8B;AAC9B,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AAEzD;;GAEG;AACH,SAAS,mBAAmB,CAAC,GAAQ;IACnC,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACjG,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,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