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
use std::mem;

use light_bounded_vec::{BoundedVec, CyclicBoundedVec, Pod};
use light_concurrent_merkle_tree::{
    changelog::ChangelogEntry, errors::ConcurrentMerkleTreeError, ConcurrentMerkleTree,
};
use light_hasher::Hasher;
use num_traits::{CheckedAdd, CheckedSub, ToBytes, Unsigned};

use crate::{errors::IndexedMerkleTreeError, IndexedMerkleTree, RawIndexedElement};

#[derive(Debug)]
pub struct IndexedMerkleTreeZeroCopy<'a, H, I, const HEIGHT: usize>
where
    H: Hasher,
    I: CheckedAdd
        + CheckedSub
        + Copy
        + Clone
        + PartialOrd
        + ToBytes
        + TryFrom<usize>
        + Unsigned
        + Pod,
    usize: From<I>,
{
    pub merkle_tree: &'a IndexedMerkleTree<'a, H, I, HEIGHT>,
}

pub type IndexedMerkleTreeZeroCopy22<'a, H, I> = IndexedMerkleTreeZeroCopy<'a, H, I, 22>;
pub type IndexedMerkleTreeZeroCopy26<'a, H, I> = IndexedMerkleTreeZeroCopy<'a, H, I, 26>;
pub type IndexedMerkleTreeZeroCopy32<'a, H, I> = IndexedMerkleTreeZeroCopy<'a, H, I, 32>;
pub type IndexedMerkleTreeZeroCopy40<'a, H, I> = IndexedMerkleTreeZeroCopy<'a, H, I, 40>;

impl<'a, H, I, const HEIGHT: usize> IndexedMerkleTreeZeroCopy<'a, H, I, HEIGHT>
where
    H: Hasher,
    I: CheckedAdd
        + CheckedSub
        + Copy
        + Clone
        + PartialOrd
        + ToBytes
        + TryFrom<usize>
        + Unsigned
        + Pod,
    usize: From<I>,
{
    /// Casts a byte slice into wrapped `IndexedMerkleTree` structure reference,
    /// without dynamic fields.
    ///
    /// # Purpose
    ///
    /// This method is meant to be used mostly in Solana programs, where memory
    /// constraints are tight and we want to make sure no data is copied.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the alignment and that the slice
    /// provides actual data of the hash set is the caller's responsibility.
    ///
    /// Calling it in async context (or anyhwere where the underlying data can
    /// be moved in the memory) is certainly going to cause undefined behavior.
    pub unsafe fn struct_from_bytes_zero_copy(
        bytes_struct: &'a [u8],
    ) -> Result<Self, IndexedMerkleTreeError> {
        let expected_bytes_struct_size = mem::size_of::<IndexedMerkleTree<'a, H, I, HEIGHT>>();
        if bytes_struct.len() != expected_bytes_struct_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::StructBufferSize(
                    expected_bytes_struct_size,
                    bytes_struct.len(),
                ),
            ));
        }
        let tree: *const IndexedMerkleTree<'a, H, I, HEIGHT> = bytes_struct.as_ptr() as _;

        Ok(Self {
            merkle_tree: &*tree,
        })
    }

    /// Casts a byte slice into wrapped `IndexedMerkleTree` structure reference,
    /// including dynamic fields.
    ///
    /// # Purpose
    ///
    /// This method is meant to be used mostly in Solana programs, where memory
    /// constraints are tight and we want to make sure no data is copied.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the alignment and that the slice
    /// provides actual data of the hash set is the caller's responsibility.
    ///
    /// Calling it in async context (or anyhwere where the underlying data can
    /// be moved in the memory) is certainly going to cause undefined behavior.
    pub unsafe fn from_bytes_zero_copy(
        bytes_struct: &'a [u8],
        bytes_filled_subtrees: &'a [u8],
        bytes_changelog: &'a [u8],
        bytes_roots: &'a [u8],
        bytes_canopy: &'a [u8],
        bytes_indexed_changelog: &'a [u8],
    ) -> Result<Self, IndexedMerkleTreeError> {
        let tree = IndexedMerkleTreeZeroCopyMut::struct_from_bytes_zero_copy_mut(bytes_struct)?;

        if tree.merkle_tree.merkle_tree.height == 0 {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::HeightZero,
            ));
        }
        if tree.merkle_tree.merkle_tree.changelog_capacity == 0 {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::ChangelogZero,
            ));
        }

        // Restore the vectors correctly, by pointing them to the appropriate
        // byte slices as underlying data. The most unsafe part of this code.
        // Here be dragons!
        let expected_bytes_filled_subtrees_size =
            mem::size_of::<[u8; 32]>() * tree.merkle_tree.merkle_tree.height;
        if bytes_filled_subtrees.len() != expected_bytes_filled_subtrees_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::FilledSubtreesBufferSize(
                    expected_bytes_filled_subtrees_size,
                    bytes_filled_subtrees.len(),
                ),
            ));
        }
        tree.merkle_tree.merkle_tree.filled_subtrees = BoundedVec::from_raw_parts(
            bytes_filled_subtrees.as_ptr() as _,
            tree.merkle_tree.merkle_tree.height,
            tree.merkle_tree.merkle_tree.height,
        );

        let expected_bytes_changelog_size = mem::size_of::<ChangelogEntry<HEIGHT>>()
            * tree.merkle_tree.merkle_tree.changelog_capacity;
        if bytes_changelog.len() != expected_bytes_changelog_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::ChangelogBufferSize(
                    expected_bytes_changelog_size,
                    bytes_changelog.len(),
                ),
            ));
        }
        tree.merkle_tree.merkle_tree.changelog = CyclicBoundedVec::from_raw_parts(
            bytes_changelog.as_ptr() as _,
            tree.merkle_tree.merkle_tree.changelog.len(),
            tree.merkle_tree.merkle_tree.changelog.capacity(),
            tree.merkle_tree.merkle_tree.changelog.first_index(),
            tree.merkle_tree.merkle_tree.changelog.last_index(),
        );

        let expected_bytes_roots_size =
            mem::size_of::<[u8; 32]>() * tree.merkle_tree.merkle_tree.roots_capacity;
        if bytes_roots.len() != expected_bytes_roots_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::RootBufferSize(
                    expected_bytes_roots_size,
                    bytes_roots.len(),
                ),
            ));
        }
        tree.merkle_tree.merkle_tree.roots =
            ConcurrentMerkleTree::<'a, H, HEIGHT>::roots_from_bytes(
                bytes_roots,
                tree.merkle_tree.merkle_tree.roots.len(),
                tree.merkle_tree.merkle_tree.roots.capacity(),
                tree.merkle_tree.merkle_tree.roots.first_index(),
                tree.merkle_tree.merkle_tree.roots.last_index(),
            )?;

        let canopy_size = ConcurrentMerkleTree::<'a, H, HEIGHT>::canopy_size(
            tree.merkle_tree.merkle_tree.canopy_depth,
        );
        let expected_canopy_size = mem::size_of::<[u8; 32]>() * canopy_size;
        if bytes_canopy.len() != expected_canopy_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::CanopyBufferSize(
                    expected_canopy_size,
                    bytes_canopy.len(),
                ),
            ));
        }
        tree.merkle_tree.merkle_tree.canopy =
            BoundedVec::from_raw_parts(bytes_canopy.as_ptr() as _, canopy_size, canopy_size);

        let expected_bytes_indexed_changelog_size =
            mem::size_of::<RawIndexedElement<I>>() * tree.merkle_tree.changelog.capacity();
        if bytes_indexed_changelog.len() != expected_bytes_indexed_changelog_size {
            return Err(IndexedMerkleTreeError::ChangelogBufferSize(
                expected_bytes_indexed_changelog_size,
                bytes_indexed_changelog.len(),
            ));
        }
        tree.merkle_tree.changelog = CyclicBoundedVec::from_raw_parts(
            bytes_indexed_changelog.as_ptr() as _,
            tree.merkle_tree.changelog.len(),
            tree.merkle_tree.changelog.capacity(),
            tree.merkle_tree.changelog.first_index(),
            tree.merkle_tree.changelog.last_index(),
        );

        Ok(IndexedMerkleTreeZeroCopy {
            merkle_tree: tree.merkle_tree,
        })
    }
}

#[derive(Debug)]
pub struct IndexedMerkleTreeZeroCopyMut<'a, H, I, const HEIGHT: usize>
where
    H: Hasher,
    I: CheckedAdd
        + CheckedSub
        + Copy
        + Clone
        + PartialOrd
        + ToBytes
        + TryFrom<usize>
        + Unsigned
        + Pod,
    usize: From<I>,
{
    pub merkle_tree: &'a mut IndexedMerkleTree<'a, H, I, HEIGHT>,
}

pub type IndexedMerkleTreeZeroCopyMut22<'a, H, I> = IndexedMerkleTreeZeroCopyMut<'a, H, I, 22>;
pub type IndexedMerkleTreeZeroCopyMut26<'a, H, I> = IndexedMerkleTreeZeroCopyMut<'a, H, I, 26>;
pub type IndexedMerkleTreeZeroCopyMut32<'a, H, I> = IndexedMerkleTreeZeroCopyMut<'a, H, I, 32>;
pub type IndexedMerkleTreeZeroCopyMut40<'a, H, I> = IndexedMerkleTreeZeroCopyMut<'a, H, I, 40>;

impl<'a, H, I, const HEIGHT: usize> IndexedMerkleTreeZeroCopyMut<'a, H, I, HEIGHT>
where
    H: Hasher,
    I: CheckedAdd
        + CheckedSub
        + Copy
        + Clone
        + PartialOrd
        + ToBytes
        + TryFrom<usize>
        + Unsigned
        + Pod,
    usize: From<I>,
{
    /// Casts a byte slice into wrapped `IndexedMerkleTree` structure mutable
    /// reference, without dynamic fields.
    ///
    /// # Purpose
    ///
    /// This method is meant to be used mostly in Solana programs, where memory
    /// constraints are tight and we want to make sure no data is copied.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the alignment and that the slice
    /// provides actual data of the hash set is the caller's responsibility.
    ///
    /// Calling it in async context (or anyhwere where the underlying data can
    /// be moved in the memory) is certainly going to cause undefined behavior.
    pub unsafe fn struct_from_bytes_zero_copy_mut(
        bytes_struct: &'a [u8],
    ) -> Result<Self, IndexedMerkleTreeError> {
        let expected_bytes_struct_size = mem::size_of::<IndexedMerkleTree<'a, H, I, HEIGHT>>();
        if bytes_struct.len() != expected_bytes_struct_size {
            return Err(IndexedMerkleTreeError::ConcurrentMerkleTree(
                ConcurrentMerkleTreeError::StructBufferSize(
                    expected_bytes_struct_size,
                    bytes_struct.len(),
                ),
            ));
        }
        let tree: *mut IndexedMerkleTree<'a, H, I, HEIGHT> = bytes_struct.as_ptr() as _;

        Ok(Self {
            merkle_tree: &mut *tree,
        })
    }

    /// Fills the dynamic fields (vectors) of a newly created
    /// `IndexerMerkleTreeZeroCopyMut` with the data from provided buffers.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the alignment and that the slice
    /// provides actual data of the hash set is the caller's responsibility.
    ///
    /// Calling it in async context (or anyhwere where the underlying data can
    /// be moved in the memory) is certainly going to cause undefined behavior.
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn fill_vectors_mut(
        &mut self,
        bytes_filled_subtrees: &'a mut [u8],
        bytes_changelog: &'a mut [u8],
        bytes_roots: &'a mut [u8],
        bytes_canopy: &'a mut [u8],
        subtrees_length: usize,
        changelog_length: usize,
        changelog_capacity: usize,
        changelog_first_index: usize,
        changelog_last_index: usize,
        roots_length: usize,
        roots_capacity: usize,
        roots_first_index: usize,
        roots_last_index: usize,
        canopy_length: usize,
        bytes_indexed_changelog: &'a mut [u8],
        indexed_changelog_length: usize,
        indexed_changelog_capacity: usize,
        indexed_changelog_first_index: usize,
        indexed_changelog_last_index: usize,
    ) -> Result<(), IndexedMerkleTreeError> {
        self.merkle_tree.merkle_tree.fill_vectors_mut(
            bytes_filled_subtrees,
            bytes_changelog,
            bytes_roots,
            bytes_canopy,
            subtrees_length,
            changelog_length,
            changelog_capacity,
            changelog_first_index,
            changelog_last_index,
            roots_length,
            roots_capacity,
            roots_first_index,
            roots_last_index,
            canopy_length,
        )?;

        #[cfg(feture = "solana")]
        solana_program::msg!(
            "changelog capacity: {}",
            self.merkle_tree.changelog_capacity
        );
        let expected_bytes_indexed_changelog_size =
            mem::size_of::<RawIndexedElement<I>>() * indexed_changelog_capacity;
        #[cfg(feture = "solana")]
        solana_program::msg!(
            "expected_bytes_indexed_changelog_size: {}",
            expected_bytes_indexed_changelog_size
        );
        if bytes_indexed_changelog.len() != expected_bytes_indexed_changelog_size {
            return Err(IndexedMerkleTreeError::ChangelogBufferSize(
                expected_bytes_indexed_changelog_size,
                bytes_indexed_changelog.len(),
            ));
        }
        self.merkle_tree.changelog = CyclicBoundedVec::from_raw_parts(
            bytes_indexed_changelog.as_mut_ptr() as _,
            indexed_changelog_length,
            indexed_changelog_capacity,
            indexed_changelog_first_index,
            indexed_changelog_last_index,
        );

        Ok(())
    }

    /// Casts byte slices into `IndexedMerkleTreeZeroCopyMut` and initializes
    /// the underlying Merkle tree.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the size and alignment of the byte
    /// slices is the caller's responsibility.
    #[allow(clippy::too_many_arguments)]
    pub unsafe fn from_bytes_zero_copy_init(
        bytes_struct: &'a mut [u8],
        bytes_filled_subtrees: &'a mut [u8],
        bytes_changelog: &'a mut [u8],
        bytes_roots: &'a mut [u8],
        bytes_canopy: &'a mut [u8],
        height: usize,
        changelog_size: usize,
        roots_size: usize,
        canopy_depth: usize,
        bytes_indexed_changelog: &'a mut [u8],
        indexed_changelog_size: usize,
    ) -> Result<Self, IndexedMerkleTreeError> {
        let mut tree = Self::struct_from_bytes_zero_copy_mut(bytes_struct)?;

        tree.merkle_tree.merkle_tree.height = height;

        tree.merkle_tree.merkle_tree.changelog_capacity = changelog_size;
        tree.merkle_tree.merkle_tree.changelog_length = 0;
        tree.merkle_tree.merkle_tree.current_changelog_index = 0;

        tree.merkle_tree.merkle_tree.roots_capacity = roots_size;
        tree.merkle_tree.merkle_tree.roots_length = 0;
        tree.merkle_tree.merkle_tree.current_root_index = 0;

        tree.merkle_tree.merkle_tree.canopy_depth = canopy_depth;

        tree.fill_vectors_mut(
            bytes_filled_subtrees,
            bytes_changelog,
            bytes_roots,
            bytes_canopy,
            0,
            0,
            changelog_size,
            0,
            0,
            0,
            roots_size,
            0,
            0,
            0,
            bytes_indexed_changelog,
            0,
            indexed_changelog_size,
            0,
            0,
        )?;

        Ok(tree)
    }

    /// Casts byte slices into `IndexedMerkleTreeZeroCopyMut`.
    ///
    /// # Safety
    ///
    /// This is highly unsafe. Ensuring the size and alignment of the byte
    /// slices is the caller's responsibility.
    pub unsafe fn from_bytes_zero_copy_mut(
        bytes_struct: &'a mut [u8],
        bytes_filled_subtrees: &'a mut [u8],
        bytes_changelog: &'a mut [u8],
        bytes_roots: &'a mut [u8],
        bytes_canopy: &'a mut [u8],
        bytes_indexed_changelog: &'a mut [u8],
    ) -> Result<Self, IndexedMerkleTreeError> {
        let mut tree = Self::struct_from_bytes_zero_copy_mut(bytes_struct)?;

        tree.fill_vectors_mut(
            bytes_filled_subtrees,
            bytes_changelog,
            bytes_roots,
            bytes_canopy,
            tree.merkle_tree.merkle_tree.height,
            tree.merkle_tree.merkle_tree.changelog.len(),
            tree.merkle_tree.merkle_tree.changelog.capacity(),
            tree.merkle_tree.merkle_tree.changelog.first_index(),
            tree.merkle_tree.merkle_tree.changelog.last_index(),
            tree.merkle_tree.merkle_tree.roots.len(),
            tree.merkle_tree.merkle_tree.roots.capacity(),
            tree.merkle_tree.merkle_tree.roots.first_index(),
            tree.merkle_tree.merkle_tree.roots.last_index(),
            ConcurrentMerkleTree::<'a, H, HEIGHT>::canopy_size(
                tree.merkle_tree.merkle_tree.canopy_depth,
            ),
            bytes_indexed_changelog,
            tree.merkle_tree.changelog.len(),
            tree.merkle_tree.changelog.capacity(),
            tree.merkle_tree.changelog.first_index(),
            tree.merkle_tree.changelog.last_index(),
        )?;

        Ok(tree)
    }
}

#[cfg(test)]
mod test {
    use light_hasher::Poseidon;

    use super::*;

    #[test]
    fn test_from_bytes_zero_copy_init() {
        let mut bytes_struct = [0u8; 320];
        let mut bytes_filled_subtrees = [0u8; 832];
        let mut bytes_changelog = [0u8; 1220800];
        let mut bytes_roots = [0u8; 76800];
        let mut bytes_canopy = [0u8; 65472];

        const HEIGHT: usize = 26;
        const CHANGELOG_SIZE: usize = 1400;
        const ROOTS: usize = 2400;
        const CANOPY_DEPTH: usize = 10;

        let mut bytes_indexed_changelog = [0u8; 20480];

        const INDEXED_CHANGELOG_SIZE: usize = 256;

        let mt = unsafe {
            IndexedMerkleTreeZeroCopyMut::<Poseidon, usize, HEIGHT>::from_bytes_zero_copy_init(
                &mut bytes_struct,
                &mut bytes_filled_subtrees,
                &mut bytes_changelog,
                &mut bytes_roots,
                &mut bytes_canopy,
                HEIGHT,
                CHANGELOG_SIZE,
                ROOTS,
                CANOPY_DEPTH,
                &mut bytes_indexed_changelog,
                INDEXED_CHANGELOG_SIZE,
            )
            .unwrap()
        };
        mt.merkle_tree.init().unwrap();

        assert_eq!(
            mt.merkle_tree.merkle_tree.root(),
            [
                31, 216, 114, 222, 104, 109, 25, 228, 3, 94, 104, 27, 124, 142, 79, 197, 7, 102,
                233, 55, 135, 141, 70, 48, 130, 255, 202, 209, 122, 217, 210, 162
            ]
        );
    }
}