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
76#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum NativeTableError {
82 DuplicateName(String),
83 SlotOccupied { index: u32, name: String },
84}
85
86impl std::fmt::Display for NativeTableError {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 match self {
89 NativeTableError::DuplicateName(name) => {
90 write!(f, "duplicate native function registered: '{name}'")
91 }
92 NativeTableError::SlotOccupied { index, name } => {
93 write!(
94 f,
95 "native slot {index} already occupied (registering '{name}')"
96 )
97 }
98 }
99 }
100}
101
102impl std::error::Error for NativeTableError {}
103
104pub struct NativeTableBuilder {
109 entries: Vec<Option<(String, NativeFn)>>,
110}
111
112impl NativeTableBuilder {
113 pub fn new() -> Self {
114 Self {
115 entries: Vec::new(),
116 }
117 }
118
119 pub fn register<F>(self, name: impl Into<String>, f: F) -> Result<Self, NativeTableError>
121 where
122 F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
123 {
124 let index = self.entries.len() as u32;
125 self.register_at(index, name, f)
126 }
127
128 pub fn register_at<F>(
131 mut self,
132 index: u32,
133 name: impl Into<String>,
134 f: F,
135 ) -> Result<Self, NativeTableError>
136 where
137 F: Fn(&[Value]) -> NativeResult + Send + Sync + 'static,
138 {
139 let name = name.into();
140 for (n, _) in self.entries.iter().flatten() {
141 if n == &name {
142 return Err(NativeTableError::DuplicateName(name));
143 }
144 }
145 let index_usize = index as usize;
146 if index_usize >= self.entries.len() {
147 self.entries.resize_with(index_usize + 1, || None);
148 }
149 if self.entries[index_usize].is_some() {
150 return Err(NativeTableError::SlotOccupied { index, name });
151 }
152 self.entries[index_usize] = Some((name, Arc::new(f)));
153 Ok(self)
154 }
155
156 pub fn build(self) -> Arc<NativeTable> {
157 Arc::new(NativeTable {
158 entries: self.entries,
159 })
160 }
161}
162
163impl Default for NativeTableBuilder {
164 fn default() -> Self {
165 Self::new()
166 }
167}
168
169pub fn expect_arg<'a>(args: &'a [Value], index: usize, fn_name: &str) -> Result<&'a Value, Fault> {
171 args.get(index).ok_or(Fault::NativeError(format!(
172 "{fn_name}: missing argument {index}"
173 )))
174}
175
176pub fn expect_int(args: &[Value], index: usize, fn_name: &str) -> Result<i64, Fault> {
178 expect_arg(args, index, fn_name)?
179 .as_int()
180 .ok_or(Fault::NativeError(format!(
181 "{fn_name}: argument {index} is not an int"
182 )))
183}
184
185pub fn expect_bool(args: &[Value], index: usize, fn_name: &str) -> Result<bool, Fault> {
187 let v = expect_arg(args, index, fn_name)?;
188 match v {
189 Value::Bool(_) | Value::Int(_) => Ok(v.is_truthy()),
190 other => Err(Fault::NativeError(format!(
191 "{fn_name}: argument {index} is not a bool/int (got {})",
192 other.type_name()
193 ))),
194 }
195}
196
197pub fn expect_message(
202 args: &[Value],
203 index: usize,
204 fn_name: &str,
205) -> Result<crate::Message, Fault> {
206 expect_arg(args, index, fn_name)?
207 .as_message()
208 .cloned()
209 .ok_or(Fault::NativeError(format!(
210 "{fn_name}: argument {index} is not a message"
211 )))
212}
213
214pub fn expect_u64(args: &[Value], index: usize, fn_name: &str) -> Result<u64, Fault> {
220 let v = expect_arg(args, index, fn_name)?;
221 if let Some(p) = v.as_pid() {
222 return Ok(p);
223 }
224 if let Some(i) = v.as_int().filter(|&n| n >= 0) {
225 return Ok(i as u64);
226 }
227 Err(Fault::NativeError(format!(
228 "{fn_name}: argument {index} is not a non-negative int/pid (got {})",
229 v.type_name()
230 )))
231}
232
233#[derive(Clone, Debug)]
235pub struct NativeGate {
236 has_native: bool,
237 mask: NativeMask,
238 authority_epoch: u64,
239 flow_cell: Arc<RevocationCell>,
240 native_epoch: u64,
241 native_cell: Arc<RevocationCell>,
242}
243
244impl NativeGate {
245 pub fn deny(native_count: usize) -> Self {
247 Self {
248 has_native: false,
249 mask: NativeMask::empty(native_count),
250 authority_epoch: 0,
251 flow_cell: Arc::new(RevocationCell::new()),
252 native_epoch: 0,
253 native_cell: Arc::new(RevocationCell::new()),
254 }
255 }
256
257 pub fn from_authority(
258 cap: &Cap,
259 flow_cell: Arc<RevocationCell>,
260 native_cell: Arc<RevocationCell>,
261 native_count: usize,
262 ) -> Self {
263 let mask = match &cap.native_mask {
264 Some(m) => m.clone(),
265 None => NativeMask::empty(native_count),
266 };
267 Self {
268 has_native: cap.rights.contains(CapRights::NATIVE),
269 mask,
270 authority_epoch: cap.epoch(),
271 flow_cell,
272 native_epoch: native_cell.epoch(),
273 native_cell,
274 }
275 }
276
277 pub fn is_live(&self) -> bool {
278 self.flow_cell.epoch() == self.authority_epoch
279 && self.native_cell.epoch() == self.native_epoch
280 }
281}
282
283pub fn check_native_call(
288 cap: &Cap,
289 table: &NativeTable,
290 idx: NativeIdx,
291) -> Result<(), NativeCallError> {
292 if (idx as usize) >= table.len() {
293 return Err(NativeCallError::IndexOutOfRange(idx));
294 }
295 if !cap.rights.contains(CapRights::NATIVE) {
296 return Err(NativeCallError::NoNativeRight);
297 }
298 match &cap.native_mask {
299 Some(mask) if mask.allows(idx) => Ok(()),
300 _ => Err(NativeCallError::IndexNotAllowlisted(idx)),
301 }
302}
303
304pub fn check_native_gate(
305 gate: &NativeGate,
306 table: &NativeTable,
307 idx: NativeIdx,
308) -> Result<(), NativeCallError> {
309 if (idx as usize) >= table.len() {
310 return Err(NativeCallError::IndexOutOfRange(idx));
311 }
312 if !gate.is_live() {
313 return Err(NativeCallError::Revoked);
314 }
315 if !gate.has_native {
316 return Err(NativeCallError::NoNativeRight);
317 }
318 if gate.mask.allows(idx) {
319 Ok(())
320 } else {
321 Err(NativeCallError::IndexNotAllowlisted(idx))
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328
329 #[test]
330 fn register_at_leaves_holes_as_none() -> Result<(), Box<dyn std::error::Error>> {
331 let table = NativeTable::builder()
332 .register_at(10, "answer", |_| Ok(Value::Int(42)))?
333 .build();
334 assert_eq!(table.len(), 11);
335 assert_eq!(table.index_of("answer"), Some(10));
336 let f = table.get(10).ok_or("missing native")?;
337 assert!(matches!(f(&[])?, Value::Int(42)));
338 assert!(table.get(2).is_none());
339 Ok(())
340 }
341
342 #[test]
343 fn register_at_errors_on_duplicate_slot() {
344 let result = NativeTable::builder()
345 .register_at(3, "a", |_| Ok(Value::Unit))
346 .and_then(|b| b.register_at(3, "b", |_| Ok(Value::Unit)));
347 assert!(matches!(
348 result,
349 Err(NativeTableError::SlotOccupied { index: 3, .. })
350 ));
351 }
352
353 #[test]
354 fn register_errors_on_duplicate_name() {
355 let result = NativeTable::builder()
356 .register("x", |_| Ok(Value::Unit))
357 .and_then(|b| b.register("x", |_| Ok(Value::Unit)));
358 assert!(matches!(result, Err(NativeTableError::DuplicateName(_))));
359 }
360
361 #[test]
362 fn denies_unlisted_index_even_with_native_right() {
363 use crate::bytecode::{CapTarget, RevocationCell};
364
365 let cell = RevocationCell::new();
366 let mask = NativeMask::from_indices(16, &[2, 4]);
367 let cap = Cap::root(CapTarget::Flow(1), CapRights::NATIVE, Some(mask), &cell);
368 let table = NativeTable {
369 entries: Vec::new(),
370 };
371 assert!(matches!(
372 check_native_call(&cap, &table, 4),
373 Err(NativeCallError::IndexOutOfRange(_))
374 ));
375 }
376}