borderless 0.1.2

SDK for borderless packages
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use anyhow::anyhow;
use borderless_id_types::{AgentId, BorderlessId, ContractId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{fmt::Display, str::FromStr};

use crate::{debug, error, NamedSink};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Enum to represent the type of method-call
pub enum MethodOrId {
    /// Method is called by its name
    ByName { method: String },
    /// Method is called by its id
    ById { method_id: u32 },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data-model for an action-call in contracts and agents.
pub struct CallAction {
    #[serde(flatten)]
    pub method: MethodOrId,
    pub params: Value,
}

impl FromStr for CallAction {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

impl CallAction {
    /// Create a new `CallAction`
    pub fn new(method: MethodOrId, params: Value) -> Self {
        Self { method, params }
    }

    /// Create a new `CallAction` by method-name
    pub fn by_method(method_name: impl AsRef<str>, params: Value) -> Self {
        Self {
            method: MethodOrId::ByName {
                method: method_name.as_ref().to_string(),
            },
            params,
        }
    }

    /// Create a new `CallAction` by method-id
    pub fn by_method_id(method_id: u32, params: Value) -> Self {
        Self {
            method: MethodOrId::ById { method_id },
            params,
        }
    }

    /// Returns the method-name of this action (if any)
    pub fn method_name(&self) -> Option<&str> {
        match &self.method {
            MethodOrId::ByName { method } => Some(method.as_str()),
            MethodOrId::ById { .. } => None,
        }
    }

    /// Returns the method-id of this action (if any)
    pub fn method_id(&self) -> Option<u32> {
        match self.method {
            MethodOrId::ByName { .. } => None,
            MethodOrId::ById { method_id } => Some(method_id),
        }
    }

    /// Prints either the method-name or method-id for this action
    pub fn print_method(&self) -> String {
        match &self.method {
            MethodOrId::ByName { method } => format!("method-name={method}"),
            MethodOrId::ById { method_id } => format!("method-id={method_id}"),
        }
    }

    /// Deserializes the JSON-Bytes into a `CallAction`
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Pretty-prints the entire `CallAction` as JSON
    pub fn pretty_print(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self)
    }

    /// Serialized the `CallAction` into JSON-Bytes
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self)
    }
}

// /// Represents a target that should execute some action.
// ///
// /// Since contracts and software-agents both use the [`CallAction`] struct,
// /// but also use different ID types, this enum can be used in cases where a `CallAction`
// /// is bundled with either a [`ContractId`] or [`AgentId`].
// pub enum TargetId {
//     Agent(AgentId),
//     Contract(ContractId),
// }

/// An outgoing event for another contract
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractCall {
    pub contract_id: ContractId,
    pub action: CallAction,
}

/// An outgoing event for another agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentCall {
    pub agent_id: AgentId,
    pub action: CallAction,
}

/// Output Events generated by a contract or sw-agent
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Events {
    pub contracts: Vec<ContractCall>,
    pub local: Vec<AgentCall>,
}

impl Events {
    /// Returns `true` if there are no events at all
    pub fn is_empty(&self) -> bool {
        self.contracts.is_empty() && self.local.is_empty()
    }

    /// Decodes the `Events` with [`postcard`]
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, postcard::Error> {
        // TODO: Postcard or json ?
        postcard::from_bytes(bytes)
    }

    /// Encodes the `Events` with [`postcard`]
    pub fn to_bytes(&self) -> Result<Vec<u8>, postcard::Error> {
        // TODO: Postcard or json ?
        postcard::to_allocvec(self)
    }
}

/// Specifies the Sink-Type of an `ActionOutput`.
///
/// A sink can be either a named sink, that gets referenced by its `sink_alias`.
/// The real contract- or process-id is taken from the Contract- or ProcessInfo,
/// using [`ContractInfo::find_sink`] (or [`ProcessInfo::find_sink`]).
///
/// In general it is recommended to use the named sink-type, as it provides the most
/// comfort and fool-proof way of interacting with other contracts or processes.
///
/// However, for maximum flexibility, users can also refer to a sink directly by their
/// [`ContractId`] or [`ProcessId`].
#[derive(Debug)]
pub enum SinkType {
    Named(String),
    Agent(AgentId),
    Contract(ContractId),
}

impl Display for SinkType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SinkType::Named(s) => write!(f, "{s}"),
            SinkType::Agent(s) => write!(f, "{s}"),
            SinkType::Contract(s) => write!(f, "{s}"),
        }
    }
}

/// Output events of a contract's action
#[derive(Default)]
pub struct ActionOutput {
    actions: Vec<(SinkType, CallAction)>,
}

impl ActionOutput {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_event<T: NamedSink>(&mut self, target: T) {
        let (sink_name, action) = target.into_action();
        self.actions
            .push((SinkType::Named(sink_name.to_string()), action));
    }

    /// Adds a generic event to the output - with dynamic dispatch of the output sinks.
    ///
    /// In contrast to [`ActionOutput::add_event`] the event type must only implement `TryInto<CallAction>`,
    /// since the user directly tells us towards which sink the event should be send.
    /// This is only necessary, if the `Sink` has been added after the contract was instantiated.
    pub fn add_event_dynamic<S, IntoAction>(&mut self, sink_alias: S, action: IntoAction)
    where
        S: AsRef<str>,
        IntoAction: TryInto<CallAction>,
        <IntoAction as TryInto<CallAction>>::Error: std::fmt::Display,
    {
        let alias = sink_alias.as_ref().to_string();
        let action = match action.try_into() {
            Ok(a) => a,
            Err(e) => {
                error!("critical error while converting action for dynamic sink '{alias}': {e}");
                crate::__private::abort();
            }
        };
        self.actions.push((SinkType::Named(alias), action))
    }

    pub fn add_event_for_contract<IntoAction>(
        &mut self,
        contract_id: ContractId,
        action: IntoAction,
    ) where
        IntoAction: TryInto<CallAction>,
        <IntoAction as TryInto<CallAction>>::Error: std::fmt::Display,
    {
        let action = match action.try_into() {
            Ok(a) => a,
            Err(e) => {
                error!(
                    "critical error while converting action for dynamic sink '{contract_id}': {e}"
                );
                crate::__private::abort();
            }
        };
        self.actions.push((SinkType::Contract(contract_id), action))
    }

    pub fn add_event_for_process<IntoAction>(&mut self, agent_id: AgentId, action: IntoAction)
    where
        IntoAction: TryInto<CallAction>,
        <IntoAction as TryInto<CallAction>>::Error: std::fmt::Display,
    {
        let action = match action.try_into() {
            Ok(a) => a,
            Err(e) => {
                error!("critical error while converting action for dynamic sink '{agent_id}': {e}");
                crate::__private::abort();
            }
        };
        self.actions.push((SinkType::Agent(agent_id), action))
    }
}

/// Trait that indicates that a return type can be used as an output of an action function.
///
/// Note: This trait converts `()`, `ActionOutput`, `Result<(), E>` and `Result<ActionOutput, E>` into [`Events`].
/// The implementation of `ActionOutput` also checks, if the writer actually has access to a sink.
pub trait ActionOutEvent: private::Sealed {
    fn convert_out_events(self) -> crate::Result<Events>;
}

mod private {
    pub trait Sealed {}
}

impl private::Sealed for () {}
impl ActionOutEvent for () {
    fn convert_out_events(self) -> crate::Result<Events> {
        Ok(Events::default())
    }
}

impl<E> private::Sealed for Result<(), E> where E: std::fmt::Display + Send + Sync + 'static {}
impl<E> ActionOutEvent for Result<(), E>
where
    E: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> crate::Result<Events> {
        self.map_err(|e| crate::Error::msg(e))?.convert_out_events()
    }
}

impl private::Sealed for ActionOutput {}
impl ActionOutEvent for ActionOutput {
    fn convert_out_events(self) -> crate::Result<Events> {
        let caller = crate::contracts::env::executor();
        let sinks = crate::contracts::env::sinks();

        let mut contracts = Vec::new();
        let mut local = Vec::new();

        // TODO: There is an edge-case here; we currently have no solution,
        // if multiple participants in a contract have access to the same sink !
        //
        // Idea: Find these places and do a pseudo-random (but deterministic) choice.
        // Or we could solve this from the outside; somehow..
        for (sink, action) in self.actions {
            match sink {
                SinkType::Named(alias) => {
                    if let Some(sink) = sinks.iter().find(|s| s.has_alias(&alias)) {
                        if !sink.has_access(caller) {
                            debug!("caller {caller} does not have access to sink {alias}");
                            continue;
                        }
                        match sink {
                            Sink::Contract { contract_id, .. } => {
                                // TODO
                                contracts.push(ContractCall {
                                    contract_id: *contract_id,
                                    action,
                                })
                            }
                            Sink::Agent { agent_id, .. } => local.push(AgentCall {
                                agent_id: *agent_id,
                                action,
                            }),
                        }
                    } else {
                        // TODO: Should this be an error or should we just log the error here ?
                        return Err(anyhow!("Failed to find sink '{alias}', which is referenced in the action output"));
                    }
                }
                SinkType::Agent(agent_id) => local.push(AgentCall { agent_id, action }),
                // TODO: The edge-case also applies here I guess ??
                SinkType::Contract(contract_id) => contracts.push(ContractCall {
                    contract_id,
                    action,
                }),
            }
        }
        Ok(Events { contracts, local })
    }
}

impl<E> private::Sealed for Result<ActionOutput, E> where
    E: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static
{
}
impl<E> ActionOutEvent for Result<ActionOutput, E>
where
    E: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> crate::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

/// An event Sink for either a contract or sw-agent
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Sink {
    Contract {
        contract_id: ContractId,
        alias: String,
        restrict_to_users: Vec<BorderlessId>,
    },
    Agent {
        agent_id: AgentId,
        alias: String,
        owner: BorderlessId,
    },
}

impl Sink {
    /// Creates a new Sink for a software-agent
    pub fn agent(agent_id: AgentId, alias: String, owner: BorderlessId) -> Sink {
        Sink::Agent {
            agent_id,
            alias: alias.to_ascii_uppercase(),
            owner,
        }
    }

    /// Creates a new Sink for a SmartContract
    pub fn contract(
        contract_id: ContractId,
        alias: String,
        restrict_to_users: Vec<BorderlessId>,
    ) -> Sink {
        Sink::Contract {
            contract_id,
            alias: alias.to_ascii_uppercase(),
            restrict_to_users,
        }
    }

    /// Checks weather or not the given user has access to this sink
    pub fn has_access(&self, user: BorderlessId) -> bool {
        match self {
            Sink::Agent { owner, .. } => *owner == user,
            Sink::Contract {
                restrict_to_users, ..
            } => {
                // If the vector is empty, everyone has access
                restrict_to_users.is_empty() || restrict_to_users.iter().any(|u| *u == user)
            }
        }
    }

    pub fn has_alias(&self, alias: impl AsRef<str>) -> bool {
        let own_alias = match self {
            Sink::Agent { alias, .. } | Sink::Contract { alias, .. } => alias,
        };
        alias.as_ref().eq_ignore_ascii_case(own_alias)
    }

    pub fn is_process(&self) -> bool {
        match self {
            Sink::Agent { .. } => true,
            Sink::Contract { .. } => false,
        }
    }
}