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 Some(i) = v.as_int().filter(|&n| n >= 0) {
247 return Ok(i as u64);
248 }
249 Err(Fault::NativeError(format!(
250 "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
251 v.type_name()
252 )))
253}
254
255#[derive(Clone, Debug)]
257pub struct NativeGate {
258 has_native: bool,
259 mask: NativeMask,
260 authority_epoch: u64,
261 flow_cell: Arc<RevocationCell>,
262 native_epoch: u64,
263 native_cell: Arc<RevocationCell>,
264}
265
266impl NativeGate {
267 pub fn deny(native_count: usize) -> Self {
269 Self {
270 has_native: false,
271 mask: NativeMask::empty(native_count),
272 authority_epoch: 0,
273 flow_cell: Arc::new(RevocationCell::new()),
274 native_epoch: 0,
275 native_cell: Arc::new(RevocationCell::new()),
276 }
277 }
278
279 pub fn from_authority(
280 cap: &Cap,
281 flow_cell: Arc<RevocationCell>,
282 native_cell: Arc<RevocationCell>,
283 native_count: usize,
284 ) -> Self {
285 let mask = match &cap.native_mask {
286 Some(m) => m.clone(),
287 None => NativeMask::empty(native_count),
288 };
289 Self {
290 has_native: cap.rights.contains(CapRights::NATIVE),
291 mask,
292 authority_epoch: cap.epoch(),
293 flow_cell,
294 native_epoch: native_cell.epoch(),
295 native_cell,
296 }
297 }
298
299 pub fn is_live(&self) -> bool {
300 self.flow_cell.epoch() == self.authority_epoch
301 && self.native_cell.epoch() == self.native_epoch
302 }
303}
304
305pub fn check_native_call(
310 cap: &Cap,
311 table: &NativeTable,
312 idx: NativeIdx,
313) -> Result<(), NativeCallError> {
314 if (idx as usize) >= table.len() {
315 return Err(NativeCallError::IndexOutOfRange(idx));
316 }
317 if !cap.rights.contains(CapRights::NATIVE) {
318 return Err(NativeCallError::NoNativeRight);
319 }
320 match &cap.native_mask {
321 Some(mask) if mask.allows(idx) => Ok(()),
322 _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
323 }
324}
325
326pub fn check_native_gate(
327 gate: &NativeGate,
328 table: &NativeTable,
329 idx: NativeIdx,
330) -> Result<(), NativeCallError> {
331 if (idx as usize) >= table.len() {
332 return Err(NativeCallError::IndexOutOfRange(idx));
333 }
334 if !gate.is_live() {
335 return Err(NativeCallError::Revoked);
336 }
337 if !gate.has_native {
338 return Err(NativeCallError::NoNativeRight);
339 }
340 if gate.mask.allows(idx) {
341 Ok(())
342 } else {
343 Err(NativeCallError::IndexNotAllowlisted(idx))
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 #[test]
352 fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
353 let table = NativeTable::builder()
354 .register_at(10, "answer", |_| Ok(Value::Int(42)))?
355 .build();
356 assert_eq!(table.len(), 11);
357 assert_eq!(table.index_of("answer"), Some(10));
358 let f = table.get(10).ok_or("missing native")?;
359 assert!(matches!(f(&[])?, Value::Int(42)));
360 assert!(table.get(2).is_none());
361 Ok(())
362 }
363
364 #[test]
365 fn register_at_rejects_an_index_past_the_slot_ceiling() {
366 let result = NativeTable::builder().register_at(u32::MAX, "huge", |_| Ok(Value::Unit));
367 assert_eq!(
368 result.map(|builder| builder.build().len()),
369 Err(NativeTableError::IndexTooLarge {
370 index: u32::MAX,
371 limit: MAX_NATIVE_SLOTS as u32,
372 })
373 );
374 }
375
376 #[test]
377 fn register_at_errors_on_duplicate_slot() {
378 let result = NativeTable::builder()
379 .register_at(3, "a", |_| Ok(Value::Unit))
380 .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
381 assert!(matches!(
382 result,
383 Err(NativeTableError::SlotOccupied { index: 3, .. })
384 ));
385 }
386
387 #[test]
388 fn register_errors_on_duplicate_name() {
389 let result = NativeTable::builder()
390 .register("x", |_| Ok(Value::Unit))
391 .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
392 assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
393 }
394
395 #[test]
396 fn denies_unlisted_index_even_with_native_right() {
397 use crate::bytecode::{CapTarget, RevocationCell};
398
399 let cell = RevocationCell::new();
400 let mask = NativeMask::from_indices(16, &[2, 4]);
401 let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
402 let table = NativeTable {
403 entries: Vec::new(),
404 };
405 assert!(matches!(
406 check_native_call(&cap, &table, 4),
407 Err(NativeCallError::IndexOutOfRange(_))
408 ));
409 }
410}