1use crate::{
5 DType, Error, Matrix, OpAttribute, Result,
6 runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch},
7};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11#[repr(u32)]
12pub enum MerkleAlgorithm {
13 Sha256 = 0,
14 Sha512 = 1,
15 Sha3_256 = 2,
16 Sha3_512 = 3,
17 Shake128 = 4,
18 Shake256 = 5,
19 Poseidon2BabyBear16 = 6,
20 Poseidon2BabyBear24 = 7,
21 Poseidon2KoalaBear16 = 8,
22 Poseidon2KoalaBear24 = 9,
23}
24
25impl MerkleAlgorithm {
26 pub const fn digest_bytes(self) -> usize {
28 match self {
29 Self::Sha256 => 32,
30 Self::Sha512 => 64,
31 Self::Sha3_256 => 32,
32 Self::Sha3_512 => 64,
33 Self::Shake128 => 32,
34 Self::Shake256 => 32,
35 Self::Poseidon2BabyBear16 => 32,
36 Self::Poseidon2BabyBear24 => 32,
37 Self::Poseidon2KoalaBear16 => 32,
38 Self::Poseidon2KoalaBear24 => 32,
39 }
40 }
41 pub const fn dtype(self) -> DType {
43 match self {
44 Self::Sha256 => DType::U8,
45 Self::Sha512 => DType::U8,
46 Self::Sha3_256 => DType::U8,
47 Self::Sha3_512 => DType::U8,
48 Self::Shake128 => DType::U8,
49 Self::Shake256 => DType::U8,
50 Self::Poseidon2BabyBear16 => DType::U32,
51 Self::Poseidon2BabyBear24 => DType::U32,
52 Self::Poseidon2KoalaBear16 => DType::U32,
53 Self::Poseidon2KoalaBear24 => DType::U32,
54 }
55 }
56 pub const fn name(self) -> &'static str {
58 match self {
59 Self::Sha256 => "sha256",
60 Self::Sha512 => "sha512",
61 Self::Sha3_256 => "sha3_256",
62 Self::Sha3_512 => "sha3_512",
63 Self::Shake128 => "shake128",
64 Self::Shake256 => "shake256",
65 Self::Poseidon2BabyBear16 => "poseidon2_babybear16",
66 Self::Poseidon2BabyBear24 => "poseidon2_babybear24",
67 Self::Poseidon2KoalaBear16 => "poseidon2_koalabear16",
68 Self::Poseidon2KoalaBear24 => "poseidon2_koalabear24",
69 }
70 }
71 pub(crate) const fn is_poseidon2(self) -> bool {
73 matches!(
74 self,
75 Self::Poseidon2BabyBear16
76 | Self::Poseidon2BabyBear24
77 | Self::Poseidon2KoalaBear16
78 | Self::Poseidon2KoalaBear24
79 )
80 }
81}
82
83#[derive(Clone)]
86pub struct DeviceMerkleTree {
87 algorithm: MerkleAlgorithm,
88 leaf_count: u32,
89 levels: Vec<Matrix>,
90}
91
92impl DeviceMerkleTree {
93 pub const fn algorithm(&self) -> MerkleAlgorithm {
95 self.algorithm
96 }
97 pub const fn leaf_count(&self) -> u32 {
99 self.leaf_count
100 }
101 pub fn root(&self) -> &Matrix {
103 &self.levels[self.levels.len() - 1]
104 }
105}
106
107pub fn build(leaves: &Matrix, algorithm: MerkleAlgorithm) -> Result<DeviceMerkleTree> {
115 let [rows, elements] = match leaves.shape() {
116 [rows, elements] => [*rows, *elements],
117 _ => {
118 return Err(Error::invalid_argument(
119 "Merkle leaves require rank-two digest rows",
120 ));
121 }
122 };
123 let bytes = algorithm.digest_bytes();
124 if leaves.dtype() != algorithm.dtype()
125 || elements != bytes / leaves.dtype().size_bytes()
126 || !(1..=(1_usize << 24)).contains(&rows)
127 {
128 return Err(Error::invalid_argument(
129 "Merkle leaves require the selected dtype/digest extent and 1..=2^24 rows",
130 ));
131 }
132 let input_bytes = rows
133 .checked_mul(bytes)
134 .ok_or_else(|| Error::invalid_argument("Merkle input bytes overflow usize"))?;
135 u32::try_from(input_bytes)
136 .map_err(|_| Error::invalid_argument("Merkle input bytes exceed u32"))?;
137 let runtime = leaves.runtime();
138 let leaf_count = rows as u32;
139 let mut levels = vec![leaves.clone()];
140 let mut current = leaves.clone();
141 let mut source_count = leaf_count;
142 while source_count > 1 {
143 let count = source_count.div_ceil(2);
144 let elements_count = (count as usize)
145 .checked_mul(elements)
146 .ok_or_else(|| Error::invalid_argument("Merkle output extent overflows usize"))?;
147 let output = Matrix::allocate_output(
148 runtime,
149 vec![count as usize, elements],
150 elements_count,
151 algorithm.dtype(),
152 )?;
153 let groups = runtime.linear_dispatch_grid(count, 128)?;
154 let kernel = if algorithm.is_poseidon2() {
155 KernelId::CryptographyMerkleTreeReducePoseidon2U32
156 } else {
157 KernelId::CryptographyMerkleTreeReduceU32
158 };
159 let buffers = [
160 BufferBinding::read(current.storage()),
161 BufferBinding::write(output.storage()),
162 ];
163 let push_constants = [
164 PushConstant::U32(count),
165 PushConstant::U32(groups[0] * 128),
166 PushConstant::U32(source_count),
167 PushConstant::U32(algorithm as u32),
168 ];
169 let attributes = [
170 OpAttribute::UnsignedInteger {
171 name: "leaf_count".into(),
172 value: u64::from(source_count),
173 },
174 OpAttribute::UnsignedInteger {
175 name: "algorithm".into(),
176 value: algorithm as u64,
177 },
178 ];
179 runtime.record_semantic(
180 ComputeDispatch {
181 kernel,
182 buffers: &buffers,
183 push_constants: &push_constants,
184 workgroups: groups,
185 indirect: None,
186 },
187 SemanticDispatch {
188 contract: crate::core::operation::crypto::merkle::MERKLE_TREE_REDUCE,
189 inputs: &[¤t],
190 outputs: &[&output],
191 attributes: &attributes,
192 },
193 )?;
194 levels.push(output.clone());
195 current = output;
196 source_count = count;
197 }
198 Ok(DeviceMerkleTree {
199 algorithm,
200 leaf_count,
201 levels,
202 })
203}
204
205pub fn subtree_roots(
213 leaves: &Matrix,
214 algorithm: MerkleAlgorithm,
215 subtree_leaves: usize,
216) -> Result<Matrix> {
217 let [rows, elements] = match leaves.shape() {
218 [rows, elements] => [*rows, *elements],
219 _ => {
220 return Err(Error::invalid_argument(
221 "Merkle subtrees require rank-two digest rows",
222 ));
223 }
224 };
225 if leaves.dtype() != algorithm.dtype()
226 || elements != algorithm.digest_bytes() / leaves.dtype().size_bytes()
227 || !(1..=(1_usize << 24)).contains(&rows)
228 || !rows.is_power_of_two()
229 || subtree_leaves == 0
230 || !subtree_leaves.is_power_of_two()
231 || subtree_leaves > rows
232 {
233 return Err(Error::invalid_argument(
234 "Merkle subtrees require matching digest rows and a power-of-two partition of power-of-two leaves",
235 ));
236 }
237 let input_bytes = rows
238 .checked_mul(algorithm.digest_bytes())
239 .ok_or_else(|| Error::invalid_argument("Merkle subtree bytes overflow usize"))?;
240 u32::try_from(input_bytes)
241 .map_err(|_| Error::invalid_argument("Merkle subtree bytes exceed u32"))?;
242 let runtime = leaves.runtime();
243 let shared_bytes = runtime.compute_shared_memory_bytes() as usize;
244 let cooperative = [
250 (
251 256_usize,
252 KernelId::CryptographyMerkleSubtreeCooperative256U32,
253 ),
254 (512, KernelId::CryptographyMerkleSubtreeCooperative512U32),
255 ]
256 .into_iter()
257 .find(|(capacity, _)| {
258 !runtime.uses_compatibility_profile()
259 && (2..=*capacity).contains(&subtree_leaves)
260 && capacity * 64 <= shared_bytes
261 });
262 if let Some((_, kernel)) = cooperative {
263 let count = rows / subtree_leaves;
264 let output = Matrix::allocate_output(
265 runtime,
266 vec![count, elements],
267 count * elements,
268 algorithm.dtype(),
269 )?;
270 let groups = runtime.linear_dispatch_grid(count as u32, 1)?;
271 let buffers = [
272 BufferBinding::read(leaves.storage()),
273 BufferBinding::write(output.storage()),
274 ];
275 let push_constants = [
276 PushConstant::U32(count as u32),
277 PushConstant::U32(groups[0]),
278 PushConstant::U32(subtree_leaves as u32),
279 PushConstant::U32(algorithm as u32),
280 ];
281 let attributes = [
282 OpAttribute::UnsignedInteger {
283 name: "leaf_count".into(),
284 value: subtree_leaves as u64,
285 },
286 OpAttribute::UnsignedInteger {
287 name: "algorithm".into(),
288 value: algorithm as u64,
289 },
290 ];
291 runtime.record_semantic(
292 ComputeDispatch {
293 kernel,
294 buffers: &buffers,
295 push_constants: &push_constants,
296 workgroups: groups,
297 indirect: None,
298 },
299 SemanticDispatch {
300 contract: crate::core::operation::crypto::merkle::MERKLE_SUBTREE_REDUCE,
301 inputs: &[leaves],
302 outputs: &[&output],
303 attributes: &attributes,
304 },
305 )?;
306 return Ok(output);
307 }
308 let mut current = leaves.clone();
309 let mut source_count = rows as u32;
310 for _ in 0..subtree_leaves.trailing_zeros() {
311 let count = source_count / 2;
312 let output = Matrix::allocate_output(
313 runtime,
314 vec![count as usize, elements],
315 count as usize * elements,
316 algorithm.dtype(),
317 )?;
318 let groups = runtime.linear_dispatch_grid(count, 128)?;
319 let kernel = if algorithm.is_poseidon2() {
320 KernelId::CryptographyMerkleTreeReducePoseidon2U32
321 } else {
322 KernelId::CryptographyMerkleTreeReduceU32
323 };
324 let buffers = [
325 BufferBinding::read(current.storage()),
326 BufferBinding::write(output.storage()),
327 ];
328 let push_constants = [
329 PushConstant::U32(count),
330 PushConstant::U32(groups[0] * 128),
331 PushConstant::U32(source_count),
332 PushConstant::U32(algorithm as u32),
333 ];
334 let attributes = [
335 OpAttribute::UnsignedInteger {
336 name: "leaf_count".into(),
337 value: u64::from(source_count),
338 },
339 OpAttribute::UnsignedInteger {
340 name: "algorithm".into(),
341 value: algorithm as u64,
342 },
343 ];
344 runtime.record_semantic(
345 ComputeDispatch {
346 kernel,
347 buffers: &buffers,
348 push_constants: &push_constants,
349 workgroups: groups,
350 indirect: None,
351 },
352 SemanticDispatch {
353 contract: crate::core::operation::crypto::merkle::MERKLE_TREE_REDUCE,
354 inputs: &[¤t],
355 outputs: &[&output],
356 attributes: &attributes,
357 },
358 )?;
359 current = output;
360 source_count = count;
361 }
362 Ok(current)
363}
364
365pub fn proofs(tree: &DeviceMerkleTree, indices: &Matrix) -> Result<Matrix> {
373 let rows = match indices.shape() {
374 [rows] => *rows,
375 _ => {
376 return Err(Error::invalid_argument(
377 "Merkle proof indices require rank-one U32 values",
378 ));
379 }
380 };
381 let source = &tree.levels[0];
382 if indices.dtype() != DType::U32 || !indices.runtime().same_as(source.runtime()) {
383 return Err(Error::invalid_argument(
384 "Merkle proof indices require matching Runtime ownership",
385 ));
386 }
387 let depth = tree.levels.len() - 1;
388 let bytes = tree.algorithm.digest_bytes();
389 let frame_bytes = 20 + depth * bytes;
390 let elements = rows
391 .checked_mul(frame_bytes)
392 .ok_or_else(|| Error::invalid_argument("Merkle proof bytes overflow usize"))?;
393 u32::try_from(elements).map_err(|_| Error::invalid_argument("Merkle proof bytes exceed u32"))?;
394 let count =
395 u32::try_from(rows).map_err(|_| Error::invalid_argument("Merkle proof batch exceeds u32"))?;
396 let runtime = source.runtime();
397 let mut frames = Matrix::allocate_output(runtime, vec![rows, frame_bytes], elements, DType::U8)?;
398 if rows == 0 {
399 return Ok(frames);
400 }
401 let groups = runtime.linear_dispatch_grid(count, 128)?;
402 let kernel = KernelId::CryptographyMerkleFrameInitU32;
403 let buffers = [
404 BufferBinding::read(indices.storage()),
405 BufferBinding::write(frames.storage()),
406 ];
407 let push_constants = [
408 PushConstant::U32(count),
409 PushConstant::U32(groups[0] * 128),
410 PushConstant::U32(tree.leaf_count),
411 PushConstant::U32(tree.algorithm as u32),
412 PushConstant::U32(frame_bytes as u32),
413 ];
414 let attributes = [
415 OpAttribute::UnsignedInteger {
416 name: "leaf_count".into(),
417 value: u64::from(tree.leaf_count),
418 },
419 OpAttribute::UnsignedInteger {
420 name: "algorithm".into(),
421 value: tree.algorithm as u64,
422 },
423 ];
424 runtime.record_semantic(
425 ComputeDispatch {
426 kernel,
427 buffers: &buffers,
428 push_constants: &push_constants,
429 workgroups: groups,
430 indirect: None,
431 },
432 SemanticDispatch {
433 contract: crate::core::operation::crypto::merkle::MERKLE_FRAME_INIT,
434 inputs: &[indices],
435 outputs: &[&frames],
436 attributes: &attributes,
437 },
438 )?;
439 for level in 0..depth {
440 let source = &tree.levels[level];
441 let output = frames.reshape_semantic_output(frames.shape().to_vec())?;
442 let kernel = KernelId::CryptographyMerkleFrameAppendU32;
443 let buffers = [
444 BufferBinding::read(source.storage()),
445 BufferBinding::read(indices.storage()),
446 BufferBinding::read(frames.storage()),
447 BufferBinding::write(output.storage()),
448 ];
449 let push_constants = [
450 PushConstant::U32(count),
451 PushConstant::U32(groups[0] * 128),
452 PushConstant::U32(tree.leaf_count),
453 PushConstant::U32(source.shape()[0] as u32),
454 PushConstant::U32(tree.algorithm as u32),
455 PushConstant::U32(frame_bytes as u32),
456 PushConstant::U32(level as u32),
457 ];
458 let attributes = [
459 OpAttribute::UnsignedInteger {
460 name: "leaf_count".into(),
461 value: u64::from(tree.leaf_count),
462 },
463 OpAttribute::UnsignedInteger {
464 name: "algorithm".into(),
465 value: tree.algorithm as u64,
466 },
467 OpAttribute::UnsignedInteger {
468 name: "level".into(),
469 value: level as u64,
470 },
471 ];
472 runtime.record_semantic(
473 ComputeDispatch {
474 kernel,
475 buffers: &buffers,
476 push_constants: &push_constants,
477 workgroups: groups,
478 indirect: None,
479 },
480 SemanticDispatch {
481 contract: crate::core::operation::crypto::merkle::MERKLE_FRAME_APPEND,
482 inputs: &[source, indices, &frames],
483 outputs: &[&output],
484 attributes: &attributes,
485 },
486 )?;
487 frames = output;
488 }
489 Ok(frames)
490}
491
492pub fn verify(
500 leaves: &Matrix,
501 frames: &Matrix,
502 roots: &Matrix,
503 algorithm: MerkleAlgorithm,
504 leaf_count: u32,
505) -> Result<Matrix> {
506 let [rows, elements] = match leaves.shape() {
507 [rows, elements] => [*rows, *elements],
508 _ => {
509 return Err(Error::invalid_argument(
510 "Merkle verify leaves require rank-two digest rows",
511 ));
512 }
513 };
514 if !(1..=(1_u32 << 24)).contains(&leaf_count) {
515 return Err(Error::invalid_argument(
516 "Merkle trusted leaf count is outside 1..=2^24",
517 ));
518 }
519 let depth = (leaf_count - 1).checked_ilog2().map_or(0, |n| n + 1) as usize;
520 let frame_bytes = 20 + depth * algorithm.digest_bytes();
521 if leaves.dtype() != algorithm.dtype()
522 || elements != algorithm.digest_bytes() / leaves.dtype().size_bytes()
523 || frames.dtype() != DType::U8
524 || frames.shape() != [rows, frame_bytes]
525 || roots.dtype() != algorithm.dtype()
526 || roots.shape().len() != 2
527 || roots.shape()[1] != elements
528 || (roots.shape()[0] != 1 && roots.shape()[0] != rows)
529 || !leaves.runtime().same_as(frames.runtime())
530 || !leaves.runtime().same_as(roots.runtime())
531 {
532 return Err(Error::invalid_argument(
533 "Merkle verify requires matching hash extents, version-two frames and Runtime ownership",
534 ));
535 }
536 let count =
537 u32::try_from(rows).map_err(|_| Error::invalid_argument("Merkle verify batch exceeds u32"))?;
538 let input_bytes = rows
539 .checked_mul(frame_bytes)
540 .ok_or_else(|| Error::invalid_argument("Merkle verify byte extent overflows usize"))?;
541 u32::try_from(input_bytes)
542 .map_err(|_| Error::invalid_argument("Merkle verify bytes exceed u32"))?;
543 let runtime = leaves.runtime();
544 let output = Matrix::allocate_output(runtime, vec![rows], rows, DType::U32)?;
545 if count != 0 {
546 let groups = runtime.linear_dispatch_grid(count, 128)?;
547 let kernel = if algorithm.is_poseidon2() {
548 KernelId::CryptographyMerkleFrameVerifyPoseidon2U32
549 } else {
550 KernelId::CryptographyMerkleFrameVerifyU32
551 };
552 let buffers = [
553 BufferBinding::read(leaves.storage()),
554 BufferBinding::read(frames.storage()),
555 BufferBinding::read(roots.storage()),
556 BufferBinding::write(output.storage()),
557 ];
558 let push_constants = [
559 PushConstant::U32(count),
560 PushConstant::U32(groups[0] * 128),
561 PushConstant::U32(leaf_count),
562 PushConstant::U32(algorithm as u32),
563 PushConstant::U32(frame_bytes as u32),
564 PushConstant::U32(roots.shape()[0] as u32),
565 ];
566 let attributes = [
567 OpAttribute::UnsignedInteger {
568 name: "leaf_count".into(),
569 value: u64::from(leaf_count),
570 },
571 OpAttribute::UnsignedInteger {
572 name: "algorithm".into(),
573 value: algorithm as u64,
574 },
575 ];
576 runtime.record_semantic(
577 ComputeDispatch {
578 kernel,
579 buffers: &buffers,
580 push_constants: &push_constants,
581 workgroups: groups,
582 indirect: None,
583 },
584 SemanticDispatch {
585 contract: crate::core::operation::crypto::merkle::MERKLE_FRAME_VERIFY,
586 inputs: &[leaves, frames, roots],
587 outputs: &[&output],
588 attributes: &attributes,
589 },
590 )?;
591 }
592 Ok(output)
593}