piecrust/
call_tree.rs

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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use std::marker::PhantomData;
use std::mem;

use piecrust_uplink::ContractId;

/// An element of the call tree.
#[derive(Debug, Clone, Copy)]
pub struct CallTreeElem {
    pub contract_id: ContractId,
    pub limit: u64,
    pub spent: u64,
    pub mem_len: usize,
}

/// The tree of contract calls.
#[derive(Debug, Default)]
pub struct CallTree(Option<*mut CallTreeNode>);

impl CallTree {
    /// Creates a new empty call tree, starting with the given contract.
    pub(crate) const fn new() -> Self {
        Self(None)
    }

    /// Push an element to the call tree.
    ///
    /// This pushes a new child to the current node, and advances to it.
    pub(crate) fn push(&mut self, elem: CallTreeElem) {
        match self.0 {
            None => self.0 = Some(CallTreeNode::new(elem)),
            Some(inner) => unsafe {
                let node = CallTreeNode::with_parent(elem, inner);
                (*inner).children.push(node);
                self.0 = Some(node)
            },
        }
    }

    /// Moves to the parent node and set the gas spent of the current element,
    /// returning it.
    pub(crate) fn move_up(&mut self, spent: u64) -> Option<CallTreeElem> {
        self.0.map(|inner| unsafe {
            (*inner).elem.spent = spent;
            let elem = (*inner).elem;

            let parent = (*inner).parent;
            if parent.is_none() {
                free_tree(inner);
            }
            self.0 = parent;

            elem
        })
    }

    /// Moves to the parent node, clearing the tree under it, and returns the
    /// current element.
    pub(crate) fn move_up_prune(&mut self) -> Option<CallTreeElem> {
        self.0.map(|inner| unsafe {
            let elem = (*inner).elem;

            let parent = (*inner).parent;
            if let Some(parent) = parent {
                (*parent).children.pop();
            }
            free_tree(inner);
            self.0 = parent;

            elem
        })
    }

    /// Give the current node the amount spent and recursively update amount
    /// spent to accurately reflect what each node spent during each call.
    pub(crate) fn update_spent(&mut self, spent: u64) {
        if let Some(inner) = self.0 {
            unsafe {
                (*inner).elem.spent = spent;
                update_spent(inner);
            }
        }
    }

    /// Returns the `n`th parent element counting from the current node. The
    /// zeroth parent element is the current node.
    pub(crate) fn nth_parent(&self, n: usize) -> Option<CallTreeElem> {
        let mut current = self.0;

        let mut i = 0;
        while i < n {
            current = current.and_then(|inner| unsafe { (*inner).parent });
            i += 1;
        }

        current.map(|inner| unsafe { (*inner).elem })
    }

    /// Returns all call ids.
    pub(crate) fn call_ids(&self) -> Vec<&ContractId> {
        let mut v = Vec::new();
        let mut current = self.0;

        while current.is_some() {
            let p = *current.as_ref().unwrap();
            v.push(unsafe { &(*p).elem.contract_id });
            current = current.and_then(|inner| unsafe { (*inner).parent });
        }

        v
    }

    /// Clears the call tree of all elements.
    pub(crate) fn clear(&mut self) {
        unsafe {
            if let Some(inner) = self.0 {
                let mut root = inner;

                while let Some(parent) = (*root).parent {
                    root = parent;
                }

                self.0 = None;
                free_tree(root);
            }
        }
    }

    /// Returns an iterator over the call tree, starting from the rightmost
    /// leaf, and proceeding to the top of the current position of the tree.
    pub fn iter(&self) -> impl Iterator<Item = &CallTreeElem> {
        CallTreeIter {
            tree: self.0.map(|root| unsafe {
                let mut node = root;

                while !(*node).children.is_empty() {
                    let last_index = (*node).children.len() - 1;
                    node = (*node).children[last_index];
                }

                Subtree { root, node }
            }),
            _marker: PhantomData,
        }
    }
}

struct Subtree {
    root: *mut CallTreeNode,
    node: *mut CallTreeNode,
}

impl Drop for CallTree {
    fn drop(&mut self) {
        self.clear()
    }
}

unsafe fn update_spent(node: *mut CallTreeNode) {
    let node = &mut *node;
    node.children.iter_mut().for_each(|&mut child| unsafe {
        // It should be impossible for this to underflow since the amount spent
        // in all child nodes is always less than or equal to the amount spent
        // in the parent node.
        node.elem.spent -= (*child).elem.spent;
        update_spent(child);
    });
}

unsafe fn free_tree(root: *mut CallTreeNode) {
    let mut node = Box::from_raw(root);

    let mut children = Vec::new();
    mem::swap(&mut node.children, &mut children);

    for child in children {
        free_tree(child);
    }
}

struct CallTreeNode {
    elem: CallTreeElem,
    children: Vec<*mut Self>,
    parent: Option<*mut Self>,
}

impl CallTreeNode {
    fn new(elem: CallTreeElem) -> *mut Self {
        Box::leak(Box::new(Self {
            elem,
            children: Vec::new(),
            parent: None,
        }))
    }

    fn with_parent(elem: CallTreeElem, parent: *mut Self) -> *mut Self {
        Box::leak(Box::new(Self {
            elem,
            children: Vec::new(),
            parent: Some(parent),
        }))
    }
}

/// An iterator over a [`CallTree`].
///
/// It starts at the rightmost node and proceeds leftward towards its siblings,
/// up toward the root.
struct CallTreeIter<'a> {
    tree: Option<Subtree>,
    _marker: PhantomData<&'a ()>,
}

impl<'a> Iterator for CallTreeIter<'a> {
    type Item = &'a CallTreeElem;

    fn next(&mut self) -> Option<Self::Item> {
        // SAFETY: This is safe since we guarantee that the tree exists between
        // the root and the current node. This is done by ensuring the iterator
        // can only exist during the lifetime of the tree.
        unsafe {
            let tree = self.tree.as_mut()?;

            let node = tree.node;
            let elem = &(*node).elem;

            if node == tree.root {
                self.tree = None;
                return Some(elem);
            }

            let parent = (*node).parent.expect(
                "There should always be a parent in a subtree before the root",
            );

            tree.node = {
                let node_index = (*parent)
                    .children
                    .iter()
                    .position(|&n| n == node)
                    .expect("The child must be the its parent's child");

                if node_index == 0 {
                    parent
                } else {
                    let sibling_index = node_index - 1;
                    let mut next_node = (*parent).children[sibling_index];

                    while !(*next_node).children.is_empty() {
                        let last_index = (*next_node).children.len() - 1;
                        next_node = (*next_node).children[last_index];
                    }

                    next_node
                }
            };

            Some(elem)
        }
    }
}