rvm-cap 0.1.1

Capability system for RVM with P1/P2 proof verification (ADR-135)
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
//! Derivation tree for capability revocation propagation.
//!
//! When a capability is derived (via `grant`), a parent-child relationship
//! is established in this tree. Revoking a parent invalidates all derived
//! capabilities (children, grandchildren, etc.) via subtree walk.

use crate::error::{CapError, CapResult};
use crate::DEFAULT_CAP_TABLE_CAPACITY;

/// A node in the derivation tree.
///
/// Uses a first-child / next-sibling linked list layout for O(1)
/// insertion and efficient subtree traversal without allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DerivationNode {
    /// Whether this node is valid (not revoked).
    pub is_valid: bool,
    /// Depth in the derivation tree (0 = root).
    pub depth: u8,
    /// Epoch at which this capability was created.
    pub epoch: u64,
    /// Index of the first child (or `u32::MAX` if no children).
    pub first_child: u32,
    /// Index of the next sibling (or `u32::MAX` if no sibling).
    pub next_sibling: u32,
    /// Cached parent index for O(1) parent lookup.
    /// `u32::MAX` means no parent (root node).
    pub parent_index: u32,
}

impl DerivationNode {
    /// An empty (unused) node.
    #[inline]
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            is_valid: false,
            depth: 0,
            epoch: 0,
            first_child: u32::MAX,
            next_sibling: u32::MAX,
            parent_index: u32::MAX,
        }
    }

    /// A new root node at the given epoch.
    #[inline]
    #[must_use]
    pub const fn new_root(epoch: u64) -> Self {
        Self {
            is_valid: true,
            depth: 0,
            epoch,
            first_child: u32::MAX,
            next_sibling: u32::MAX,
            parent_index: u32::MAX,
        }
    }

    /// A new child node at the given depth and epoch.
    #[inline]
    #[must_use]
    pub const fn new_child(depth: u8, epoch: u64) -> Self {
        Self {
            is_valid: true,
            depth,
            epoch,
            first_child: u32::MAX,
            next_sibling: u32::MAX,
            parent_index: u32::MAX,
        }
    }

    /// Returns true if this node has children.
    #[inline]
    #[must_use]
    pub const fn has_children(&self) -> bool {
        self.first_child != u32::MAX
    }
}

impl Default for DerivationNode {
    fn default() -> Self {
        Self::empty()
    }
}

/// Derivation tree for tracking parent-child capability relationships.
///
/// Fixed-size array indexed by slot index. No heap allocation.
pub struct DerivationTree<const N: usize = DEFAULT_CAP_TABLE_CAPACITY> {
    /// Nodes indexed by capability slot index.
    nodes: [DerivationNode; N],
    /// Number of active (valid) nodes.
    count: usize,
}

impl<const N: usize> DerivationTree<N> {
    /// Creates a new empty derivation tree.
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            nodes: [DerivationNode::empty(); N],
            count: 0,
        }
    }

    /// Returns the number of active nodes.
    #[inline]
    #[must_use]
    pub const fn len(&self) -> usize {
        self.count
    }

    /// Returns true if the tree has no active nodes.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// Registers a root capability in the tree.
    ///
    /// # Errors
    ///
    /// Returns [`CapError::TreeFull`] if the index is out of bounds.
    pub fn add_root(&mut self, index: u32, epoch: u64) -> CapResult<()> {
        let idx = index as usize;
        if idx >= N {
            return Err(CapError::TreeFull);
        }
        self.nodes[idx] = DerivationNode::new_root(epoch);
        self.count += 1;
        Ok(())
    }

    /// Registers a derived capability in the tree, linking it to its parent.
    ///
    /// # Errors
    ///
    /// Returns [`CapError::TreeFull`] if either index is out of bounds.
    /// Returns [`CapError::Revoked`] if the parent node has been revoked.
    pub fn add_child(
        &mut self,
        parent_index: u32,
        child_index: u32,
        depth: u8,
        epoch: u64,
    ) -> CapResult<()> {
        let pidx = parent_index as usize;
        let cidx = child_index as usize;

        if pidx >= N || cidx >= N {
            return Err(CapError::TreeFull);
        }
        if !self.nodes[pidx].is_valid {
            return Err(CapError::Revoked);
        }

        // Create child node and link to parent's child list (prepend).
        let mut child = DerivationNode::new_child(depth, epoch);
        child.next_sibling = self.nodes[pidx].first_child;
        child.parent_index = parent_index;
        self.nodes[pidx].first_child = child_index;
        self.nodes[cidx] = child;
        self.count += 1;

        Ok(())
    }

    /// Revokes a node and all its descendants. Returns the count of revoked nodes.
    ///
    /// # Errors
    ///
    /// Returns [`CapError::InvalidHandle`] if the index is out of bounds.
    /// Returns [`CapError::Revoked`] if the node has already been revoked.
    pub fn revoke(&mut self, index: u32) -> CapResult<usize> {
        let idx = index as usize;
        if idx >= N {
            return Err(CapError::InvalidHandle);
        }
        if !self.nodes[idx].is_valid {
            return Err(CapError::Revoked);
        }
        Ok(self.revoke_subtree(index))
    }

    /// Returns the depth of the node at the given index.
    ///
    /// # Errors
    ///
    /// Returns [`CapError::InvalidHandle`] if the index is invalid or the node is revoked.
    pub fn depth(&self, index: u32) -> CapResult<u8> {
        let idx = index as usize;
        if idx >= N || !self.nodes[idx].is_valid {
            return Err(CapError::InvalidHandle);
        }
        Ok(self.nodes[idx].depth)
    }

    /// Returns true if the node at the given index is valid.
    #[must_use]
    pub fn is_valid(&self, index: u32) -> bool {
        let idx = index as usize;
        idx < N && self.nodes[idx].is_valid
    }

    /// Returns a reference to a node by index.
    #[must_use]
    pub fn get(&self, index: u32) -> Option<&DerivationNode> {
        let idx = index as usize;
        if idx < N && self.nodes[idx].is_valid {
            Some(&self.nodes[idx])
        } else {
            None
        }
    }

    /// Collect all valid indices in the subtree rooted at `index`.
    ///
    /// Returns a fixed-size array of indices (up to N). This is used
    /// by revocation to synchronize the capability table.
    ///
    /// Uses an iterative stack to avoid stack overflow on wide trees.
    #[must_use]
    pub fn collect_subtree(&self, index: u32) -> [u32; N] {
        let mut result = [u32::MAX; N];
        let mut result_count = 0;
        let mut stack = [u32::MAX; N];
        let mut stack_top = 0;

        // Push the root.
        let idx = index as usize;
        if idx < N && self.nodes[idx].is_valid {
            stack[stack_top] = index;
            stack_top += 1;
        }

        while stack_top > 0 {
            stack_top -= 1;
            let current = stack[stack_top];
            let cidx = current as usize;
            if cidx >= N || !self.nodes[cidx].is_valid {
                continue;
            }

            if result_count < N {
                result[result_count] = current;
                result_count += 1;
            }

            // Push children.
            let mut child = self.nodes[cidx].first_child;
            while child != u32::MAX {
                let child_idx = child as usize;
                if child_idx >= N {
                    break;
                }
                if self.nodes[child_idx].is_valid && stack_top < N {
                    stack[stack_top] = child;
                    stack_top += 1;
                }
                child = self.nodes[child_idx].next_sibling;
            }
        }

        result
    }

    /// Find the parent of a given node.
    ///
    /// Uses the cached `parent_index` field for O(1) lookup. Falls back
    /// to O(N) scan if the cached index is stale (should not happen in
    /// normal operation).
    ///
    /// Returns `None` for root nodes or if the parent is not found.
    #[must_use]
    pub fn find_parent(&self, child_index: u32) -> Option<u32> {
        let cidx = child_index as usize;
        if cidx >= N || !self.nodes[cidx].is_valid {
            return None;
        }
        // Root nodes have no parent.
        if self.nodes[cidx].depth == 0 {
            return None;
        }
        // O(1) fast path via cached parent_index.
        let pidx = self.nodes[cidx].parent_index;
        if pidx != u32::MAX {
            let pi = pidx as usize;
            if pi < N && self.nodes[pi].is_valid {
                return Some(pidx);
            }
        }
        // Fallback: scan all nodes to find one whose child chain
        // includes child_index (handles stale parent_index).
        for i in 0..N {
            if !self.nodes[i].is_valid {
                continue;
            }
            let mut cursor = self.nodes[i].first_child;
            while cursor != u32::MAX {
                if cursor == child_index {
                    return Some(u32::try_from(i).unwrap_or(u32::MAX));
                }
                let c = cursor as usize;
                if c >= N {
                    break;
                }
                cursor = self.nodes[c].next_sibling;
            }
        }
        None
    }

    /// # Security
    ///
    /// The previous recursive implementation could overflow the stack on
    /// wide trees (e.g., 256 siblings under one parent). This iterative
    /// version uses a fixed-size stack bounded by N to prevent stack
    /// exhaustion denial-of-service.
    fn revoke_subtree(&mut self, index: u32) -> usize {
        let mut stack = [u32::MAX; N];
        let mut stack_top: usize = 0;
        let mut count: usize = 0;

        // Push the root of the subtree.
        let root_idx = index as usize;
        if root_idx >= N || !self.nodes[root_idx].is_valid {
            return 0;
        }
        stack[stack_top] = index;
        stack_top += 1;

        while stack_top > 0 {
            stack_top -= 1;
            let current = stack[stack_top];
            let cidx = current as usize;

            if cidx >= N || !self.nodes[cidx].is_valid {
                continue;
            }

            // Revoke this node.
            self.nodes[cidx].is_valid = false;
            self.count = self.count.saturating_sub(1);
            count += 1;

            // Push all children onto the stack.
            let mut child = self.nodes[cidx].first_child;
            while child != u32::MAX {
                let child_idx = child as usize;
                if child_idx >= N {
                    break;
                }
                if self.nodes[child_idx].is_valid && stack_top < N {
                    stack[stack_top] = child;
                    stack_top += 1;
                }
                // Read sibling BEFORE potentially invalidating the node.
                child = self.nodes[child_idx].next_sibling;
            }
        }

        count
    }
}

impl<const N: usize> Default for DerivationTree<N> {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_add_root() {
        let mut tree = DerivationTree::<64>::new();
        tree.add_root(0, 1).unwrap();
        assert_eq!(tree.len(), 1);
        assert!(tree.is_valid(0));
        assert_eq!(tree.depth(0).unwrap(), 0);
    }

    #[test]
    fn test_add_child() {
        let mut tree = DerivationTree::<64>::new();
        tree.add_root(0, 1).unwrap();
        tree.add_child(0, 1, 1, 1).unwrap();
        assert_eq!(tree.len(), 2);
        assert!(tree.is_valid(1));
        assert_eq!(tree.depth(1).unwrap(), 1);
        assert!(tree.get(0).unwrap().has_children());
    }

    #[test]
    fn test_revoke_subtree() {
        let mut tree = DerivationTree::<64>::new();
        tree.add_root(0, 1).unwrap();
        tree.add_child(0, 1, 1, 1).unwrap();
        tree.add_child(0, 2, 1, 1).unwrap();
        tree.add_child(1, 3, 2, 1).unwrap();

        let revoked = tree.revoke(0).unwrap();
        assert_eq!(revoked, 4);
        assert_eq!(tree.len(), 0);
    }

    #[test]
    fn test_partial_revoke() {
        let mut tree = DerivationTree::<64>::new();
        tree.add_root(0, 1).unwrap();
        tree.add_child(0, 1, 1, 1).unwrap();
        tree.add_child(0, 2, 1, 1).unwrap();
        tree.add_child(1, 3, 2, 1).unwrap();

        let revoked = tree.revoke(1).unwrap();
        assert_eq!(revoked, 2);
        assert!(tree.is_valid(0));
        assert!(!tree.is_valid(1));
        assert!(tree.is_valid(2));
        assert!(!tree.is_valid(3));
    }

    #[test]
    fn test_add_child_to_revoked_parent() {
        let mut tree = DerivationTree::<64>::new();
        tree.add_root(0, 1).unwrap();
        tree.revoke(0).unwrap();
        assert_eq!(tree.add_child(0, 1, 1, 1), Err(CapError::Revoked));
    }

    #[test]
    fn test_out_of_bounds() {
        let mut tree = DerivationTree::<4>::new();
        assert_eq!(tree.add_root(10, 1), Err(CapError::TreeFull));
    }
}