orbinum-encrypted-memo 0.2.2

Encrypted memo primitives for Orbinum shielded transactions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Groth16 Prover Use Case
//!
//! Generates Groth16 proofs for disclosure circuit using ark-groth16 with BN254.
//! WASM witness calculator produces complete witness (~740 wires).
//! Proving keys must be in ark-serialize format (.ark).

use crate::{
	application::disclosure::DisclosureWitness,
	domain::{aggregates::disclosure::DisclosurePublicSignals, entities::error::MemoError},
};
use alloc::vec::Vec;

// Ark imports
use ark_bn254::{Bn254, Fr as Bn254Fr};
use ark_ff::PrimeField;
use ark_groth16::{Groth16, ProvingKey};
use ark_relations::r1cs::ConstraintSynthesizer;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_snark::SNARK;

// ============================================================================
// Witness Calculator
// ============================================================================

/// Converts bytes to BN254 field element (big-endian)
fn bytes_to_field(bytes: &[u8]) -> Result<Bn254Fr, MemoError> {
	// Pad to 32 bytes if necessary
	let mut padded = [0u8; 32];
	let len = bytes.len().min(32);
	padded[32 - len..].copy_from_slice(&bytes[..len]);

	// Use Big-Endian to match disclosure.rs and standard crypto conventions
	Ok(Bn254Fr::from_be_bytes_mod_order(&padded))
}

// ============================================================================
// WASM Witness Calculator Integration
// ============================================================================

/// Calculates full witness using WASM witness calculator
///
/// Executes compiled circuit to produce complete witness (~740 wires).
/// Requires wasm-witness feature.
#[cfg(feature = "wasm-witness")]
pub fn calculate_witness_wasm(
	wasm_bytes: &[u8],
	witness: &DisclosureWitness,
	public_signals: &DisclosurePublicSignals,
) -> Result<Vec<Bn254Fr>, MemoError> {
	use crate::infrastructure::repositories::wasm_witness::WasmWitnessCalculator;
	use alloc::string::ToString;

	// 1. Create calculator
	let mut calculator = WasmWitnessCalculator::new(wasm_bytes)?;

	// 2. Prepare inputs as (signal_name, value) pairs
	// Order must match disclosure.circom declaration order
	let inputs = vec![
		// Public inputs
		(
			"commitment".to_string(),
			bytes_to_field(&public_signals.commitment)?,
		),
		(
			"revealed_value".to_string(),
			Bn254Fr::from(witness.value * (public_signals.disclose_value() as u64)),
		),
		(
			"revealed_asset_id".to_string(),
			Bn254Fr::from((witness.asset_id as u64) * (public_signals.disclose_asset_id() as u64)),
		),
		(
			"revealed_owner_hash".to_string(),
			bytes_to_field(&public_signals.revealed_owner_hash)?,
		),
		// Private inputs
		("value".to_string(), Bn254Fr::from(witness.value)),
		(
			"asset_id".to_string(),
			Bn254Fr::from(witness.asset_id as u64),
		),
		(
			"owner_pubkey".to_string(),
			bytes_to_field(&witness.owner_pubkey)?,
		),
		("blinding".to_string(), bytes_to_field(&witness.blinding)?),
		(
			"viewing_key".to_string(),
			bytes_to_field(&witness.viewing_key)?,
		),
		(
			"disclose_value".to_string(),
			Bn254Fr::from(public_signals.disclose_value() as u64),
		),
		(
			"disclose_asset_id".to_string(),
			Bn254Fr::from(public_signals.disclose_asset_id() as u64),
		),
		(
			"disclose_owner".to_string(),
			Bn254Fr::from(public_signals.disclose_owner() as u64),
		),
	];

	// 3. Calculate witness
	let full_witness = calculator.calculate_witness(&inputs)?;

	Ok(full_witness)
}

/// Placeholder when wasm-witness feature is not enabled
#[cfg(not(feature = "wasm-witness"))]
pub fn calculate_witness_wasm(
	_wasm_bytes: &[u8],
	_witness: &DisclosureWitness,
	_public_signals: &DisclosurePublicSignals,
) -> Result<Vec<Bn254Fr>, MemoError> {
	Err(MemoError::WasmLoadFailed(
		"wasm-witness feature not enabled. Rebuild with --features wasm-witness",
	))
}

/// Generates disclosure proof using WASM witness calculator
///
/// High-level API for production. Proving key must be provided by caller.
#[cfg(feature = "wasm-witness")]
pub fn prove_with_wasm(
	wasm_bytes: &[u8],
	witness: &DisclosureWitness,
	public_signals: &DisclosurePublicSignals,
	proving_key: Option<&[u8]>,
) -> Result<Vec<u8>, MemoError> {
	// Step 1: Get proving key (must be provided by caller)
	let pk = match proving_key {
		Some(pk_bytes) => pk_bytes.to_vec(),
		None => {
			return Err(MemoError::KeyLoadingFailed(
				"Proving key required but not provided - caller must load and pass key bytes",
			));
		}
	};

	// Step 2: Calculate full witness using WASM
	let full_witness = calculate_witness_wasm(wasm_bytes, witness, public_signals)?;

	// Step 3: Generate proof
	generate_groth16_proof_internal(&pk, &full_witness)
}

#[cfg(not(feature = "wasm-witness"))]
pub fn prove_with_wasm(
	_wasm_bytes: &[u8],
	_witness: &DisclosureWitness,
	_public_signals: &DisclosurePublicSignals,
	_proving_key: Option<&[u8]>,
) -> Result<Vec<u8>, MemoError> {
	Err(MemoError::WasmLoadFailed(
		"wasm-witness feature not enabled",
	))
}

// ============================================================================
// Groth16 Prover (ARK Implementation)
// ============================================================================

/// Generates Groth16 proof using ark-groth16
///
/// Proving key must be ark-serialize format (.ark), not snarkjs .zkey.
/// Returns serialized proof or error.
pub fn generate_groth16_proof_internal(
	proving_key_bytes: &[u8],
	witness: &[Bn254Fr],
) -> Result<Vec<u8>, MemoError> {
	// 1. Deserializar proving key
	let pk = ProvingKey::<Bn254>::deserialize_compressed(proving_key_bytes).map_err(|e| {
		MemoError::InvalidProvingKey(
			alloc::format!("Failed to deserialize proving key: {e:?}").leak(),
		)
	})?;

	// 2. Create constraint system with the witness
	// NOTE: This requires that the witness is complete (all wires)
	// In production, use WASM witness calculator
	let circuit = WitnessCircuit {
		witness: witness.to_vec(),
	};

	// 3. Generate proof with ark-groth16
	// NOTE: In production use OsRng or ChaCha20Rng with random seed
	use ark_std::rand::{rngs::StdRng, SeedableRng};
	let mut rng = StdRng::from_entropy();

	let proof = Groth16::<Bn254>::prove(&pk, circuit, &mut rng).map_err(|e| {
		MemoError::ProofGenerationFailed(
			alloc::format!("ark-groth16 proof generation failed: {e:?}").leak(),
		)
	})?;

	// 4. Serialize proof
	let mut proof_bytes = Vec::new();
	proof.serialize_compressed(&mut proof_bytes).map_err(|e| {
		MemoError::ProofGenerationFailed(alloc::format!("Failed to serialize proof: {e:?}").leak())
	})?;

	Ok(proof_bytes)
}

/// Minimal circuit wrapper for ark-groth16
struct WitnessCircuit {
	witness: Vec<Bn254Fr>,
}

impl ConstraintSynthesizer<Bn254Fr> for WitnessCircuit {
	fn generate_constraints(
		self,
		cs: ark_relations::r1cs::ConstraintSystemRef<Bn254Fr>,
	) -> ark_relations::r1cs::Result<()> {
		// NOTE: This DisclosureCircuit is a basic implementation for testing.
		// It only assigns the witness without implementing the complete constraints of the circuit.

		// Mark public inputs
		let num_public = 4; // commitment, vk_hash, mask, revealed_owner_hash
		for i in 0..num_public.min(self.witness.len().saturating_sub(1)) {
			let _ = cs.new_input_variable(|| Ok(self.witness[i + 1]))?;
		}

		// Private witness variables
		for signal in self.witness.iter().skip(num_public + 1) {
			let _ = cs.new_witness_variable(|| Ok(*signal))?;
		}

		Ok(())
	}
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
	use super::*;
	use crate::domain::aggregates::disclosure::DisclosurePublicSignals;

	// ===== bytes_to_field Tests =====

	#[test]
	fn test_bytes_to_field_zero() {
		let bytes = [0u8; 32];
		let result = bytes_to_field(&bytes);

		assert!(result.is_ok());
		assert_eq!(result.unwrap(), Bn254Fr::from(0u64));
	}

	#[test]
	fn test_bytes_to_field_one() {
		let mut bytes = [0u8; 32];
		bytes[31] = 1; // Big-endian
		let result = bytes_to_field(&bytes);

		assert!(result.is_ok());
		assert_eq!(result.unwrap(), Bn254Fr::from(1u64));
	}

	#[test]
	fn test_bytes_to_field_small_input() {
		let bytes = [1u8; 8];
		let result = bytes_to_field(&bytes);

		assert!(result.is_ok());
		// Should pad and convert correctly
		assert_ne!(result.unwrap(), Bn254Fr::from(0u64));
	}

	#[test]
	fn test_bytes_to_field_large_input() {
		let bytes = [255u8; 32];
		let result = bytes_to_field(&bytes);

		assert!(result.is_ok());
		// Should reduce modulo field order
		assert_ne!(result.unwrap(), Bn254Fr::from(0u64));
	}

	#[test]
	fn test_bytes_to_field_deterministic() {
		let bytes = [42u8; 32];
		let result1 = bytes_to_field(&bytes);
		let result2 = bytes_to_field(&bytes);

		assert!(result1.is_ok());
		assert!(result2.is_ok());
		assert_eq!(result1.unwrap(), result2.unwrap());
	}

	#[test]
	fn test_bytes_to_field_different_inputs() {
		let bytes1 = [1u8; 32];
		let bytes2 = [2u8; 32];

		let result1 = bytes_to_field(&bytes1).unwrap();
		let result2 = bytes_to_field(&bytes2).unwrap();

		assert_ne!(result1, result2);
	}

	#[test]
	fn test_bytes_to_field_empty_padded() {
		let bytes = [];
		let result = bytes_to_field(&bytes);

		assert!(result.is_ok());
		assert_eq!(result.unwrap(), Bn254Fr::from(0u64));
	}

	#[test]
	fn test_bytes_to_field_sequential() {
		let mut bytes = [0u8; 32];
		for (i, byte) in bytes.iter_mut().enumerate() {
			*byte = i as u8;
		}

		let result = bytes_to_field(&bytes);
		assert!(result.is_ok());
		assert_ne!(result.unwrap(), Bn254Fr::from(0u64));
	}

	// ===== WitnessCircuit Tests =====

	#[test]
	fn test_witness_circuit_construction() {
		let witness = vec![
			Bn254Fr::from(0u64),
			Bn254Fr::from(1u64),
			Bn254Fr::from(2u64),
		];
		let circuit = WitnessCircuit {
			witness: witness.clone(),
		};

		assert_eq!(circuit.witness.len(), 3);
		assert_eq!(circuit.witness[0], Bn254Fr::from(0u64));
		assert_eq!(circuit.witness[1], Bn254Fr::from(1u64));
		assert_eq!(circuit.witness[2], Bn254Fr::from(2u64));
	}

	#[test]
	fn test_witness_circuit_empty() {
		let circuit = WitnessCircuit { witness: vec![] };

		assert_eq!(circuit.witness.len(), 0);
	}

	#[test]
	fn test_witness_circuit_large() {
		let witness = vec![Bn254Fr::from(42u64); 1000];
		let circuit = WitnessCircuit {
			witness: witness.clone(),
		};

		assert_eq!(circuit.witness.len(), 1000);
		assert_eq!(circuit.witness[500], Bn254Fr::from(42u64));
	}

	// ===== calculate_witness_wasm Tests (without feature) =====

	#[test]
	#[cfg(not(feature = "wasm-witness"))]
	fn test_calculate_witness_wasm_without_feature() {
		let wasm_bytes = vec![0u8; 100];
		let witness = DisclosureWitness {
			value: 1000,
			owner_pubkey: [1u8; 32],
			blinding: [2u8; 32],
			asset_id: 0,
			viewing_key: [3u8; 32],
		};
		let public_signals = DisclosurePublicSignals {
			commitment: [4u8; 32],
			revealed_value: 1000,
			revealed_asset_id: 0,
			revealed_owner_hash: [0u8; 32],
		};

		let result = calculate_witness_wasm(&wasm_bytes, &witness, &public_signals);

		assert!(result.is_err());
		if let Err(MemoError::WasmLoadFailed(msg)) = result {
			assert!(msg.contains("wasm-witness feature not enabled"));
		}
	}

	#[test]
	#[cfg(not(feature = "wasm-witness"))]
	fn test_prove_with_wasm_without_feature() {
		let wasm_bytes = vec![0u8; 100];
		let witness = DisclosureWitness {
			value: 1000,
			owner_pubkey: [1u8; 32],
			blinding: [2u8; 32],
			asset_id: 0,
			viewing_key: [3u8; 32],
		};
		let public_signals = DisclosurePublicSignals {
			commitment: [4u8; 32],
			revealed_value: 1000,
			revealed_asset_id: 0,
			revealed_owner_hash: [0u8; 32],
		};

		let result = prove_with_wasm(&wasm_bytes, &witness, &public_signals, None);

		assert!(result.is_err());
		if let Err(MemoError::WasmLoadFailed(msg)) = result {
			assert!(msg.contains("wasm-witness feature not enabled"));
		}
	}

	// ===== prove_with_wasm Tests (with feature) =====

	#[test]
	#[cfg(feature = "wasm-witness")]
	fn test_prove_with_wasm_no_proving_key() {
		let wasm_bytes = vec![0u8; 100];
		let witness = DisclosureWitness {
			value: 1000,
			owner_pubkey: [1u8; 32],
			blinding: [2u8; 32],
			asset_id: 0,
			viewing_key: [3u8; 32],
		};
		let public_signals = DisclosurePublicSignals {
			commitment: [4u8; 32],
			revealed_value: 1000,
			revealed_asset_id: 0,
			revealed_owner_hash: [0u8; 32],
		};

		let result = prove_with_wasm(&wasm_bytes, &witness, &public_signals, None);

		assert!(result.is_err());
		if let Err(MemoError::KeyLoadingFailed(msg)) = result {
			assert!(msg.contains("Proving key required"));
		}
	}

	// ===== generate_groth16_proof_internal Tests =====

	#[test]
	fn test_generate_groth16_proof_invalid_key() {
		let invalid_key = vec![0u8; 100];
		let witness = vec![Bn254Fr::from(1u64), Bn254Fr::from(2u64)];

		let result = generate_groth16_proof_internal(&invalid_key, &witness);

		assert!(result.is_err());
		if let Err(MemoError::InvalidProvingKey(msg)) = result {
			assert!(msg.contains("Failed to deserialize proving key"));
		}
	}

	#[test]
	fn test_generate_groth16_proof_empty_key() {
		let empty_key = vec![];
		let witness = vec![Bn254Fr::from(1u64)];

		let result = generate_groth16_proof_internal(&empty_key, &witness);

		assert!(result.is_err());
		if let Err(MemoError::InvalidProvingKey(_)) = result {
			// Expected
		} else {
			panic!("Expected InvalidProvingKey error");
		}
	}

	#[test]
	fn test_generate_groth16_proof_empty_witness() {
		let invalid_key = vec![1u8; 100];
		let witness = vec![];

		let result = generate_groth16_proof_internal(&invalid_key, &witness);

		assert!(result.is_err());
	}

	// ===== Integration Tests =====

	#[test]
	fn test_bytes_to_field_roundtrip_values() {
		let test_values = [0u64, 1u64, 100u64, 1000u64, u64::MAX];

		for val in test_values {
			let field = Bn254Fr::from(val);
			let mut bytes = [0u8; 32];
			let val_bytes = val.to_be_bytes();
			bytes[24..].copy_from_slice(&val_bytes);

			let result = bytes_to_field(&bytes);
			assert!(result.is_ok());
			assert_eq!(result.unwrap(), field);
		}
	}

	#[test]
	fn test_witness_circuit_constraint_synthesis() {
		use ark_relations::r1cs::ConstraintSystem;

		let witness = vec![
			Bn254Fr::from(0u64), // Wire 0 (always 1 in R1CS)
			Bn254Fr::from(1u64),
			Bn254Fr::from(2u64),
			Bn254Fr::from(3u64),
			Bn254Fr::from(4u64),
			Bn254Fr::from(5u64),
		];

		let circuit = WitnessCircuit {
			witness: witness.clone(),
		};

		let cs = ConstraintSystem::<Bn254Fr>::new_ref();
		let result = circuit.generate_constraints(cs.clone());

		assert!(result.is_ok());
		assert!(cs.num_instance_variables() > 0 || cs.num_witness_variables() > 0);
	}

	#[test]
	fn test_bytes_to_field_padding_consistency() {
		let short_bytes = [42u8; 8];
		let mut padded_bytes = [0u8; 32];
		padded_bytes[24..].copy_from_slice(&short_bytes);

		let result_short = bytes_to_field(&short_bytes).unwrap();
		let result_padded = bytes_to_field(&padded_bytes).unwrap();

		assert_eq!(result_short, result_padded);
	}

	#[test]
	fn test_witness_circuit_with_minimal_witness() {
		use ark_relations::r1cs::ConstraintSystem;

		// Minimal witness: wire 0 + 4 public + 1 private
		let witness = vec![
			Bn254Fr::from(1u64), // wire 0
			Bn254Fr::from(10u64),
			Bn254Fr::from(20u64),
			Bn254Fr::from(30u64),
			Bn254Fr::from(40u64),
			Bn254Fr::from(50u64), // private
		];

		let circuit = WitnessCircuit { witness };
		let cs = ConstraintSystem::<Bn254Fr>::new_ref();
		let result = circuit.generate_constraints(cs.clone());

		assert!(result.is_ok());
	}
}