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
use std::{
    marker::PhantomData,
    mem,
    ops::{Deref, DerefMut},
};

use light_bounded_vec::{
    BoundedVec, BoundedVecMetadata, CyclicBoundedVec, CyclicBoundedVecMetadata,
};
use light_hasher::Hasher;
use light_utils::offset::{read_array_like_ptr_at, read_ptr_at, write_at};
use memoffset::{offset_of, span_of};

use crate::{errors::ConcurrentMerkleTreeError, ConcurrentMerkleTree};

#[derive(Debug)]
pub struct ConcurrentMerkleTreeZeroCopy<'a, H, const HEIGHT: usize>
where
    H: Hasher,
{
    merkle_tree: mem::ManuallyDrop<ConcurrentMerkleTree<H, HEIGHT>>,
    // The purpose of this field is ensuring that the wrapper does not outlive
    // the buffer.
    _bytes: &'a [u8],
}

impl<'a, H, const HEIGHT: usize> ConcurrentMerkleTreeZeroCopy<'a, H, HEIGHT>
where
    H: Hasher,
{
    pub fn struct_from_bytes_zero_copy(
        bytes: &'a [u8],
    ) -> Result<(ConcurrentMerkleTree<H, HEIGHT>, usize), ConcurrentMerkleTreeError> {
        let expected_size = ConcurrentMerkleTree::<H, HEIGHT>::non_dyn_fields_size();
        if bytes.len() < expected_size {
            return Err(ConcurrentMerkleTreeError::BufferSize(
                expected_size,
                bytes.len(),
            ));
        }

        let height = usize::from_ne_bytes(
            bytes[span_of!(ConcurrentMerkleTree<H, HEIGHT>, height)]
                .try_into()
                .unwrap(),
        );
        let canopy_depth = usize::from_ne_bytes(
            bytes[span_of!(ConcurrentMerkleTree<H, HEIGHT>, canopy_depth)]
                .try_into()
                .unwrap(),
        );

        let mut offset = offset_of!(ConcurrentMerkleTree<H, HEIGHT>, next_index);

        let next_index = unsafe { read_ptr_at(bytes, &mut offset) };
        let sequence_number = unsafe { read_ptr_at(bytes, &mut offset) };
        let rightmost_leaf = unsafe { read_ptr_at(bytes, &mut offset) };
        let filled_subtrees_metadata = unsafe { read_ptr_at(bytes, &mut offset) };
        let changelog_metadata: *mut CyclicBoundedVecMetadata =
            unsafe { read_ptr_at(bytes, &mut offset) };
        let roots_metadata: *mut CyclicBoundedVecMetadata =
            unsafe { read_ptr_at(bytes, &mut offset) };
        let canopy_metadata = unsafe { read_ptr_at(bytes, &mut offset) };

        let expected_size = ConcurrentMerkleTree::<H, HEIGHT>::size_in_account(
            height,
            unsafe { (*changelog_metadata).capacity() },
            unsafe { (*roots_metadata).capacity() },
            canopy_depth,
        );
        if bytes.len() < expected_size {
            return Err(ConcurrentMerkleTreeError::BufferSize(
                expected_size,
                bytes.len(),
            ));
        }

        let filled_subtrees = unsafe {
            BoundedVec::from_raw_parts(
                filled_subtrees_metadata,
                read_array_like_ptr_at(bytes, &mut offset, height),
            )
        };
        let changelog = unsafe {
            CyclicBoundedVec::from_raw_parts(
                changelog_metadata,
                read_array_like_ptr_at(bytes, &mut offset, (*changelog_metadata).capacity()),
            )
        };
        let roots = unsafe {
            CyclicBoundedVec::from_raw_parts(
                roots_metadata,
                read_array_like_ptr_at(bytes, &mut offset, (*roots_metadata).capacity()),
            )
        };
        let canopy = unsafe {
            BoundedVec::from_raw_parts(
                canopy_metadata,
                read_array_like_ptr_at(bytes, &mut offset, (*canopy_metadata).capacity()),
            )
        };

        Ok((
            ConcurrentMerkleTree {
                height,
                canopy_depth,
                next_index,
                sequence_number,
                rightmost_leaf,
                filled_subtrees,
                changelog,
                roots,
                canopy,
                _hasher: PhantomData,
            },
            offset,
        ))
    }

    pub fn from_bytes_zero_copy(bytes: &'a [u8]) -> Result<Self, ConcurrentMerkleTreeError> {
        let (merkle_tree, _) = Self::struct_from_bytes_zero_copy(bytes)?;

        Ok(Self {
            merkle_tree: mem::ManuallyDrop::new(merkle_tree),
            _bytes: bytes,
        })
    }
}

impl<'a, H, const HEIGHT: usize> Deref for ConcurrentMerkleTreeZeroCopy<'a, H, HEIGHT>
where
    H: Hasher,
{
    type Target = ConcurrentMerkleTree<H, HEIGHT>;

    fn deref(&self) -> &Self::Target {
        &self.merkle_tree
    }
}

impl<'a, H, const HEIGHT: usize> Drop for ConcurrentMerkleTreeZeroCopy<'a, H, HEIGHT>
where
    H: Hasher,
{
    fn drop(&mut self) {
        // SAFETY: Don't do anything here! Why?
        //
        // * Primitive fields of `ConcurrentMerkleTree` implement `Copy`,
        //   therefore `drop()` has no effect on them - Rust drops them when
        //   they go out of scope.
        // * Don't drop the dynamic fields (`filled_subtrees`, `roots` etc.). In
        //   `ConcurrentMerkleTreeZeroCopy`, they are backed by buffers provided
        //   by the caller. These buffers are going to be eventually deallocated.
        //   Performing an another `drop()` here would result double `free()`
        //   which would result in aborting the program (either with `SIGABRT`
        //   or `SIGSEGV`).
    }
}

#[derive(Debug)]
pub struct ConcurrentMerkleTreeZeroCopyMut<'a, H, const HEIGHT: usize>(
    ConcurrentMerkleTreeZeroCopy<'a, H, HEIGHT>,
)
where
    H: Hasher;

impl<'a, H, const HEIGHT: usize> ConcurrentMerkleTreeZeroCopyMut<'a, H, HEIGHT>
where
    H: Hasher,
{
    pub fn from_bytes_zero_copy_mut(
        bytes: &'a mut [u8],
    ) -> Result<Self, ConcurrentMerkleTreeError> {
        Ok(Self(ConcurrentMerkleTreeZeroCopy::from_bytes_zero_copy(
            bytes,
        )?))
    }

    pub fn fill_non_dyn_fields_in_buffer(
        bytes: &mut [u8],
        height: usize,
        canopy_depth: usize,
        changelog_capacity: usize,
        roots_capacity: usize,
    ) -> Result<usize, ConcurrentMerkleTreeError> {
        let expected_size = ConcurrentMerkleTree::<H, HEIGHT>::size_in_account(
            height,
            changelog_capacity,
            roots_capacity,
            canopy_depth,
        );
        if bytes.len() < expected_size {
            return Err(ConcurrentMerkleTreeError::BufferSize(
                expected_size,
                bytes.len(),
            ));
        }

        bytes[span_of!(ConcurrentMerkleTree<H, HEIGHT>, height)]
            .copy_from_slice(&height.to_ne_bytes());
        bytes[span_of!(ConcurrentMerkleTree<H, HEIGHT>, canopy_depth)]
            .copy_from_slice(&canopy_depth.to_ne_bytes());

        let mut offset = offset_of!(ConcurrentMerkleTree<H, HEIGHT>, next_index);
        // next_index
        write_at::<usize>(bytes, &0_usize.to_ne_bytes(), &mut offset);
        // sequence_number
        write_at::<usize>(bytes, &0_usize.to_ne_bytes(), &mut offset);
        // rightmost_leaf
        write_at::<[u8; 32]>(bytes, &H::zero_bytes()[0], &mut offset);
        // filled_subtrees (metadata)
        let filled_subtrees_metadata = BoundedVecMetadata::new(height);
        write_at::<BoundedVecMetadata>(bytes, &filled_subtrees_metadata.to_ne_bytes(), &mut offset);
        // changelog (metadata)
        let changelog_metadata = CyclicBoundedVecMetadata::new(changelog_capacity);
        write_at::<CyclicBoundedVecMetadata>(bytes, &changelog_metadata.to_ne_bytes(), &mut offset);
        // roots (metadata)
        let roots_metadata = CyclicBoundedVecMetadata::new(roots_capacity);
        write_at::<CyclicBoundedVecMetadata>(bytes, &roots_metadata.to_ne_bytes(), &mut offset);
        // canopy (metadata)
        let canopy_size = ConcurrentMerkleTree::<H, HEIGHT>::canopy_size(canopy_depth);
        let canopy_metadata = BoundedVecMetadata::new(canopy_size);
        write_at::<BoundedVecMetadata>(bytes, &canopy_metadata.to_ne_bytes(), &mut offset);

        Ok(offset)
    }

    pub fn from_bytes_zero_copy_init(
        bytes: &'a mut [u8],
        height: usize,
        canopy_depth: usize,
        changelog_capacity: usize,
        roots_capacity: usize,
    ) -> Result<Self, ConcurrentMerkleTreeError> {
        Self::fill_non_dyn_fields_in_buffer(
            bytes,
            height,
            canopy_depth,
            changelog_capacity,
            roots_capacity,
        )?;
        Self::from_bytes_zero_copy_mut(bytes)
    }
}

impl<'a, H, const HEIGHT: usize> Deref for ConcurrentMerkleTreeZeroCopyMut<'a, H, HEIGHT>
where
    H: Hasher,
{
    type Target = ConcurrentMerkleTree<H, HEIGHT>;

    fn deref(&self) -> &Self::Target {
        &self.0.merkle_tree
    }
}
impl<'a, H, const HEIGHT: usize> DerefMut for ConcurrentMerkleTreeZeroCopyMut<'a, H, HEIGHT>
where
    H: Hasher,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0.merkle_tree
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use ark_bn254::Fr;
    use ark_ff::{BigInteger, PrimeField, UniformRand};
    use light_hasher::Poseidon;
    use rand::{thread_rng, Rng};

    fn load_from_bytes<
        const HEIGHT: usize,
        const CHANGELOG: usize,
        const ROOTS: usize,
        const CANOPY_DEPTH: usize,
        const OPERATIONS: usize,
    >() {
        let mut mt_1 =
            ConcurrentMerkleTree::<Poseidon, HEIGHT>::new(HEIGHT, CHANGELOG, ROOTS, CANOPY_DEPTH)
                .unwrap();
        mt_1.init().unwrap();

        // Create a buffer with random bytes - the `*_init` method should
        // initialize the buffer gracefully and the randomness shouldn't cause
        // undefined behavior.
        let mut bytes = vec![
            0u8;
            ConcurrentMerkleTree::<Poseidon, HEIGHT>::size_in_account(
                HEIGHT,
                CHANGELOG,
                ROOTS,
                CANOPY_DEPTH
            )
        ];
        thread_rng().fill(bytes.as_mut_slice());

        // Initialize a Merkle tree on top of a byte slice.
        {
            let mut mt =
                ConcurrentMerkleTreeZeroCopyMut::<Poseidon, HEIGHT>::from_bytes_zero_copy_init(
                    bytes.as_mut_slice(),
                    HEIGHT,
                    CANOPY_DEPTH,
                    CHANGELOG,
                    ROOTS,
                )
                .unwrap();
            mt.init().unwrap();

            // Ensure that it was properly initialized.
            assert_eq!(mt.height, HEIGHT);
            assert_eq!(mt.canopy_depth, CANOPY_DEPTH,);
            assert_eq!(mt.next_index(), 0);
            assert_eq!(mt.sequence_number(), 0);
            assert_eq!(mt.rightmost_leaf(), Poseidon::zero_bytes()[0]);

            assert_eq!(mt.filled_subtrees.capacity(), HEIGHT);
            assert_eq!(mt.filled_subtrees.len(), HEIGHT);

            assert_eq!(mt.changelog.capacity(), CHANGELOG);
            assert_eq!(mt.changelog.len(), 1);

            assert_eq!(mt.roots.capacity(), ROOTS);
            assert_eq!(mt.roots.len(), 1);

            assert_eq!(
                mt.canopy.capacity(),
                ConcurrentMerkleTree::<Poseidon, HEIGHT>::canopy_size(CANOPY_DEPTH)
            );

            assert_eq!(mt.root(), Poseidon::zero_bytes()[HEIGHT]);
        }

        let mut rng = thread_rng();

        for _ in 0..OPERATIONS {
            // Reload the tree from bytes on each iteration.
            let mut mt_2 =
                ConcurrentMerkleTreeZeroCopyMut::<Poseidon, HEIGHT>::from_bytes_zero_copy_mut(
                    &mut bytes,
                )
                .unwrap();

            let leaf: [u8; 32] = Fr::rand(&mut rng)
                .into_bigint()
                .to_bytes_be()
                .try_into()
                .unwrap();
            mt_1.append(&leaf).unwrap();
            mt_2.append(&leaf).unwrap();

            assert_eq!(mt_1, *mt_2);
        }
    }

    #[test]
    fn test_load_from_bytes_22_256_256_0_1024() {
        load_from_bytes::<22, 256, 256, 0, 1024>()
    }

    #[test]
    fn test_load_from_bytes_22_256_256_10_1024() {
        load_from_bytes::<22, 256, 256, 10, 1024>()
    }
}