1use std::sync::Arc;
10
11use crate::bytecode::{Cap, CapRights, NativeIdx, NativeMask, RevocationCell, Value};
12
13use super::fault::Fault;
14
15pub use super::fault::NativeCallError;
16
17pub type NativeResult = Result<Value, Fault>;
19
20pub type NativeFn = Arc<dyn Fn(&[Value]) -> NativeResult + Send + Sync>;
22
23pub struct NativeTable {
26 entries: Vec<Option<(String, NativeFn)>>,
27}
28
29impl NativeTable {
30 pub fn builder() -> NativeTableBuilder {
31 NativeTableBuilder {
32 entries: Vec::new(),
33 }
34 }
35
36 pub fn empty() -> Arc<NativeTable> {
38 Arc::new(NativeTable {
39 entries: Vec::new(),
40 })
41 }
42
43 #[inline]
44 pub fn get(&self, index: u32) -> Option<&NativeFn> {
45 self.entries
46 .get(index as usize)
47 .and_then(|slot| slot.as_ref())
48 .map(|(_, f)| f)
49 }
50
51 pub fn index_of(&self, name: &str) -> Option<u32> {
52 self.entries
53 .iter()
54 .enumerate()
55 .find(|(_, slot)| slot.as_ref().is_some_and(|(n, _)| n == name))
56 .map(|(i, _)| i as u32)
57 }
58
59 pub fn len(&self) -> usize {
62 self.entries.len()
63 }
64
65 pub fn is_empty(&self) -> bool {
66 self.entries.is_empty()
67 }
68
69 pub fn names(&self) -> impl Iterator<Item = &str> {
70 self.entries
71 .iter()
72 .filter_map(|slot| slot.as_ref().map(|(n, _)| n.as_str()))
73 }
74}
75
76pub const MAX_NATIVE_SLOTS: usize = 4096;
79
80#[derive(Debug, Clone, PartialEq, Eq)]
86pub enum NativeTableError {
87 DuplicateName(String),
88 SlotOccupied {
89 index: u32,
90 name: String,
91 },
92 IndexTooLarge {
94 index: u32,
95 limit: u32,
96 },
97}
98
99impl std::fmt::Display for NativeTableError {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 match self {
102 NativeTableError::DuplicateName(name) => {
103 write!(f, "duplicate native function registered: '{name}'")
104 }
105 NativeTableError::SlotOccupied { index, name } => {
106 write!(
107 f,
108 "native slot {index} already occupied (registering '{name}')"
109 )
110 }
111 NativeTableError::IndexTooLarge { index, limit } => {
112 write!(f, "native slot {index} is past the limit of {limit}")
113 }
114 }
115 }
116}
117
118impl std::error::Error for NativeTableError {}
119
120pub struct NativeTableBuilder {
125 entries: Vec<Option<(String, NativeFn)>>,
126}
127
128impl NativeTableBuilder {
129 pub fn new() -> Self {
130 Self {
131 entries: Vec::new(),
132 }
133 }
134
135 pub fn register<F>(self, name: impl Into<String>, f: F) -> Result<Self, NativeTableError>
137 where
138 F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
139 {
140 let index = self.entries.len() as u32;
141 self.register_at(index, name, f)
142 }
143
144 pub fn register_at<F>(
147 mut self,
148 index: u32,
149 name: impl Into<String>,
150 f: F,
151 ) -> Result<Self, NativeTableError>
152 where
153 F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
154 {
155 let name = name.into();
156 for (n, _) in self.entries.iter().flatten() {
157 if n == &name {
158 return Err(NativeTableError::DuplicateName(name));
159 }
160 }
161 let index_usize = index as usize;
162 if index_usize >= MAX_NATIVE_SLOTS {
163 return Err(NativeTableError::IndexTooLarge {
164 index,
165 limit: MAX_NATIVE_SLOTS as u32,
166 });
167 }
168 if index_usize >= self.entries.len() {
169 self.entries.resize_with(index_usize + 1, || None);
170 }
171 if self.entries[index_usize].is_some() {
172 return Err(NativeTableError::SlotOccupied { index, name });
173 }
174 self.entries[index_usize] = Some((name, Arc::new(f)));
175 Ok(self)
176 }
177
178 pub fn build(self) -> Arc<NativeTable> {
179 Arc::new(NativeTable {
180 entries: self.entries,
181 })
182 }
183}
184
185impl Default for NativeTableBuilder {
186 fn default() -> Self {
187 Self::new()
188 }
189}
190
191pub fn expect_arg<'a>(args: &'a [Value], index: usize, fn_name: &str) -> Result<&'a Value, Fault> {
193 args.get(index).ok_or(Fault::NativeError(format!(
194 "{fn_name}: missing argument {index}"
195 )))
196}
197
198pub fn expect_int(args: &[Value], index: usize, fn_name: &str) -> Result<i64, Fault> {
200 expect_arg(args, index, fn_name)?
201 .as_int()
202 .ok_or(Fault::NativeError(format!(
203 "{fn_name}: argument {index} is not an int"
204 )))
205}
206
207pub fn expect_bool(args: &[Value], index: usize, fn_name: &str) -> Result<bool, Fault> {
209 let v = expect_arg(args, index, fn_name)?;
210 match v {
211 Value::Bool(_) | Value::Int(_) => Ok(v.is_truthy()),
212 other => Err(Fault::NativeError(format!(
213 "{fn_name}: argument {index} is not a bool/int (got {})",
214 other.type_name()
215 ))),
216 }
217}
218
219pub fn expect_message(
224 args: &[Value],
225 index: usize,
226 fn_name: &str,
227) -> Result<crate::Message, Fault> {
228 expect_arg(args, index, fn_name)?
229 .as_message()
230 .cloned()
231 .ok_or(Fault::NativeError(format!(
232 "{fn_name}: argument {index} is not a message"
233 )))
234}
235
236pub fn expect_u64(args: &[Value], index: usize, fn_name: &str) -> Result<u64, Fault> {
242 let v = expect_arg(args, index, fn_name)?;
243 if let Some(p) = v.as_pid() {
244 return Ok(p);
245 }
246 if let Value::Int(i) = v {
247 if *i >= 0 {
248 return Ok(*i as u64);
249 }
250 }
251 Err(Fault::NativeError(format!(
252 "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
253 v.type_name()
254 )))
255}
256
257#[derive(Clone, Debug)]
259pub struct NativeGate {
260 has_native: bool,
261 mask: NativeMask,
262 authority_epoch: u64,
263 flow_cell: Arc<RevocationCell>,
264 native_epoch: u64,
265 native_cell: Arc<RevocationCell>,
266}
267
268impl NativeGate {
269 pub fn deny(native_count: usize) -> Self {
271 Self {
272 has_native: false,
273 mask: NativeMask::empty(native_count),
274 authority_epoch: 0,
275 flow_cell: Arc::new(RevocationCell::new()),
276 native_epoch: 0,
277 native_cell: Arc::new(RevocationCell::new()),
278 }
279 }
280
281 pub fn from_authority(
282 cap: &Cap,
283 flow_cell: Arc<RevocationCell>,
284 native_cell: Arc<RevocationCell>,
285 native_count: usize,
286 ) -> Self {
287 let mask = match cap.native_mask() {
288 Some(m) => m.clone(),
289 None => NativeMask::empty(native_count),
290 };
291 Self {
292 has_native: cap.rights().contains(CapRights::NATIVE),
293 mask,
294 authority_epoch: cap.epoch(),
295 flow_cell,
296 native_epoch: native_cell.epoch(),
297 native_cell,
298 }
299 }
300
301 pub fn is_live(&self) -> bool {
302 self.flow_cell.epoch() == self.authority_epoch
303 && self.native_cell.epoch() == self.native_epoch
304 }
305}
306
307pub fn check_native_call(
312 cap: &Cap,
313 table: &NativeTable,
314 idx: NativeIdx,
315) -> Result<(), NativeCallError> {
316 if (idx as usize) >= table.len() {
317 return Err(NativeCallError::IndexOutOfRange(idx));
318 }
319 if !cap.rights().contains(CapRights::NATIVE) {
320 return Err(NativeCallError::NoNativeRight);
321 }
322 match cap.native_mask() {
323 Some(mask) if mask.allows(idx) => Ok(()),
324 _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
325 }
326}
327
328pub fn check_native_gate(
329 gate: &NativeGate,
330 table: &NativeTable,
331 idx: NativeIdx,
332) -> Result<(), NativeCallError> {
333 if (idx as usize) >= table.len() {
334 return Err(NativeCallError::IndexOutOfRange(idx));
335 }
336 if !gate.is_live() {
337 return Err(NativeCallError::Revoked);
338 }
339 if !gate.has_native {
340 return Err(NativeCallError::NoNativeRight);
341 }
342 if gate.mask.allows(idx) {
343 Ok(())
344 } else {
345 Err(NativeCallError::IndexNotAllowlisted(idx))
346 }
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 #[test]
354 fn expect_u64_rejects_bool_and_keeps_non_negative_ints() {
355 let flag = [Value::Bool(true)];
356 assert!(expect_u64(&flag, 0, "make_msg").is_err());
357 let negative = [Value::Int(-1)];
358 assert!(expect_u64(&negative, 0, "make_msg").is_err());
359 let zero = [Value::Int(0)];
360 assert_eq!(expect_u64(&zero, 0, "make_msg").ok(), Some(0));
361 let pid = [Value::Pid(7)];
362 assert_eq!(expect_u64(&pid, 0, "make_msg").ok(), Some(7));
363 }
364
365 #[test]
366 fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
367 let table = NativeTable::builder()
368 .register_at(10, "answer", |_| Ok(Value::Int(42)))?
369 .build();
370 assert_eq!(table.len(), 11);
371 assert_eq!(table.index_of("answer"), Some(10));
372 let f = table.get(10).ok_or("missing native")?;
373 assert!(matches!(f(&[])?, Value::Int(42)));
374 assert!(table.get(2).is_none());
375 Ok(())
376 }
377
378 #[test]
379 fn register_at_rejects_an_index_past_the_slot_ceiling() {
380 let result = NativeTable::builder().register_at(u32::MAX, "huge", |_| Ok(Value::Unit));
381 assert_eq!(
382 result.map(|builder| builder.build().len()),
383 Err(NativeTableError::IndexTooLarge {
384 index: u32::MAX,
385 limit: MAX_NATIVE_SLOTS as u32,
386 })
387 );
388 }
389
390 #[test]
391 fn register_at_errors_on_duplicate_slot() {
392 let result = NativeTable::builder()
393 .register_at(3, "a", |_| Ok(Value::Unit))
394 .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
395 assert!(matches!(
396 result,
397 Err(NativeTableError::SlotOccupied { index: 3, .. })
398 ));
399 }
400
401 #[test]
402 fn register_errors_on_duplicate_name() {
403 let result = NativeTable::builder()
404 .register("x", |_| Ok(Value::Unit))
405 .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
406 assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
407 }
408
409 #[test]
410 fn denies_unlisted_index_even_with_native_right() {
411 use crate::bytecode::{CapTarget, RevocationCell};
412
413 let cell = RevocationCell::new();
414 let mask = NativeMask::from_indices(16, &[2, 4]);
415 let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
416 let table = NativeTable {
417 entries: Vec::new(),
418 };
419 assert!(matches!(
420 check_native_call(&cap, &table, 4),
421 Err(NativeCallError::IndexOutOfRange(_))
422 ));
423 }
424}