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
563
564
565
566
567
use anchor_lang::{
prelude::*,
solana_program::sysvar::{clock::Clock, rent::Rent},
};
use borsh::{BorshDeserialize, BorshSerialize};
use std::mem::size_of;
pub mod canopy;
mod data_wrapper;
pub mod error;
pub mod events;
pub mod state;
pub mod zero_copy;
pub use crate::data_wrapper::{wrap_application_data_v1, Wrapper};
use crate::canopy::{fill_in_proof_from_canopy, update_canopy};
use crate::data_wrapper::wrap_event;
use crate::error::AccountCompressionError;
use crate::events::{AccountCompressionEvent, ChangeLogEvent};
use crate::state::{ConcurrentMerkleTreeHeader, CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1};
use crate::zero_copy::ZeroCopy;
pub use spl_concurrent_merkle_tree::{
concurrent_merkle_tree::ConcurrentMerkleTree, error::ConcurrentMerkleTreeError, node::Node,
};
declare_id!("cmtDvXumGCrqC1Age74AVPhSRVXJMd8PJS91L8KbNCK");
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(zero)]
pub merkle_tree: UncheckedAccount<'info>,
pub authority: Signer<'info>,
pub log_wrapper: Program<'info, Wrapper>,
}
#[derive(Accounts)]
pub struct Modify<'info> {
#[account(mut)]
pub merkle_tree: UncheckedAccount<'info>,
pub authority: Signer<'info>,
pub log_wrapper: Program<'info, Wrapper>,
}
#[derive(Accounts)]
pub struct VerifyLeaf<'info> {
pub merkle_tree: UncheckedAccount<'info>,
}
#[derive(Accounts)]
pub struct TransferAuthority<'info> {
#[account(mut)]
pub merkle_tree: UncheckedAccount<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct CloseTree<'info> {
#[account(mut)]
pub merkle_tree: AccountInfo<'info>,
pub authority: Signer<'info>,
#[account(mut)]
pub recipient: AccountInfo<'info>,
}
macro_rules! merkle_tree_depth_size_apply_fn {
($max_depth:literal, $max_size:literal, $id:ident, $bytes:ident, $func:ident, $($arg:tt)*) => {
match ConcurrentMerkleTree::<$max_depth, $max_size>::load_mut_bytes($bytes) {
Ok(merkle_tree) => {
match merkle_tree.$func($($arg)*) {
Ok(_) => {
Ok(Box::<ChangeLogEvent>::from((merkle_tree.get_change_log(), $id, merkle_tree.sequence_number)))
}
Err(err) => {
msg!("Error using concurrent merkle tree: {}", err);
err!(AccountCompressionError::ConcurrentMerkleTreeError)
}
}
}
Err(err) => {
msg!("Error zero copying concurrent merkle tree: {}", err);
err!(AccountCompressionError::ZeroCopyError)
}
}
}
}
fn merkle_tree_get_size(header: &ConcurrentMerkleTreeHeader) -> Result<usize> {
match (header.get_max_depth(), header.get_max_buffer_size()) {
(3, 8) => Ok(size_of::<ConcurrentMerkleTree<3, 8>>()),
(5, 8) => Ok(size_of::<ConcurrentMerkleTree<5, 8>>()),
(14, 64) => Ok(size_of::<ConcurrentMerkleTree<14, 64>>()),
(14, 256) => Ok(size_of::<ConcurrentMerkleTree<14, 256>>()),
(14, 1024) => Ok(size_of::<ConcurrentMerkleTree<14, 1024>>()),
(14, 2048) => Ok(size_of::<ConcurrentMerkleTree<14, 2048>>()),
(20, 64) => Ok(size_of::<ConcurrentMerkleTree<20, 64>>()),
(20, 256) => Ok(size_of::<ConcurrentMerkleTree<20, 256>>()),
(20, 1024) => Ok(size_of::<ConcurrentMerkleTree<20, 1024>>()),
(20, 2048) => Ok(size_of::<ConcurrentMerkleTree<20, 2048>>()),
(24, 64) => Ok(size_of::<ConcurrentMerkleTree<24, 64>>()),
(24, 256) => Ok(size_of::<ConcurrentMerkleTree<24, 256>>()),
(24, 512) => Ok(size_of::<ConcurrentMerkleTree<24, 512>>()),
(24, 1024) => Ok(size_of::<ConcurrentMerkleTree<24, 1024>>()),
(24, 2048) => Ok(size_of::<ConcurrentMerkleTree<24, 2048>>()),
(26, 512) => Ok(size_of::<ConcurrentMerkleTree<26, 512>>()),
(26, 1024) => Ok(size_of::<ConcurrentMerkleTree<26, 1024>>()),
(26, 2048) => Ok(size_of::<ConcurrentMerkleTree<26, 2048>>()),
(30, 512) => Ok(size_of::<ConcurrentMerkleTree<30, 512>>()),
(30, 1024) => Ok(size_of::<ConcurrentMerkleTree<30, 1024>>()),
(30, 2048) => Ok(size_of::<ConcurrentMerkleTree<30, 2048>>()),
_ => {
msg!(
"Failed to get size of max depth {} and max buffer size {}",
header.get_max_depth(),
header.get_max_buffer_size()
);
err!(AccountCompressionError::ConcurrentMerkleTreeConstantsError)
}
}
}
macro_rules! merkle_tree_apply_fn {
($header:ident, $id:ident, $bytes:ident, $func:ident, $($arg:tt)*) => {
match ($header.get_max_depth(), $header.get_max_buffer_size()) {
(3, 8) => merkle_tree_depth_size_apply_fn!(3, 8, $id, $bytes, $func, $($arg)*),
(5, 8) => merkle_tree_depth_size_apply_fn!(5, 8, $id, $bytes, $func, $($arg)*),
(14, 64) => merkle_tree_depth_size_apply_fn!(14, 64, $id, $bytes, $func, $($arg)*),
(14, 256) => merkle_tree_depth_size_apply_fn!(14, 256, $id, $bytes, $func, $($arg)*),
(14, 1024) => merkle_tree_depth_size_apply_fn!(14, 1024, $id, $bytes, $func, $($arg)*),
(14, 2048) => merkle_tree_depth_size_apply_fn!(14, 2048, $id, $bytes, $func, $($arg)*),
(20, 64) => merkle_tree_depth_size_apply_fn!(20, 64, $id, $bytes, $func, $($arg)*),
(20, 256) => merkle_tree_depth_size_apply_fn!(20, 256, $id, $bytes, $func, $($arg)*),
(20, 1024) => merkle_tree_depth_size_apply_fn!(20, 1024, $id, $bytes, $func, $($arg)*),
(20, 2048) => merkle_tree_depth_size_apply_fn!(20, 2048, $id, $bytes, $func, $($arg)*),
(24, 64) => merkle_tree_depth_size_apply_fn!(24, 64, $id, $bytes, $func, $($arg)*),
(24, 256) => merkle_tree_depth_size_apply_fn!(24, 256, $id, $bytes, $func, $($arg)*),
(24, 512) => merkle_tree_depth_size_apply_fn!(24, 512, $id, $bytes, $func, $($arg)*),
(24, 1024) => merkle_tree_depth_size_apply_fn!(24, 1024, $id, $bytes, $func, $($arg)*),
(24, 2048) => merkle_tree_depth_size_apply_fn!(24, 2048, $id, $bytes, $func, $($arg)*),
(26, 512) => merkle_tree_depth_size_apply_fn!(26, 512, $id, $bytes, $func, $($arg)*),
(26, 1024) => merkle_tree_depth_size_apply_fn!(26, 1024, $id, $bytes, $func, $($arg)*),
(26, 2048) => merkle_tree_depth_size_apply_fn!(26, 2048, $id, $bytes, $func, $($arg)*),
(30, 512) => merkle_tree_depth_size_apply_fn!(30, 512, $id, $bytes, $func, $($arg)*),
(30, 1024) => merkle_tree_depth_size_apply_fn!(30, 1024, $id, $bytes, $func, $($arg)*),
(30, 2048) => merkle_tree_depth_size_apply_fn!(30, 2048, $id, $bytes, $func, $($arg)*),
_ => {
msg!("Failed to apply {} on concurrent merkle tree with max depth {} and max buffer size {}", stringify!($func), $header.get_max_depth(), $header.get_max_buffer_size());
err!(AccountCompressionError::ConcurrentMerkleTreeConstantsError)
}
}
};
}
#[program]
pub mod spl_account_compression {
use super::*;
pub fn init_empty_merkle_tree(
ctx: Context<Initialize>,
max_depth: u32,
max_buffer_size: u32,
) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (mut header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let mut header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.initialize(
max_depth,
max_buffer_size,
&ctx.accounts.authority.key(),
Clock::get()?.slot,
);
header.serialize(&mut header_bytes)?;
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let id = ctx.accounts.merkle_tree.key();
let change_log_event = merkle_tree_apply_fn!(header, id, tree_bytes, initialize,)?;
wrap_event(
&AccountCompressionEvent::ChangeLog(*change_log_event),
&ctx.accounts.log_wrapper,
)?;
update_canopy(canopy_bytes, header.get_max_depth(), None)
}
pub fn replace_leaf(
ctx: Context<Modify>,
root: [u8; 32],
previous_leaf: [u8; 32],
new_leaf: [u8; 32],
index: u32,
) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid_authority(&ctx.accounts.authority.key())?;
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let mut proof = vec![];
for node in ctx.remaining_accounts.iter() {
proof.push(node.key().to_bytes());
}
fill_in_proof_from_canopy(canopy_bytes, header.get_max_depth(), index, &mut proof)?;
let id = ctx.accounts.merkle_tree.key();
let change_log_event = merkle_tree_apply_fn!(
header,
id,
tree_bytes,
set_leaf,
root,
previous_leaf,
new_leaf,
&proof,
index,
)?;
update_canopy(
canopy_bytes,
header.get_max_depth(),
Some(&change_log_event),
)?;
wrap_event(
&AccountCompressionEvent::ChangeLog(*change_log_event),
&ctx.accounts.log_wrapper,
)
}
pub fn transfer_authority(
ctx: Context<TransferAuthority>,
new_authority: Pubkey,
) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (mut header_bytes, _) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let mut header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid_authority(&ctx.accounts.authority.key())?;
header.set_new_authority(&new_authority);
header.serialize(&mut header_bytes)?;
Ok(())
}
pub fn verify_leaf(
ctx: Context<VerifyLeaf>,
root: [u8; 32],
leaf: [u8; 32],
index: u32,
) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid()?;
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let mut proof = vec![];
for node in ctx.remaining_accounts.iter() {
proof.push(node.key().to_bytes());
}
fill_in_proof_from_canopy(canopy_bytes, header.get_max_depth(), index, &mut proof)?;
let id = ctx.accounts.merkle_tree.key();
merkle_tree_apply_fn!(header, id, tree_bytes, prove_leaf, root, leaf, &proof, index)?;
Ok(())
}
pub fn append(ctx: Context<Modify>, leaf: [u8; 32]) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid_authority(&ctx.accounts.authority.key())?;
let id = ctx.accounts.merkle_tree.key();
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let change_log_event = merkle_tree_apply_fn!(header, id, tree_bytes, append, leaf)?;
update_canopy(
canopy_bytes,
header.get_max_depth(),
Some(&change_log_event),
)?;
wrap_event(
&AccountCompressionEvent::ChangeLog(*change_log_event),
&ctx.accounts.log_wrapper,
)
}
pub fn insert_or_append(
ctx: Context<Modify>,
root: [u8; 32],
leaf: [u8; 32],
index: u32,
) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid_authority(&ctx.accounts.authority.key())?;
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let mut proof = vec![];
for node in ctx.remaining_accounts.iter() {
proof.push(node.key().to_bytes());
}
fill_in_proof_from_canopy(canopy_bytes, header.get_max_depth(), index, &mut proof)?;
let id = ctx.accounts.merkle_tree.key();
let change_log_event = merkle_tree_apply_fn!(
header,
id,
tree_bytes,
fill_empty_or_append,
root,
leaf,
&proof,
index,
)?;
update_canopy(
canopy_bytes,
header.get_max_depth(),
Some(&change_log_event),
)?;
wrap_event(
&AccountCompressionEvent::ChangeLog(*change_log_event),
&ctx.accounts.log_wrapper,
)
}
pub fn close_empty_tree(ctx: Context<CloseTree>) -> Result<()> {
require_eq!(
*ctx.accounts.merkle_tree.owner,
crate::id(),
AccountCompressionError::IncorrectAccountOwner
);
let mut merkle_tree_bytes = ctx.accounts.merkle_tree.try_borrow_mut_data()?;
let (header_bytes, rest) =
merkle_tree_bytes.split_at_mut(CONCURRENT_MERKLE_TREE_HEADER_SIZE_V1);
let header = ConcurrentMerkleTreeHeader::try_from_slice(header_bytes)?;
header.assert_valid_authority(&ctx.accounts.authority.key())?;
let merkle_tree_size = merkle_tree_get_size(&header)?;
let (tree_bytes, canopy_bytes) = rest.split_at_mut(merkle_tree_size);
let id = ctx.accounts.merkle_tree.key();
merkle_tree_apply_fn!(header, id, tree_bytes, prove_tree_is_empty,)?;
let dest_starting_lamports = ctx.accounts.recipient.lamports();
**ctx.accounts.recipient.lamports.borrow_mut() = dest_starting_lamports
.checked_add(ctx.accounts.merkle_tree.lamports())
.unwrap();
**ctx.accounts.merkle_tree.lamports.borrow_mut() = 0;
header_bytes.fill(0);
tree_bytes.fill(0);
canopy_bytes.fill(0);
Ok(())
}
}