@sip-protocol/sdk 0.1.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.
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Mock Proof Provider
3
+ *
4
+ * ⚠️ WARNING: FOR TESTING ONLY - DO NOT USE IN PRODUCTION ⚠️
5
+ *
6
+ * This provider generates fake proofs that provide NO cryptographic guarantees.
7
+ * It is intended solely for:
8
+ * - Unit testing
9
+ * - Integration testing
10
+ * - Development/debugging
11
+ *
12
+ * The mock proofs are clearly marked and will be rejected by any real verifier.
13
+ */
14
+
15
+ import type { ZKProof, HexString } from '@sip-protocol/types'
16
+ import { sha256 } from '@noble/hashes/sha256'
17
+ import { bytesToHex, randomBytes } from '@noble/hashes/utils'
18
+ import type {
19
+ ProofProvider,
20
+ ProofFramework,
21
+ FundingProofParams,
22
+ ValidityProofParams,
23
+ FulfillmentProofParams,
24
+ ProofResult,
25
+ } from './interface'
26
+ import { ProofGenerationError } from './interface'
27
+ import { ProofError, ErrorCode } from '../errors'
28
+
29
+ /**
30
+ * Mock proof marker - all mock proofs start with this prefix
31
+ * This allows easy identification of mock proofs
32
+ */
33
+ const MOCK_PROOF_PREFIX = '0x4d4f434b' // "MOCK" in hex
34
+
35
+ /**
36
+ * Console warning message for mock provider usage
37
+ */
38
+ const WARNING_MESSAGE = `
39
+ ╔══════════════════════════════════════════════════════════════╗
40
+ ║ ⚠️ MOCK PROOF PROVIDER - NOT FOR PRODUCTION USE ⚠️ ║
41
+ ║ ║
42
+ ║ Mock proofs provide NO cryptographic security guarantees. ║
43
+ ║ Use NoirProofProvider for production deployments. ║
44
+ ╚══════════════════════════════════════════════════════════════╝
45
+ `
46
+
47
+ /**
48
+ * Mock Proof Provider for testing
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * // Only use in tests
53
+ * const provider = new MockProofProvider()
54
+ * await provider.initialize()
55
+ *
56
+ * const result = await provider.generateFundingProof({
57
+ * balance: 100n,
58
+ * minimumRequired: 50n,
59
+ * // ... other params
60
+ * })
61
+ * ```
62
+ */
63
+ export class MockProofProvider implements ProofProvider {
64
+ readonly framework: ProofFramework = 'mock'
65
+ private _isReady = false
66
+ private _warningShown = false
67
+
68
+ get isReady(): boolean {
69
+ return this._isReady
70
+ }
71
+
72
+ /**
73
+ * Initialize the mock provider
74
+ *
75
+ * Logs a warning to console about mock usage.
76
+ */
77
+ async initialize(): Promise<void> {
78
+ if (!this._warningShown) {
79
+ console.warn(WARNING_MESSAGE)
80
+ this._warningShown = true
81
+ }
82
+ this._isReady = true
83
+ }
84
+
85
+ /**
86
+ * Generate a mock funding proof
87
+ *
88
+ * ⚠️ This proof provides NO cryptographic guarantees!
89
+ */
90
+ async generateFundingProof(params: FundingProofParams): Promise<ProofResult> {
91
+ this.ensureReady()
92
+
93
+ // Validate parameters (actual validation, not cryptographic)
94
+ if (params.balance < params.minimumRequired) {
95
+ throw new ProofGenerationError(
96
+ 'funding',
97
+ 'Balance is less than minimum required',
98
+ )
99
+ }
100
+
101
+ // Generate deterministic mock proof
102
+ const proofData = this.generateMockProofData('funding', params)
103
+
104
+ return {
105
+ proof: {
106
+ type: 'funding',
107
+ proof: proofData,
108
+ publicInputs: [
109
+ this.hashToHex(params.assetId),
110
+ `0x${params.minimumRequired.toString(16).padStart(16, '0')}`,
111
+ ],
112
+ },
113
+ publicInputs: [
114
+ this.hashToHex(params.assetId),
115
+ `0x${params.minimumRequired.toString(16).padStart(16, '0')}`,
116
+ ],
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Generate a mock validity proof
122
+ *
123
+ * ⚠️ This proof provides NO cryptographic guarantees!
124
+ */
125
+ async generateValidityProof(params: ValidityProofParams): Promise<ProofResult> {
126
+ this.ensureReady()
127
+
128
+ // Validate parameters
129
+ if (params.timestamp >= params.expiry) {
130
+ throw new ProofGenerationError(
131
+ 'validity',
132
+ 'Intent has already expired',
133
+ )
134
+ }
135
+
136
+ // Generate deterministic mock proof
137
+ const proofData = this.generateMockProofData('validity', params)
138
+
139
+ return {
140
+ proof: {
141
+ type: 'validity',
142
+ proof: proofData,
143
+ publicInputs: [
144
+ params.intentHash,
145
+ `0x${params.timestamp.toString(16)}`,
146
+ `0x${params.expiry.toString(16)}`,
147
+ ],
148
+ },
149
+ publicInputs: [
150
+ params.intentHash,
151
+ `0x${params.timestamp.toString(16)}`,
152
+ `0x${params.expiry.toString(16)}`,
153
+ ],
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Generate a mock fulfillment proof
159
+ *
160
+ * ⚠️ This proof provides NO cryptographic guarantees!
161
+ */
162
+ async generateFulfillmentProof(params: FulfillmentProofParams): Promise<ProofResult> {
163
+ this.ensureReady()
164
+
165
+ // Validate parameters
166
+ if (params.outputAmount < params.minOutputAmount) {
167
+ throw new ProofGenerationError(
168
+ 'fulfillment',
169
+ 'Output amount is less than minimum required',
170
+ )
171
+ }
172
+
173
+ if (params.fulfillmentTime > params.expiry) {
174
+ throw new ProofGenerationError(
175
+ 'fulfillment',
176
+ 'Fulfillment time is after expiry',
177
+ )
178
+ }
179
+
180
+ // Generate deterministic mock proof
181
+ const proofData = this.generateMockProofData('fulfillment', params)
182
+
183
+ return {
184
+ proof: {
185
+ type: 'fulfillment',
186
+ proof: proofData,
187
+ publicInputs: [
188
+ params.intentHash,
189
+ params.recipientStealth,
190
+ `0x${params.minOutputAmount.toString(16).padStart(16, '0')}`,
191
+ ],
192
+ },
193
+ publicInputs: [
194
+ params.intentHash,
195
+ params.recipientStealth,
196
+ `0x${params.minOutputAmount.toString(16).padStart(16, '0')}`,
197
+ ],
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Verify a mock proof
203
+ *
204
+ * Only verifies that the proof has the mock prefix.
205
+ * ⚠️ This provides NO cryptographic verification!
206
+ */
207
+ async verifyProof(proof: ZKProof): Promise<boolean> {
208
+ this.ensureReady()
209
+
210
+ // Mock verification: just check the prefix
211
+ return proof.proof.startsWith(MOCK_PROOF_PREFIX)
212
+ }
213
+
214
+ /**
215
+ * Check if a proof is a mock proof
216
+ */
217
+ static isMockProof(proof: ZKProof): boolean {
218
+ return proof.proof.startsWith(MOCK_PROOF_PREFIX)
219
+ }
220
+
221
+ // ─── Private Methods ───────────────────────────────────────────────────────
222
+
223
+ private ensureReady(): void {
224
+ if (!this._isReady) {
225
+ throw new ProofError(
226
+ 'MockProofProvider not initialized. Call initialize() first.',
227
+ ErrorCode.PROOF_PROVIDER_NOT_READY
228
+ )
229
+ }
230
+ }
231
+
232
+ private generateMockProofData(
233
+ proofType: string,
234
+ params: unknown,
235
+ ): HexString {
236
+ // Create deterministic proof data from inputs
237
+ const input = JSON.stringify({ type: proofType, params }, (_, v) =>
238
+ typeof v === 'bigint' ? v.toString() : v,
239
+ )
240
+ const hash = sha256(new TextEncoder().encode(input))
241
+
242
+ // Add some random bytes to make each proof unique
243
+ const random = randomBytes(16)
244
+
245
+ // Combine: MOCK prefix + hash + random
246
+ const combined = new Uint8Array(4 + hash.length + random.length)
247
+ combined.set(new TextEncoder().encode('MOCK'), 0)
248
+ combined.set(hash, 4)
249
+ combined.set(random, 4 + hash.length)
250
+
251
+ return `${MOCK_PROOF_PREFIX}${bytesToHex(combined.slice(4))}` as HexString
252
+ }
253
+
254
+ private hashToHex(data: string): HexString {
255
+ const hash = sha256(new TextEncoder().encode(data))
256
+ return `0x${bytesToHex(hash)}` as HexString
257
+ }
258
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Noir Proof Provider
3
+ *
4
+ * Production-ready ZK proof provider using Noir (Aztec) circuits.
5
+ *
6
+ * This provider generates cryptographically sound proofs using:
7
+ * - Funding Proof: ~22,000 constraints (docs/specs/FUNDING-PROOF.md)
8
+ * - Validity Proof: ~72,000 constraints (docs/specs/VALIDITY-PROOF.md)
9
+ * - Fulfillment Proof: ~22,000 constraints (docs/specs/FULFILLMENT-PROOF.md)
10
+ *
11
+ * @see docs/specs/ZK-ARCHITECTURE.md for framework decision
12
+ */
13
+
14
+ import type { ZKProof } from '@sip-protocol/types'
15
+ import type {
16
+ ProofProvider,
17
+ ProofFramework,
18
+ FundingProofParams,
19
+ ValidityProofParams,
20
+ FulfillmentProofParams,
21
+ ProofResult,
22
+ } from './interface'
23
+ import { ProofGenerationError } from './interface'
24
+ import { ProofError, ErrorCode } from '../errors'
25
+
26
+ /**
27
+ * Noir circuit artifacts paths
28
+ * These will be populated when circuits are compiled (#14, #15, #16)
29
+ */
30
+ interface NoirCircuitArtifacts {
31
+ fundingCircuit?: unknown
32
+ validityCircuit?: unknown
33
+ fulfillmentCircuit?: unknown
34
+ }
35
+
36
+ /**
37
+ * Noir Proof Provider Configuration
38
+ */
39
+ export interface NoirProviderConfig {
40
+ /**
41
+ * Path to compiled circuit artifacts
42
+ * If not provided, uses bundled artifacts
43
+ */
44
+ artifactsPath?: string
45
+
46
+ /**
47
+ * Backend to use for proof generation
48
+ * @default 'barretenberg' (UltraPlonk)
49
+ */
50
+ backend?: 'barretenberg'
51
+
52
+ /**
53
+ * Enable verbose logging for debugging
54
+ * @default false
55
+ */
56
+ verbose?: boolean
57
+ }
58
+
59
+ /**
60
+ * Noir Proof Provider
61
+ *
62
+ * Production ZK proof provider using Noir circuits.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const provider = new NoirProofProvider({
67
+ * artifactsPath: './circuits/target',
68
+ * })
69
+ *
70
+ * await provider.initialize()
71
+ *
72
+ * const result = await provider.generateFundingProof({
73
+ * balance: 100n,
74
+ * minimumRequired: 50n,
75
+ * // ... other params
76
+ * })
77
+ * ```
78
+ */
79
+ export class NoirProofProvider implements ProofProvider {
80
+ readonly framework: ProofFramework = 'noir'
81
+ private _isReady = false
82
+ private config: NoirProviderConfig
83
+ private artifacts: NoirCircuitArtifacts = {}
84
+
85
+ constructor(config: NoirProviderConfig = {}) {
86
+ this.config = {
87
+ backend: 'barretenberg',
88
+ verbose: false,
89
+ ...config,
90
+ }
91
+ }
92
+
93
+ get isReady(): boolean {
94
+ return this._isReady
95
+ }
96
+
97
+ /**
98
+ * Initialize the Noir provider
99
+ *
100
+ * Loads circuit artifacts and initializes the proving backend.
101
+ *
102
+ * @throws Error if circuits are not yet implemented
103
+ */
104
+ async initialize(): Promise<void> {
105
+ // TODO: Implement when circuits are ready (#14, #15, #16)
106
+ //
107
+ // Implementation will:
108
+ // 1. Load compiled circuit artifacts from artifactsPath
109
+ // 2. Initialize Barretenberg backend
110
+ // 3. Load proving/verification keys
111
+ //
112
+ // Dependencies:
113
+ // - @noir-lang/noir_js
114
+ // - @noir-lang/backend_barretenberg
115
+ //
116
+ // Example:
117
+ // ```typescript
118
+ // import { Noir } from '@noir-lang/noir_js'
119
+ // import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'
120
+ //
121
+ // const circuit = await import('./circuits/funding/target/funding.json')
122
+ // const backend = new BarretenbergBackend(circuit)
123
+ // const noir = new Noir(circuit, backend)
124
+ // ```
125
+
126
+ throw new ProofError(
127
+ 'NoirProofProvider not yet implemented. ' +
128
+ 'Circuits must be compiled first. See issues #14, #15, #16.',
129
+ ErrorCode.PROOF_NOT_IMPLEMENTED,
130
+ { context: { issues: ['#14', '#15', '#16'] } }
131
+ )
132
+ }
133
+
134
+ /**
135
+ * Generate a Funding Proof using Noir circuits
136
+ *
137
+ * @see docs/specs/FUNDING-PROOF.md
138
+ */
139
+ async generateFundingProof(_params: FundingProofParams): Promise<ProofResult> {
140
+ this.ensureReady()
141
+
142
+ // TODO: Implement when circuit is ready (#14)
143
+ //
144
+ // Implementation will:
145
+ // 1. Prepare witness inputs from params
146
+ // 2. Execute circuit to generate proof
147
+ // 3. Extract public inputs
148
+ //
149
+ // Example:
150
+ // ```typescript
151
+ // const witness = {
152
+ // balance: params.balance,
153
+ // minimum_required: params.minimumRequired,
154
+ // blinding: params.blindingFactor,
155
+ // // ... other inputs
156
+ // }
157
+ //
158
+ // const proof = await this.fundingCircuit.generateProof(witness)
159
+ // return { proof, publicInputs: proof.publicInputs }
160
+ // ```
161
+
162
+ throw new ProofGenerationError(
163
+ 'funding',
164
+ 'Noir circuit not yet implemented. See #14.',
165
+ )
166
+ }
167
+
168
+ /**
169
+ * Generate a Validity Proof using Noir circuits
170
+ *
171
+ * @see docs/specs/VALIDITY-PROOF.md
172
+ */
173
+ async generateValidityProof(_params: ValidityProofParams): Promise<ProofResult> {
174
+ this.ensureReady()
175
+
176
+ // TODO: Implement when circuit is ready (#15)
177
+ throw new ProofGenerationError(
178
+ 'validity',
179
+ 'Noir circuit not yet implemented. See #15.',
180
+ )
181
+ }
182
+
183
+ /**
184
+ * Generate a Fulfillment Proof using Noir circuits
185
+ *
186
+ * @see docs/specs/FULFILLMENT-PROOF.md
187
+ */
188
+ async generateFulfillmentProof(_params: FulfillmentProofParams): Promise<ProofResult> {
189
+ this.ensureReady()
190
+
191
+ // TODO: Implement when circuit is ready (#16)
192
+ throw new ProofGenerationError(
193
+ 'fulfillment',
194
+ 'Noir circuit not yet implemented. See #16.',
195
+ )
196
+ }
197
+
198
+ /**
199
+ * Verify a Noir proof
200
+ */
201
+ async verifyProof(_proof: ZKProof): Promise<boolean> {
202
+ this.ensureReady()
203
+
204
+ // TODO: Implement when circuits are ready
205
+ //
206
+ // Implementation will:
207
+ // 1. Determine proof type from proof.type
208
+ // 2. Use appropriate verifier circuit
209
+ // 3. Return verification result
210
+ //
211
+ // Example:
212
+ // ```typescript
213
+ // const verified = await this.backend.verifyProof(proof)
214
+ // return verified
215
+ // ```
216
+
217
+ throw new ProofError(
218
+ 'Noir proof verification not yet implemented.',
219
+ ErrorCode.PROOF_NOT_IMPLEMENTED
220
+ )
221
+ }
222
+
223
+ // ─── Private Methods ───────────────────────────────────────────────────────
224
+
225
+ private ensureReady(): void {
226
+ if (!this._isReady) {
227
+ throw new ProofError(
228
+ 'NoirProofProvider not initialized. Call initialize() first.',
229
+ ErrorCode.PROOF_PROVIDER_NOT_READY
230
+ )
231
+ }
232
+ }
233
+ }