oarust 0.9.0

GPU-first semantic computing engine written in Rust
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
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=cryptography_merkle.json schema_version=1 generator_version=64
// schema_sha256=c2af72d18234e1a9e0207b42b94a8769a0b85371b65edc828d41c0a577bfc4a8
use crate::{
	DType, Error, Matrix, OpAttribute, Result,
	runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
};

/// Selected parent-hash identity; digest sizes are part of the contract.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum MerkleAlgorithm {
	Sha256 = 0,
	Sha512 = 1,
	Sha3_256 = 2,
	Sha3_512 = 3,
	Shake128 = 4,
	Shake256 = 5,
	Poseidon2BabyBear16 = 6,
	Poseidon2BabyBear24 = 7,
	Poseidon2KoalaBear16 = 8,
	Poseidon2KoalaBear24 = 9,
}

impl MerkleAlgorithm {
	/// Exact digest byte extent.
	pub const fn digest_bytes(self) -> usize {
		match self {
			Self::Sha256 => 32,
			Self::Sha512 => 64,
			Self::Sha3_256 => 32,
			Self::Sha3_512 => 64,
			Self::Shake128 => 32,
			Self::Shake256 => 32,
			Self::Poseidon2BabyBear16 => 32,
			Self::Poseidon2BabyBear24 => 32,
			Self::Poseidon2KoalaBear16 => 32,
			Self::Poseidon2KoalaBear24 => 32,
		}
	}
	/// Storage type of supplied leaf and root rows.
	pub const fn dtype(self) -> DType {
		match self {
			Self::Sha256 => DType::U8,
			Self::Sha512 => DType::U8,
			Self::Sha3_256 => DType::U8,
			Self::Sha3_512 => DType::U8,
			Self::Shake128 => DType::U8,
			Self::Shake256 => DType::U8,
			Self::Poseidon2BabyBear16 => DType::U32,
			Self::Poseidon2BabyBear24 => DType::U32,
			Self::Poseidon2KoalaBear16 => DType::U32,
			Self::Poseidon2KoalaBear24 => DType::U32,
		}
	}
	/// Stable API hash spelling.
	pub const fn name(self) -> &'static str {
		match self {
			Self::Sha256 => "sha256",
			Self::Sha512 => "sha512",
			Self::Sha3_256 => "sha3_256",
			Self::Sha3_512 => "sha3_512",
			Self::Shake128 => "shake128",
			Self::Shake256 => "shake256",
			Self::Poseidon2BabyBear16 => "poseidon2_babybear16",
			Self::Poseidon2BabyBear24 => "poseidon2_babybear24",
			Self::Poseidon2KoalaBear16 => "poseidon2_koalabear16",
			Self::Poseidon2KoalaBear24 => "poseidon2_koalabear24",
		}
	}
}

/// Device-resident immutable tree levels over supplied, already hashed leaves.
/// Odd levels duplicate their last node. No host tree or digest copies are made.
#[derive(Clone)]
pub struct DeviceMerkleTree {
	algorithm: MerkleAlgorithm,
	leaf_count: u32,
	levels: Vec<Matrix>,
}

impl DeviceMerkleTree {
	/// Hash identity used at every parent node.
	pub const fn algorithm(&self) -> MerkleAlgorithm {
		self.algorithm
	}
	/// Trusted original leaf count, independent of root bytes.
	pub const fn leaf_count(&self) -> u32 {
		self.leaf_count
	}
	/// Retained root digest as a one-row Matrix.
	pub fn root(&self) -> &Matrix {
		&self.levels[self.levels.len() - 1]
	}
}

/// Build retained device tree levels using the selected parent hash.
///
/// Leaves are prehashed U8/U32 rows with the algorithm's exact digest extent.
/// Poseidon2 nodes use OA's versioned field framing, not NVIDIA wire semantics.
///
/// # Errors
/// Rejects dtype, rank, extent, leaf count, allocation or recording failures.
pub fn build(leaves: &Matrix, algorithm: MerkleAlgorithm) -> Result<DeviceMerkleTree> {
	let [rows, elements] = match leaves.shape() {
		[rows, elements] => [*rows, *elements],
		_ => {
			return Err(Error::invalid_argument(
				"Merkle leaves require rank-two digest rows",
			));
		}
	};
	let bytes = algorithm.digest_bytes();
	if leaves.dtype() != algorithm.dtype()
		|| elements != bytes / leaves.dtype().size_bytes()
		|| !(1..=(1_usize << 24)).contains(&rows)
	{
		return Err(Error::invalid_argument(
			"Merkle leaves require the selected dtype/digest extent and 1..=2^24 rows",
		));
	}
	let input_bytes = rows
		.checked_mul(bytes)
		.ok_or_else(|| Error::invalid_argument("Merkle input bytes overflow usize"))?;
	u32::try_from(input_bytes)
		.map_err(|_| Error::invalid_argument("Merkle input bytes exceed u32"))?;
	let engine = leaves.engine_handle();
	let leaf_count = rows as u32;
	let mut levels = vec![leaves.clone()];
	let mut current = leaves.clone();
	let mut source_count = leaf_count;
	while source_count > 1 {
		let count = source_count.div_ceil(2);
		let elements_count = (count as usize)
			.checked_mul(elements)
			.ok_or_else(|| Error::invalid_argument("Merkle output extent overflows usize"))?;
		let output = Matrix::allocate_output(
			engine,
			vec![count as usize, elements],
			elements_count,
			algorithm.dtype(),
		)?;
		let groups = engine.linear_dispatch_grid(count, 128)?;
		let kernel = KernelId::CryptographyMerkleTreeReduceU32;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(source_count),
			PushConstant::U32(algorithm as u32),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "leaf_count".into(),
				value: u64::from(source_count),
			},
			OpAttribute::UnsignedInteger {
				name: "algorithm".into(),
				value: algorithm as u64,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
			},
			SemanticDispatch {
				contract: crate::core::operation::cryptography::merkle::MERKLE_TREE_REDUCE,
				inputs: &[&current],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		levels.push(output.clone());
		current = output;
		source_count = count;
	}
	Ok(DeviceMerkleTree {
		algorithm,
		leaf_count,
		levels,
	})
}

/// Compute roots of contiguous power-of-two subtrees for hierarchical construction.
///
/// Records the first log2(subtree_leaves) tree levels. The returned rows can be
/// passed to `build` to finish the tree; no leaf readback/repacking is involved.
///
/// # Errors
/// Rejects dtype, rank, extent, partition sizes, allocation or recording failures.
pub fn subtree_roots(
	leaves: &Matrix,
	algorithm: MerkleAlgorithm,
	subtree_leaves: usize,
) -> Result<Matrix> {
	let [rows, elements] = match leaves.shape() {
		[rows, elements] => [*rows, *elements],
		_ => {
			return Err(Error::invalid_argument(
				"Merkle subtrees require rank-two digest rows",
			));
		}
	};
	if leaves.dtype() != algorithm.dtype()
		|| elements != algorithm.digest_bytes() / leaves.dtype().size_bytes()
		|| !(1..=(1_usize << 24)).contains(&rows)
		|| !rows.is_power_of_two()
		|| subtree_leaves == 0
		|| !subtree_leaves.is_power_of_two()
		|| subtree_leaves > rows
	{
		return Err(Error::invalid_argument(
			"Merkle subtrees require matching digest rows and a power-of-two partition of power-of-two leaves",
		));
	}
	let input_bytes = rows
		.checked_mul(algorithm.digest_bytes())
		.ok_or_else(|| Error::invalid_argument("Merkle subtree bytes overflow usize"))?;
	u32::try_from(input_bytes)
		.map_err(|_| Error::invalid_argument("Merkle subtree bytes exceed u32"))?;
	let engine = leaves.engine_handle();
	let mut current = leaves.clone();
	let mut source_count = rows as u32;
	for _ in 0..subtree_leaves.trailing_zeros() {
		let count = source_count / 2;
		let output = Matrix::allocate_output(
			engine,
			vec![count as usize, elements],
			count as usize * elements,
			algorithm.dtype(),
		)?;
		let groups = engine.linear_dispatch_grid(count, 128)?;
		let kernel = KernelId::CryptographyMerkleTreeReduceU32;
		let buffers = [
			BufferBinding::read(current.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(source_count),
			PushConstant::U32(algorithm as u32),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "leaf_count".into(),
				value: u64::from(source_count),
			},
			OpAttribute::UnsignedInteger {
				name: "algorithm".into(),
				value: algorithm as u64,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
			},
			SemanticDispatch {
				contract: crate::core::operation::cryptography::merkle::MERKLE_TREE_REDUCE,
				inputs: &[&current],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		current = output;
		source_count = count;
	}
	Ok(current)
}

/// Produce version-two inclusion frames for U32 `[batch]` leaf indices.
///
/// Frames carry the original count, index, hash identity and validity flag.
/// Out-of-range indices produce invalid, completely zero sibling paths.
///
/// # Errors
/// Rejects dtype, rank, ownership, address limits, allocation or recording failures.
pub fn proofs(tree: &DeviceMerkleTree, indices: &Matrix) -> Result<Matrix> {
	let rows = match indices.shape() {
		[rows] => *rows,
		_ => {
			return Err(Error::invalid_argument(
				"Merkle proof indices require rank-one U32 values",
			));
		}
	};
	let source = &tree.levels[0];
	if indices.dtype() != DType::U32 || !indices.engine_handle().same_as(source.engine_handle()) {
		return Err(Error::invalid_argument(
			"Merkle proof indices require matching Engine ownership",
		));
	}
	let depth = tree.levels.len() - 1;
	let bytes = tree.algorithm.digest_bytes();
	let frame_bytes = 20 + depth * bytes;
	let elements = rows
		.checked_mul(frame_bytes)
		.ok_or_else(|| Error::invalid_argument("Merkle proof bytes overflow usize"))?;
	u32::try_from(elements).map_err(|_| Error::invalid_argument("Merkle proof bytes exceed u32"))?;
	let count =
		u32::try_from(rows).map_err(|_| Error::invalid_argument("Merkle proof batch exceeds u32"))?;
	let engine = source.engine_handle();
	let mut frames = Matrix::allocate_output(engine, vec![rows, frame_bytes], elements, DType::U8)?;
	if rows == 0 {
		return Ok(frames);
	}
	let groups = engine.linear_dispatch_grid(count, 128)?;
	let kernel = KernelId::CryptographyMerkleFrameInitU32;
	let buffers = [
		BufferBinding::read(indices.storage()),
		BufferBinding::write(frames.storage()),
	];
	let push_constants = [
		PushConstant::U32(count),
		PushConstant::U32(groups[0] * 128),
		PushConstant::U32(tree.leaf_count),
		PushConstant::U32(tree.algorithm as u32),
		PushConstant::U32(frame_bytes as u32),
	];
	let attributes = [
		OpAttribute::UnsignedInteger {
			name: "leaf_count".into(),
			value: u64::from(tree.leaf_count),
		},
		OpAttribute::UnsignedInteger {
			name: "algorithm".into(),
			value: tree.algorithm as u64,
		},
	];
	engine.record_semantic(
		ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: groups,
		},
		SemanticDispatch {
			contract: crate::core::operation::cryptography::merkle::MERKLE_FRAME_INIT,
			inputs: &[indices],
			outputs: &[&frames],
			attributes: &attributes,
		},
	)?;
	for level in 0..depth {
		let source = &tree.levels[level];
		let output = frames.reshape_semantic_output(frames.shape().to_vec())?;
		let kernel = KernelId::CryptographyMerkleFrameAppendU32;
		let buffers = [
			BufferBinding::read(source.storage()),
			BufferBinding::read(indices.storage()),
			BufferBinding::read(frames.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(tree.leaf_count),
			PushConstant::U32(source.shape()[0] as u32),
			PushConstant::U32(tree.algorithm as u32),
			PushConstant::U32(frame_bytes as u32),
			PushConstant::U32(level as u32),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "leaf_count".into(),
				value: u64::from(tree.leaf_count),
			},
			OpAttribute::UnsignedInteger {
				name: "algorithm".into(),
				value: tree.algorithm as u64,
			},
			OpAttribute::UnsignedInteger {
				name: "level".into(),
				value: level as u64,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
			},
			SemanticDispatch {
				contract: crate::core::operation::cryptography::merkle::MERKLE_FRAME_APPEND,
				inputs: &[source, indices, &frames],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
		frames = output;
	}
	Ok(frames)
}

/// Verify inclusion frames against roots and an independently trusted leaf count.
///
/// Roots may contain one shared digest or one digest per proof. Malformed
/// headers, identity/count mismatches and changed sibling paths return zero.
///
/// # Errors
/// Rejects metadata, ownership, address limits, allocation or recording failures.
pub fn verify(
	leaves: &Matrix,
	frames: &Matrix,
	roots: &Matrix,
	algorithm: MerkleAlgorithm,
	leaf_count: u32,
) -> Result<Matrix> {
	let [rows, elements] = match leaves.shape() {
		[rows, elements] => [*rows, *elements],
		_ => {
			return Err(Error::invalid_argument(
				"Merkle verify leaves require rank-two digest rows",
			));
		}
	};
	if !(1..=(1_u32 << 24)).contains(&leaf_count) {
		return Err(Error::invalid_argument(
			"Merkle trusted leaf count is outside 1..=2^24",
		));
	}
	let depth = (leaf_count - 1).checked_ilog2().map_or(0, |n| n + 1) as usize;
	let frame_bytes = 20 + depth * algorithm.digest_bytes();
	if leaves.dtype() != algorithm.dtype()
		|| elements != algorithm.digest_bytes() / leaves.dtype().size_bytes()
		|| frames.dtype() != DType::U8
		|| frames.shape() != [rows, frame_bytes]
		|| roots.dtype() != algorithm.dtype()
		|| roots.shape().len() != 2
		|| roots.shape()[1] != elements
		|| (roots.shape()[0] != 1 && roots.shape()[0] != rows)
		|| !leaves.engine_handle().same_as(frames.engine_handle())
		|| !leaves.engine_handle().same_as(roots.engine_handle())
	{
		return Err(Error::invalid_argument(
			"Merkle verify requires matching hash extents, version-two frames and Engine ownership",
		));
	}
	let count =
		u32::try_from(rows).map_err(|_| Error::invalid_argument("Merkle verify batch exceeds u32"))?;
	let input_bytes = rows
		.checked_mul(frame_bytes)
		.ok_or_else(|| Error::invalid_argument("Merkle verify byte extent overflows usize"))?;
	u32::try_from(input_bytes)
		.map_err(|_| Error::invalid_argument("Merkle verify bytes exceed u32"))?;
	let engine = leaves.engine_handle();
	let output = Matrix::allocate_output(engine, vec![rows], rows, DType::U32)?;
	if count != 0 {
		let groups = engine.linear_dispatch_grid(count, 128)?;
		let kernel = KernelId::CryptographyMerkleFrameVerifyU32;
		let buffers = [
			BufferBinding::read(leaves.storage()),
			BufferBinding::read(frames.storage()),
			BufferBinding::read(roots.storage()),
			BufferBinding::write(output.storage()),
		];
		let push_constants = [
			PushConstant::U32(count),
			PushConstant::U32(groups[0] * 128),
			PushConstant::U32(leaf_count),
			PushConstant::U32(algorithm as u32),
			PushConstant::U32(frame_bytes as u32),
			PushConstant::U32(roots.shape()[0] as u32),
		];
		let attributes = [
			OpAttribute::UnsignedInteger {
				name: "leaf_count".into(),
				value: u64::from(leaf_count),
			},
			OpAttribute::UnsignedInteger {
				name: "algorithm".into(),
				value: algorithm as u64,
			},
		];
		engine.record_semantic(
			ComputeDispatch {
				kernel,
				buffers: &buffers,
				push_constants: &push_constants,
				workgroups: groups,
			},
			SemanticDispatch {
				contract: crate::core::operation::cryptography::merkle::MERKLE_FRAME_VERIFY,
				inputs: &[leaves, frames, roots],
				outputs: &[&output],
				attributes: &attributes,
			},
		)?;
	}
	Ok(output)
}