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
use anchor_lang::{prelude::msg, solana_program::instruction::TRANSACTION_LEVEL_STACK_HEIGHT};
use bytemuck::{Pod, Zeroable};
use crate::{
syscall::{sys, Sys},
AccountPosition, ErrorCode,
};
pub trait Require<T> {
fn require(self) -> std::result::Result<T, ErrorCode>;
fn require_ref(&self) -> std::result::Result<&T, ErrorCode>;
fn require_mut(&mut self) -> std::result::Result<&mut T, ErrorCode>;
}
impl<T: ErrorIfMissing> Require<T> for Option<T> {
fn require(self) -> std::result::Result<T, ErrorCode> {
self.ok_or(T::ERROR)
}
fn require_ref(&self) -> std::result::Result<&T, ErrorCode> {
self.as_ref().ok_or(T::ERROR)
}
fn require_mut(&mut self) -> std::result::Result<&mut T, ErrorCode> {
self.as_mut().ok_or(T::ERROR)
}
}
pub trait ErrorIfMissing {
const ERROR: ErrorCode;
}
impl ErrorIfMissing for &mut AccountPosition {
const ERROR: ErrorCode = ErrorCode::PositionNotRegistered;
}
impl ErrorIfMissing for &AccountPosition {
const ERROR: ErrorCode = ErrorCode::PositionNotRegistered;
}
macro_rules! log_on_error {
($result:expr, $($args:tt)*) => {{
if $result.is_err() {
msg!($($args)*);
}
$result
}};
}
pub(crate) use log_on_error;
#[derive(Pod, Zeroable, Copy, Clone, Debug, Default)]
#[repr(transparent)]
pub struct Invocation {
caller_heights: BitSet,
}
impl Invocation {
pub(crate) fn start(&mut self) {
self.caller_heights.insert(sys().get_stack_height() as u8);
}
pub(crate) fn end(&mut self) {
self.caller_heights.remove(sys().get_stack_height() as u8);
}
pub fn verify_directly_invoked(&self) -> Result<(), ErrorCode> {
if !self.directly_invoked() {
msg!(
"Current stack height: {}. Invocations: {:?} (indexed from {})",
sys().get_stack_height(),
self,
TRANSACTION_LEVEL_STACK_HEIGHT
);
return Err(ErrorCode::IndirectInvocation);
}
Ok(())
}
pub fn directly_invoked(&self) -> bool {
let height = sys().get_stack_height();
height != 0 && self.caller_heights.contains(height as u8 - 1)
}
}
mod _idl {
use anchor_lang::prelude::*;
#[derive(AnchorSerialize, AnchorDeserialize, Default)]
pub struct Invocation {
pub flags: u8,
}
}
#[derive(Pod, Zeroable, Copy, Clone, Default, PartialEq, Eq)]
#[repr(transparent)]
struct BitSet(u8);
impl BitSet {
fn insert(&mut self, n: u8) {
if n > 7 {
panic!("attempted to set value outside bounds: {}", n);
}
self.0 |= 1 << n;
}
fn remove(&mut self, n: u8) {
self.0 &= !(1 << n);
}
fn contains(&self, n: u8) -> bool {
self.0 >> n & 1 == 1
}
}
impl std::fmt::Debug for BitSet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_tuple("BitSet")
.field(&format_args!("{:#010b}", &self.0))
.finish()
}
}
#[cfg(test)]
mod test {
impl BitSet {
fn set(&mut self, n: u8, state: bool) {
if state {
self.insert(n)
} else {
self.remove(n)
}
}
fn max(&self) -> Option<u32> {
if self.0 == 0 {
None
} else {
Some(7 - self.0.leading_zeros())
}
}
fn min(&self) -> Option<u32> {
if self.0 == 0 {
None
} else {
Some(7 - self.0.trailing_zeros())
}
}
}
use anchor_lang::solana_program::instruction::TRANSACTION_LEVEL_STACK_HEIGHT;
use itertools::Itertools;
use crate::syscall::thread_local_mock::mock_stack_height;
use super::*;
const MAX_DEPTH: u8 = 5 + (TRANSACTION_LEVEL_STACK_HEIGHT as u8);
#[test]
fn never_report_if_none_marked() {
let subject = Invocation::default();
for i in 0..MAX_DEPTH {
mock_stack_height(Some(i as usize));
assert!(!subject.directly_invoked())
}
}
#[test]
fn happy_path() {
let mut subject = Invocation::default();
mock_stack_height(Some(1));
subject.start();
assert!(!subject.directly_invoked());
mock_stack_height(Some(2));
assert!(subject.directly_invoked());
mock_stack_height(Some(3));
assert!(!subject.directly_invoked());
mock_stack_height(Some(4));
assert!(!subject.directly_invoked());
mock_stack_height(Some(5));
assert!(!subject.directly_invoked());
mock_stack_height(Some(1));
subject.end();
mock_stack_height(Some(2));
assert!(!subject.directly_invoked());
}
#[test]
fn check_all_heights_with_one_mark() {
for mark_at in 0..MAX_DEPTH + 1 {
let mut subject = Invocation::default();
mock_stack_height(Some(mark_at as usize));
subject.start();
for check_at in 0..MAX_DEPTH + 1 {
mock_stack_height(Some(check_at as usize));
assert_eq!(
mark_at.checked_add(1).unwrap() == check_at,
subject.directly_invoked()
)
}
mock_stack_height(Some(mark_at as usize));
subject.end();
for check_at in 0..MAX_DEPTH + 1 {
mock_stack_height(Some(check_at as usize));
assert!(!subject.directly_invoked());
}
}
}
#[test]
fn check_all_heights_with_any_marks() {
for size in 0..MAX_DEPTH + 2 {
for combo in (0..MAX_DEPTH + 1).into_iter().combinations(size.into()) {
let mut subject = Invocation::default();
for depth in combo.clone() {
mock_stack_height(Some(depth as usize));
assert!(!subject.directly_invoked())
}
for depth in combo.clone() {
mock_stack_height(Some(depth as usize));
subject.start();
}
for depth in 0..MAX_DEPTH + 1 {
mock_stack_height(Some(depth as usize));
assert_eq!(
depth != 0 && combo.contains(&(depth - 1)),
subject.directly_invoked()
)
}
for depth in combo {
mock_stack_height(Some(depth as usize));
subject.end();
mock_stack_height(Some((depth + 1) as usize));
assert!(!subject.directly_invoked())
}
for depth in 0..MAX_DEPTH + 1 {
mock_stack_height(Some(depth as usize));
assert!(!subject.directly_invoked())
}
}
}
}
#[test]
fn bitset_insert() {
bitset_manipulation(BitSet::insert, true);
}
#[test]
fn bitset_remove() {
bitset_manipulation(BitSet::remove, false);
}
fn bitset_manipulation(mutator: fn(&mut BitSet, u8) -> (), contains: bool) {
for byte in 0..u8::MAX {
for n in 0..8 {
let mut ba = BitSet(byte);
mutator(&mut ba, n);
assert_eq!(contains, ba.contains(n));
for i in 0..8u8 {
if i != n {
assert_eq!(BitSet(byte).contains(i), ba.contains(i));
}
}
ba.set(n, BitSet(byte).contains(n));
assert_eq!(BitSet(byte), ba);
}
}
}
#[test]
fn bitset_extrema() {
assert_eq!(BitSet(0).max(), None);
assert_eq!(BitSet(0).min(), None);
for extremum in 0..8 {
let top = 2u8.checked_pow(extremum + 1).unwrap_or(u8::MAX);
for byte in 2u8.pow(extremum)..top {
assert_eq!(extremum, BitSet(byte).max().unwrap());
assert_eq!(extremum, BitSet(byte.reverse_bits()).min().unwrap());
}
}
}
}