tezos-smart-rollup-storage 0.2.2

Higher-level transactional account view over Tezos Smart Rollup durable storage.
Documentation
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// SPDX-FileCopyrightText: 2022-2023 TriliTech <contact@trili.tech>
// SPDX-FileCopyrightText: 2023 Functori <contact@functori.com>
//
// SPDX-License-Identifier: MIT

//! Storage API for transactional storage updates.

use crate::layer::Layer;
use crate::StorageError;
use core::marker::PhantomData;
use tezos_smart_rollup_host::path::{OwnedPath, Path};
use tezos_smart_rollup_host::runtime::Runtime;

extern crate alloc;

/// Failsafe storage interface
pub struct Storage<T: From<OwnedPath>> {
    prefix: String,
    layers: Vec<Layer<T>>,
    phantom: PhantomData<T>,
}

impl<T: From<OwnedPath>> Storage<T> {
    /// Create the initial storage
    pub fn init(name: &impl Path) -> Result<Self, StorageError> {
        let name_bytes = name.as_bytes().to_vec();

        Ok(Self {
            prefix: String::from_utf8(name_bytes)
                .map_err(|_| StorageError::InvalidAccountsPath)?,
            layers: vec![Layer::<T>::with_path(name)],
            phantom: PhantomData,
        })
    }

    /// Get storage's given object in state given by current storage
    /// state/transaction and id
    pub fn get(
        &self,
        host: &impl Runtime,
        id: &impl Path,
    ) -> Result<Option<T>, StorageError> {
        if let Some(top_layer) = self.layers.last() {
            Ok(top_layer.get(host, id)?)
        } else {
            Err(StorageError::NoStorage)
        }
    }

    /// Get immutable object in state before any transaction began
    pub fn get_original(
        &self,
        host: &impl Runtime,
        id: &impl Path,
    ) -> Result<Option<T>, StorageError> {
        if let Some(bottom_layer) = self.layers.first() {
            Ok(bottom_layer.get(host, id)?)
        } else {
            Err(StorageError::NoStorage)
        }
    }

    /// Create a new object as part of current storage state/transaction
    pub fn create_new(
        &mut self,
        host: &mut impl Runtime,
        id: &impl Path,
    ) -> Result<Option<T>, StorageError> {
        if let Some(top_layer) = self.layers.last_mut() {
            Ok(top_layer.create_new(host, id)?)
        } else {
            Err(StorageError::NoStorage)
        }
    }

    pub fn get_or_create(
        &self,
        host: &impl Runtime,
        id: &impl Path,
    ) -> Result<T, StorageError> {
        if let Some(top_layer) = self.layers.last() {
            Ok(top_layer.get_or_create(host, id)?)
        } else {
            Err(StorageError::NoStorage)
        }
    }

    /// Delete an object as part of current storage state/transaction
    pub fn delete(
        &mut self,
        host: &mut impl Runtime,
        id: &impl Path,
    ) -> Result<(), StorageError> {
        if let Some(top_layer) = self.layers.last_mut() {
            top_layer.delete(host, id)
        } else {
            Err(StorageError::NoStorage)
        }
    }

    /// Begin a new transaction
    pub fn begin_transaction(
        &mut self,
        host: &mut impl Runtime,
    ) -> Result<(), StorageError> {
        let new_layer_index = self.layers.len() + 1;
        if let Some(top) = self.layers.last() {
            let new_layer_name = alloc::format!("{}.{}", self.prefix, new_layer_index);
            let new_layer_path = OwnedPath::try_from(new_layer_name.as_bytes().to_vec())?;
            let new_top = top.force_make_copy(host, &new_layer_path)?;
            self.layers.push(new_top);
            Ok(())
        } else {
            Err(StorageError::NoStorage)
        }
    }

    /// Commit current storage state
    pub fn commit_transaction(
        &mut self,
        host: &mut impl Runtime,
    ) -> Result<(), StorageError> {
        if self.layers.len() > 1 {
            if let (Some(top), Some(last)) = (self.layers.pop(), self.layers.last_mut()) {
                last.consume(host, top)
            } else {
                panic!("Could not commit transaction")
            }
        } else {
            Err(StorageError::NoCurrentTransaction)
        }
    }

    /// Abort current storage state
    pub fn rollback_transaction(
        &mut self,
        host: &mut impl Runtime,
    ) -> Result<(), StorageError> {
        if self.layers.len() > 1 {
            if let Some(top) = self.layers.pop() {
                top.discard(host)
            } else {
                panic!("Could not rollback transaction")
            }
        } else {
            Err(StorageError::NoCurrentTransaction)
        }
    }

    /// Get the number of active storage transaction layers, ie, the stack's depth.
    /// Note that the bottom layer of the storage transaction stack is _not_ a transaction
    /// itself, but rather the original storage before there was any storage modification
    /// currently in progress.
    pub fn stack_depth(&self) -> usize {
        self.layers.len() - 1
    }
}

#[cfg(test)]
mod test {
    use crate::storage::Storage;
    use host::path::{concat, OwnedPath, RefPath};
    use host::runtime::Runtime;
    use tezos_smart_rollup_mock::MockHost;

    #[derive(PartialEq, Debug)]
    struct TestAccount {
        path: OwnedPath,
    }

    const VALUE_A_PATH: RefPath = RefPath::assert_from(b"/a");
    const VALUE_B_PATH: RefPath = RefPath::assert_from(b"/b");

    impl TestAccount {
        pub fn set_a(&mut self, host: &mut impl Runtime, v: &str) {
            let value_path = concat(&self.path, &VALUE_A_PATH)
                .expect("The account should have a path for a");
            host.store_write(&value_path, v.as_bytes(), 0)
                .expect("Cannot set value for b")
        }

        pub fn set_b(&mut self, host: &mut impl Runtime, v: &str) {
            let value_path = concat(&self.path, &VALUE_B_PATH)
                .expect("The account should have a path for b");
            host.store_write(&value_path, v.as_bytes(), 0)
                .expect("Cannot set value for b")
        }

        pub fn get_a(&self, host: &impl Runtime) -> Vec<u8> {
            let value_path = concat(&self.path, &VALUE_A_PATH)
                .expect("The account should have a path for a");
            host.store_read(&value_path, 0, 1024)
                .expect("No value for a")
        }

        pub fn get_b(&self, host: &impl Runtime) -> Vec<u8> {
            let value_path = concat(&self.path, &VALUE_B_PATH)
                .expect("The account should have a path for b");
            host.store_read(&value_path, 0, 1024)
                .expect("No value for b")
        }
    }

    impl From<OwnedPath> for TestAccount {
        fn from(path: OwnedPath) -> Self {
            Self { path }
        }
    }

    const ACCOUNTS_PATH: RefPath = RefPath::assert_from(b"/accounts");

    #[test]
    fn test_commit() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        let mut a = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage during transaction");

        a.set_a(&mut host, "a11");
        a.set_b(&mut host, "b11");

        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        let a11 = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage after commit");
        assert_eq!(a11.get_a(&host), b"a11");
        assert_eq!(a11.get_b(&host), b"b11");

        let a21 = storage
            .get(&host, &a2_name)
            .expect("Cannot get account a1")
            .expect("No account a2 in storage after commit");
        assert_eq!(a21.get_a(&host), b"a2");
        assert_eq!(a21.get_b(&host), b"b2");
    }

    #[test]
    fn test_rollback() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        let mut a = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage during transaction");

        a.set_a(&mut host, "a11");
        a.set_b(&mut host, "b11");

        storage
            .rollback_transaction(&mut host)
            .expect("Cannot rollback transaction");

        // Assert
        let a11 = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage after commit");
        assert_eq!(a11.get_a(&host), b"a1");
        assert_eq!(a11.get_b(&host), b"b1");

        let a21 = storage
            .get(&host, &a2_name)
            .expect("Cannot get account a1")
            .expect("No account a2 in storage after commit");
        assert_eq!(a21.get_a(&host), b"a2");
        assert_eq!(a21.get_b(&host), b"b2");
    }

    #[test]
    fn test_original_account() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        let mut a = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage during transaction");
        a.set_a(&mut host, "a11");
        a.set_b(&mut host, "b11");

        // Test original account content while inside transaction
        let oa = storage
            .get_original(&host, &a1_name)
            .expect("Cannot get original account a1")
            .expect("No original account a1 in storage during transaction");
        assert_eq!(oa.get_a(&host), b"a1");
        assert_eq!(oa.get_b(&host), b"b1");

        // Commit
        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        let a11 = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage after commit");
        assert_eq!(a11.get_a(&host), b"a11");
        assert_eq!(a11.get_b(&host), b"b11");

        let a21 = storage
            .get(&host, &a2_name)
            .expect("Cannot get account a1")
            .expect("No account a2 in storage after commit");
        assert_eq!(a21.get_a(&host), b"a2");
        assert_eq!(a21.get_b(&host), b"b2");
    }

    #[test]
    fn create_new_account_in_transaction() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        let a1_name = RefPath::assert_from(b"/alpha");

        // Arrange
        // - start with no accounts in storage

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        let mut a = storage
            .create_new(&mut host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage during transaction");
        a.set_a(&mut host, "a1");
        a.set_b(&mut host, "b1");

        let oa = storage
            .get_original(&host, &a1_name)
            .expect("Cannot get original account a1");

        assert_eq!(oa, None);

        // Commit
        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        let a11 = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage after commit");
        assert_eq!(a11.get_a(&host), b"a1");
        assert_eq!(a11.get_b(&host), b"b1");
    }

    #[test]
    fn do_nothing() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        // - start with no accounts in storage

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        // Commit
        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        // - nothing to assert as store is all empty
    }

    #[test]
    fn delete_account_in_transaction() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        storage
            .delete(&mut host, &a1_name)
            .expect("Cannot delete account");

        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        let a11 = storage.get(&host, &a1_name).expect("Cannot get account a1");
        assert_eq!(a11, None);

        let a21 = storage
            .get(&host, &a2_name)
            .expect("Cannot get account a1")
            .expect("No account a2 in storage after commit");
        assert_eq!(a21.get_a(&host), b"a2");
        assert_eq!(a21.get_b(&host), b"b2");
    }

    #[test]
    fn delete_all_accounts_in_transaction() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        storage
            .delete(&mut host, &a1_name)
            .expect("Cannot delete account a1");
        storage
            .delete(&mut host, &a2_name)
            .expect("Cannot delete account a2");

        storage
            .commit_transaction(&mut host)
            .expect("Cannot commit transaction");

        // Assert
        let a11 = storage.get(&host, &a1_name).expect("Cannot get account a1");
        assert_eq!(a11, None);

        let a21 = storage.get(&host, &a2_name).expect("Cannot get account a1");
        assert_eq!(a21, None);
    }

    #[test]
    fn delete_account_but_rollback() {
        let mut host = MockHost::default();

        let mut storage = Storage::<TestAccount>::init(&ACCOUNTS_PATH)
            .expect("Could not create basic storage interface@");

        // Arrange
        let a1_name = RefPath::assert_from(b"/alpha");
        let a2_name = RefPath::assert_from(b"/beta");

        let mut a1 = storage
            .create_new(&mut host, &a1_name)
            .expect("Unable to get first account")
            .expect("No account in storage");
        let mut a2 = storage
            .create_new(&mut host, &a2_name)
            .expect("Unable to get second account")
            .expect("No account in storage");

        a1.set_a(&mut host, "a1");
        a1.set_b(&mut host, "b1");
        a2.set_a(&mut host, "a2");
        a2.set_b(&mut host, "b2");

        // Act
        storage
            .begin_transaction(&mut host)
            .expect("Cannot begin transaction");

        storage
            .delete(&mut host, &a1_name)
            .expect("Cannot delete account a1");
        storage
            .delete(&mut host, &a2_name)
            .expect("Cannot delete account a2");

        storage
            .rollback_transaction(&mut host)
            .expect("Cannot rollback transaction");

        // Assert
        let a11 = storage
            .get(&host, &a1_name)
            .expect("Cannot get account a1")
            .expect("No account a1 in storage after commit");
        assert_eq!(a11.get_a(&host), b"a1");
        assert_eq!(a11.get_b(&host), b"b1");

        let a21 = storage
            .get(&host, &a2_name)
            .expect("Cannot get account a1")
            .expect("No account a2 in storage after commit");
        assert_eq!(a21.get_a(&host), b"a2");
        assert_eq!(a21.get_b(&host), b"b2");
    }
}