Skip to main content

freenet_stdlib/
delegate_interface.rs

1use std::{
2    borrow::{Borrow, Cow},
3    fmt::Display,
4    fs::File,
5    io::Read,
6    ops::Deref,
7    path::Path,
8};
9
10use blake3::{traits::digest::Digest, Hasher as Blake3};
11use serde::{Deserialize, Deserializer, Serialize};
12use serde_with::serde_as;
13
14use crate::generated::client_request::{
15    DelegateKey as FbsDelegateKey, InboundDelegateMsg as FbsInboundDelegateMsg,
16    InboundDelegateMsgType,
17};
18
19use crate::common_generated::common::SecretsId as FbsSecretsId;
20
21use crate::client_api::{TryFromFbs, WsApiError};
22use crate::contract_interface::{RelatedContracts, UpdateData};
23use crate::prelude::{ContractInstanceId, WrappedState, CONTRACT_KEY_SIZE};
24use crate::versioning::ContractContainer;
25use crate::{code_hash::CodeHash, prelude::Parameters};
26
27const DELEGATE_HASH_LENGTH: usize = 32;
28
29#[derive(Clone, Debug, Serialize, Deserialize)]
30pub struct Delegate<'a> {
31    #[serde(borrow)]
32    parameters: Parameters<'a>,
33    #[serde(borrow)]
34    pub data: DelegateCode<'a>,
35    key: DelegateKey,
36}
37
38impl Delegate<'_> {
39    pub fn key(&self) -> &DelegateKey {
40        &self.key
41    }
42
43    pub fn code(&self) -> &DelegateCode<'_> {
44        &self.data
45    }
46
47    pub fn code_hash(&self) -> &CodeHash {
48        &self.data.code_hash
49    }
50
51    pub fn params(&self) -> &Parameters<'_> {
52        &self.parameters
53    }
54
55    pub fn into_owned(self) -> Delegate<'static> {
56        Delegate {
57            parameters: self.parameters.into_owned(),
58            data: self.data.into_owned(),
59            key: self.key,
60        }
61    }
62
63    pub fn size(&self) -> usize {
64        self.parameters.size() + self.data.size()
65    }
66
67    pub(crate) fn deserialize_delegate<'de, D>(deser: D) -> Result<Delegate<'static>, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        let data: Delegate<'de> = Deserialize::deserialize(deser)?;
72        Ok(data.into_owned())
73    }
74}
75
76impl PartialEq for Delegate<'_> {
77    fn eq(&self, other: &Self) -> bool {
78        self.key == other.key
79    }
80}
81
82impl Eq for Delegate<'_> {}
83
84impl<'a> From<(&DelegateCode<'a>, &Parameters<'a>)> for Delegate<'a> {
85    fn from((data, parameters): (&DelegateCode<'a>, &Parameters<'a>)) -> Self {
86        Self {
87            key: DelegateKey::from_params_and_code(parameters, data),
88            parameters: parameters.clone(),
89            data: data.clone(),
90        }
91    }
92}
93
94/// Executable delegate
95#[derive(Debug, Serialize, Deserialize, Clone)]
96#[serde_as]
97pub struct DelegateCode<'a> {
98    #[serde_as(as = "serde_with::Bytes")]
99    #[serde(borrow)]
100    pub(crate) data: Cow<'a, [u8]>,
101    // todo: skip serializing and instead compute it
102    pub(crate) code_hash: CodeHash,
103}
104
105impl DelegateCode<'static> {
106    /// Loads the contract raw wasm module, without any version.
107    pub fn load_raw(path: &Path) -> Result<Self, std::io::Error> {
108        let contract_data = Self::load_bytes(path)?;
109        Ok(DelegateCode::from(contract_data))
110    }
111
112    pub(crate) fn load_bytes(path: &Path) -> Result<Vec<u8>, std::io::Error> {
113        let mut contract_file = File::open(path)?;
114        let mut contract_data = if let Ok(md) = contract_file.metadata() {
115            Vec::with_capacity(md.len() as usize)
116        } else {
117            Vec::new()
118        };
119        contract_file.read_to_end(&mut contract_data)?;
120        Ok(contract_data)
121    }
122}
123
124impl DelegateCode<'_> {
125    /// Delegate code hash.
126    pub fn hash(&self) -> &CodeHash {
127        &self.code_hash
128    }
129
130    /// Returns the `Base58` string representation of the delegate key.
131    pub fn hash_str(&self) -> String {
132        Self::encode_hash(&self.code_hash.0)
133    }
134
135    /// Reference to delegate code.
136    pub fn data(&self) -> &[u8] {
137        &self.data
138    }
139
140    /// Returns the `Base58` string representation of a hash.
141    pub fn encode_hash(hash: &[u8; DELEGATE_HASH_LENGTH]) -> String {
142        bs58::encode(hash)
143            .with_alphabet(bs58::Alphabet::BITCOIN)
144            .into_string()
145    }
146
147    pub fn into_owned(self) -> DelegateCode<'static> {
148        DelegateCode {
149            code_hash: self.code_hash,
150            data: Cow::from(self.data.into_owned()),
151        }
152    }
153
154    pub fn size(&self) -> usize {
155        self.data.len()
156    }
157}
158
159impl PartialEq for DelegateCode<'_> {
160    fn eq(&self, other: &Self) -> bool {
161        self.code_hash == other.code_hash
162    }
163}
164
165impl Eq for DelegateCode<'_> {}
166
167impl AsRef<[u8]> for DelegateCode<'_> {
168    fn as_ref(&self) -> &[u8] {
169        self.data.borrow()
170    }
171}
172
173impl From<Vec<u8>> for DelegateCode<'static> {
174    fn from(data: Vec<u8>) -> Self {
175        let key = CodeHash::from_code(data.as_slice());
176        DelegateCode {
177            data: Cow::from(data),
178            code_hash: key,
179        }
180    }
181}
182
183impl<'a> From<&'a [u8]> for DelegateCode<'a> {
184    fn from(code: &'a [u8]) -> Self {
185        let key = CodeHash::from_code(code);
186        DelegateCode {
187            data: Cow::from(code),
188            code_hash: key,
189        }
190    }
191}
192
193#[serde_as]
194#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
195pub struct DelegateKey {
196    #[serde_as(as = "[_; DELEGATE_HASH_LENGTH]")]
197    key: [u8; DELEGATE_HASH_LENGTH],
198    code_hash: CodeHash,
199}
200
201impl From<DelegateKey> for SecretsId {
202    fn from(key: DelegateKey) -> SecretsId {
203        SecretsId {
204            hash: key.key,
205            key: vec![],
206        }
207    }
208}
209
210impl DelegateKey {
211    pub const fn new(key: [u8; DELEGATE_HASH_LENGTH], code_hash: CodeHash) -> Self {
212        Self { key, code_hash }
213    }
214
215    fn from_params_and_code<'a>(
216        params: impl Borrow<Parameters<'a>>,
217        wasm_code: impl Borrow<DelegateCode<'a>>,
218    ) -> Self {
219        let code = wasm_code.borrow();
220        let key = generate_id(params.borrow(), code);
221        Self {
222            key,
223            code_hash: *code.hash(),
224        }
225    }
226
227    pub fn encode(&self) -> String {
228        bs58::encode(self.key)
229            .with_alphabet(bs58::Alphabet::BITCOIN)
230            .into_string()
231    }
232
233    pub fn code_hash(&self) -> &CodeHash {
234        &self.code_hash
235    }
236
237    pub fn bytes(&self) -> &[u8] {
238        self.key.as_ref()
239    }
240
241    pub fn from_params(
242        code_hash: impl Into<String>,
243        parameters: &Parameters,
244    ) -> Result<Self, bs58::decode::Error> {
245        let mut code_key = [0; DELEGATE_HASH_LENGTH];
246        bs58::decode(code_hash.into())
247            .with_alphabet(bs58::Alphabet::BITCOIN)
248            .onto(&mut code_key)?;
249        let mut hasher = Blake3::new();
250        hasher.update(code_key.as_slice());
251        hasher.update(parameters.as_ref());
252        let full_key_arr = hasher.finalize();
253
254        debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
255        let mut key = [0; DELEGATE_HASH_LENGTH];
256        key.copy_from_slice(&full_key_arr);
257
258        Ok(Self {
259            key,
260            code_hash: CodeHash(code_key),
261        })
262    }
263}
264
265impl Deref for DelegateKey {
266    type Target = [u8; DELEGATE_HASH_LENGTH];
267
268    fn deref(&self) -> &Self::Target {
269        &self.key
270    }
271}
272
273impl Display for DelegateKey {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        write!(f, "{}", self.encode())
276    }
277}
278
279impl<'a> TryFromFbs<&FbsDelegateKey<'a>> for DelegateKey {
280    fn try_decode_fbs(key: &FbsDelegateKey<'a>) -> Result<Self, WsApiError> {
281        let mut key_bytes = [0; DELEGATE_HASH_LENGTH];
282        key_bytes.copy_from_slice(key.key().bytes().iter().as_ref());
283        Ok(DelegateKey {
284            key: key_bytes,
285            code_hash: CodeHash::from_code(key.code_hash().bytes()),
286        })
287    }
288}
289
290/// Type of errors during interaction with a delegate.
291#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
292pub enum DelegateError {
293    #[error("de/serialization error: {0}")]
294    Deser(String),
295    #[error("{0}")]
296    Other(String),
297}
298
299fn generate_id<'a>(
300    parameters: &Parameters<'a>,
301    code_data: &DelegateCode<'a>,
302) -> [u8; DELEGATE_HASH_LENGTH] {
303    let contract_hash = code_data.hash();
304
305    let mut hasher = Blake3::new();
306    hasher.update(contract_hash.0.as_slice());
307    hasher.update(parameters.as_ref());
308    let full_key_arr = hasher.finalize();
309
310    debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
311    let mut key = [0; DELEGATE_HASH_LENGTH];
312    key.copy_from_slice(&full_key_arr);
313    key
314}
315
316#[serde_as]
317#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
318pub struct SecretsId {
319    #[serde_as(as = "serde_with::Bytes")]
320    key: Vec<u8>,
321    #[serde_as(as = "[_; 32]")]
322    hash: [u8; 32],
323}
324
325impl SecretsId {
326    pub fn new(key: Vec<u8>) -> Self {
327        let mut hasher = Blake3::new();
328        hasher.update(&key);
329        let hashed = hasher.finalize();
330        let mut hash = [0; 32];
331        hash.copy_from_slice(&hashed);
332        Self { key, hash }
333    }
334
335    pub fn encode(&self) -> String {
336        bs58::encode(self.hash)
337            .with_alphabet(bs58::Alphabet::BITCOIN)
338            .into_string()
339    }
340
341    pub fn hash(&self) -> &[u8; 32] {
342        &self.hash
343    }
344    pub fn key(&self) -> &[u8] {
345        self.key.as_slice()
346    }
347}
348
349impl Display for SecretsId {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        write!(f, "{}", self.encode())
352    }
353}
354
355impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
356    fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
357        let mut key_hash = [0; 32];
358        key_hash.copy_from_slice(key.hash().bytes().iter().as_ref());
359        Ok(SecretsId {
360            key: key.key().bytes().to_vec(),
361            hash: key_hash,
362        })
363    }
364}
365
366/// A Delegate is a webassembly code designed to act as an agent for the user on
367/// Freenet. Delegates can:
368///
369///  * Store private data on behalf of the user
370///  * Create, read, and modify contracts
371///  * Create other delegates
372///  * Send and receive messages from other delegates and user interfaces
373///  * Ask the user questions and receive answers
374///
375/// Example use cases:
376///
377///  * A delegate stores a private key for the user, other components can ask
378///    the delegate to sign messages, it will ask the user for permission
379///  * A delegate monitors an inbox contract and downloads new messages when
380///    they arrive
381///
382/// # Example
383///
384/// ```ignore
385/// use freenet_stdlib::prelude::*;
386///
387/// struct MyDelegate;
388///
389/// #[delegate]
390/// impl DelegateInterface for MyDelegate {
391///     fn process(
392///         ctx: &mut DelegateCtx,
393///         _params: Parameters<'static>,
394///         _attested: Option<&'static [u8]>,
395///         message: InboundDelegateMsg,
396///     ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
397///         // Access secrets synchronously - no round-trip needed!
398///         if let Some(key) = ctx.get_secret(b"private_key") {
399///             // use key...
400///         }
401///         ctx.set_secret(b"new_key", b"value");
402///
403///         // Read/write context for temporary state within a batch
404///         ctx.write(b"some state");
405///
406///         Ok(vec![])
407///     }
408/// }
409/// ```
410pub trait DelegateInterface {
411    /// Process inbound message, producing zero or more outbound messages in response.
412    ///
413    /// # Arguments
414    /// - `ctx`: Mutable handle to the delegate's execution environment. Provides:
415    ///   - **Context** (temporary): `read()`, `write()`, `len()`, `clear()` - state within a batch
416    ///   - **Secrets** (persistent): `get_secret()`, `set_secret()`, `has_secret()`, `remove_secret()`
417    /// - `parameters`: The delegate's initialization parameters.
418    /// - `attested`: An optional identifier for the client of this function. Usually
419    ///   will be a [`ContractInstanceId`].
420    /// - `message`: The inbound message to process.
421    fn process(
422        ctx: &mut crate::delegate_host::DelegateCtx,
423        parameters: Parameters<'static>,
424        attested: Option<&'static [u8]>,
425        message: InboundDelegateMsg,
426    ) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
427}
428
429#[serde_as]
430#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
431pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);
432
433impl DelegateContext {
434    pub const MAX_SIZE: usize = 4096 * 10 * 10;
435
436    pub fn new(bytes: Vec<u8>) -> Self {
437        assert!(bytes.len() < Self::MAX_SIZE);
438        Self(bytes)
439    }
440
441    pub fn append(&mut self, bytes: &mut Vec<u8>) {
442        assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
443        self.0.append(bytes)
444    }
445
446    pub fn replace(&mut self, bytes: Vec<u8>) {
447        assert!(bytes.len() < Self::MAX_SIZE);
448        let _ = std::mem::replace(&mut self.0, bytes);
449    }
450}
451
452impl AsRef<[u8]> for DelegateContext {
453    fn as_ref(&self) -> &[u8] {
454        &self.0
455    }
456}
457
458#[derive(Serialize, Deserialize, Debug, Clone)]
459pub enum InboundDelegateMsg<'a> {
460    ApplicationMessage(ApplicationMessage),
461    UserResponse(#[serde(borrow)] UserInputResponse<'a>),
462    GetContractResponse(GetContractResponse),
463    PutContractResponse(PutContractResponse),
464    UpdateContractResponse(UpdateContractResponse),
465    SubscribeContractResponse(SubscribeContractResponse),
466    ContractNotification(ContractNotification),
467    DelegateMessage(DelegateMessage),
468}
469
470impl InboundDelegateMsg<'_> {
471    pub fn into_owned(self) -> InboundDelegateMsg<'static> {
472        match self {
473            InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
474            InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
475            InboundDelegateMsg::GetContractResponse(r) => {
476                InboundDelegateMsg::GetContractResponse(r)
477            }
478            InboundDelegateMsg::PutContractResponse(r) => {
479                InboundDelegateMsg::PutContractResponse(r)
480            }
481            InboundDelegateMsg::UpdateContractResponse(r) => {
482                InboundDelegateMsg::UpdateContractResponse(r)
483            }
484            InboundDelegateMsg::SubscribeContractResponse(r) => {
485                InboundDelegateMsg::SubscribeContractResponse(r)
486            }
487            InboundDelegateMsg::ContractNotification(r) => {
488                InboundDelegateMsg::ContractNotification(r)
489            }
490            InboundDelegateMsg::DelegateMessage(r) => InboundDelegateMsg::DelegateMessage(r),
491        }
492    }
493
494    pub fn get_context(&self) -> Option<&DelegateContext> {
495        match self {
496            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
497                Some(context)
498            }
499            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
500                Some(context)
501            }
502            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
503                Some(context)
504            }
505            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
506                context, ..
507            }) => Some(context),
508            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
509                context,
510                ..
511            }) => Some(context),
512            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
513                Some(context)
514            }
515            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
516            _ => None,
517        }
518    }
519
520    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
521        match self {
522            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
523                Some(context)
524            }
525            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
526                Some(context)
527            }
528            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
529                Some(context)
530            }
531            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
532                context, ..
533            }) => Some(context),
534            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
535                context,
536                ..
537            }) => Some(context),
538            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
539                Some(context)
540            }
541            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
542            _ => None,
543        }
544    }
545}
546
547impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
548    fn from(value: ApplicationMessage) -> Self {
549        Self::ApplicationMessage(value)
550    }
551}
552
553impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
554    fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
555        match msg.inbound_type() {
556            InboundDelegateMsgType::common_ApplicationMessage => {
557                let app_msg = msg.inbound_as_common_application_message().unwrap();
558                let mut instance_key_bytes = [0; CONTRACT_KEY_SIZE];
559                instance_key_bytes
560                    .copy_from_slice(app_msg.app().data().bytes().to_vec().as_slice());
561                let app_msg = ApplicationMessage {
562                    app: ContractInstanceId::new(instance_key_bytes),
563                    payload: app_msg.payload().bytes().to_vec(),
564                    context: DelegateContext::new(app_msg.context().bytes().to_vec()),
565                    processed: app_msg.processed(),
566                };
567                Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
568            }
569            InboundDelegateMsgType::UserInputResponse => {
570                let user_response = msg.inbound_as_user_input_response().unwrap();
571                let user_response = UserInputResponse {
572                    request_id: user_response.request_id(),
573                    response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
574                    context: DelegateContext::new(
575                        user_response.delegate_context().bytes().to_vec(),
576                    ),
577                };
578                Ok(InboundDelegateMsg::UserResponse(user_response))
579            }
580            _ => unreachable!("invalid inbound delegate message type"),
581        }
582    }
583}
584
585#[non_exhaustive]
586#[derive(Serialize, Deserialize, Debug, Clone)]
587pub struct ApplicationMessage {
588    pub app: ContractInstanceId,
589    pub payload: Vec<u8>,
590    pub context: DelegateContext,
591    pub processed: bool,
592}
593
594impl ApplicationMessage {
595    pub fn new(app: ContractInstanceId, payload: Vec<u8>) -> Self {
596        Self {
597            app,
598            payload,
599            context: DelegateContext::default(),
600            processed: false,
601        }
602    }
603
604    pub fn with_context(mut self, context: DelegateContext) -> Self {
605        self.context = context;
606        self
607    }
608
609    pub fn processed(mut self, p: bool) -> Self {
610        self.processed = p;
611        self
612    }
613}
614
615#[derive(Serialize, Deserialize, Debug, Clone)]
616pub struct UserInputResponse<'a> {
617    pub request_id: u32,
618    #[serde(borrow)]
619    pub response: ClientResponse<'a>,
620    pub context: DelegateContext,
621}
622
623impl UserInputResponse<'_> {
624    pub fn into_owned(self) -> UserInputResponse<'static> {
625        UserInputResponse {
626            request_id: self.request_id,
627            response: self.response.into_owned(),
628            context: self.context,
629        }
630    }
631}
632
633#[derive(Serialize, Deserialize, Debug, Clone)]
634pub enum OutboundDelegateMsg {
635    // for the apps
636    ApplicationMessage(ApplicationMessage),
637    RequestUserInput(
638        #[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
639        UserInputRequest<'static>,
640    ),
641    // todo: remove when context can be accessed from the delegate environment and we pass it as reference
642    ContextUpdated(DelegateContext),
643    GetContractRequest(GetContractRequest),
644    PutContractRequest(PutContractRequest),
645    UpdateContractRequest(UpdateContractRequest),
646    SubscribeContractRequest(SubscribeContractRequest),
647    SendDelegateMessage(DelegateMessage),
648}
649
650impl From<ApplicationMessage> for OutboundDelegateMsg {
651    fn from(req: ApplicationMessage) -> Self {
652        Self::ApplicationMessage(req)
653    }
654}
655
656impl From<GetContractRequest> for OutboundDelegateMsg {
657    fn from(req: GetContractRequest) -> Self {
658        Self::GetContractRequest(req)
659    }
660}
661
662impl From<PutContractRequest> for OutboundDelegateMsg {
663    fn from(req: PutContractRequest) -> Self {
664        Self::PutContractRequest(req)
665    }
666}
667
668impl From<UpdateContractRequest> for OutboundDelegateMsg {
669    fn from(req: UpdateContractRequest) -> Self {
670        Self::UpdateContractRequest(req)
671    }
672}
673
674impl From<SubscribeContractRequest> for OutboundDelegateMsg {
675    fn from(req: SubscribeContractRequest) -> Self {
676        Self::SubscribeContractRequest(req)
677    }
678}
679
680impl From<DelegateMessage> for OutboundDelegateMsg {
681    fn from(msg: DelegateMessage) -> Self {
682        Self::SendDelegateMessage(msg)
683    }
684}
685
686impl OutboundDelegateMsg {
687    fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
688    where
689        D: serde::Deserializer<'de>,
690    {
691        let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
692        Ok(value.into_owned())
693    }
694
695    pub fn processed(&self) -> bool {
696        match self {
697            OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
698            OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
699            OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
700            OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
701            OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
702            OutboundDelegateMsg::SendDelegateMessage(msg) => msg.processed,
703            OutboundDelegateMsg::RequestUserInput(_) => true,
704            OutboundDelegateMsg::ContextUpdated(_) => true,
705        }
706    }
707
708    pub fn get_context(&self) -> Option<&DelegateContext> {
709        match self {
710            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
711                Some(context)
712            }
713            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
714                Some(context)
715            }
716            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
717                Some(context)
718            }
719            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
720                context, ..
721            }) => Some(context),
722            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
723                context,
724                ..
725            }) => Some(context),
726            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
727                Some(context)
728            }
729            _ => None,
730        }
731    }
732
733    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
734        match self {
735            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
736                Some(context)
737            }
738            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
739                Some(context)
740            }
741            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
742                Some(context)
743            }
744            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
745                context, ..
746            }) => Some(context),
747            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
748                context,
749                ..
750            }) => Some(context),
751            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
752                Some(context)
753            }
754            _ => None,
755        }
756    }
757}
758
759/// Request to get contract state from within a delegate.
760#[derive(Serialize, Deserialize, Debug, Clone)]
761pub struct GetContractRequest {
762    pub contract_id: ContractInstanceId,
763    pub context: DelegateContext,
764    pub processed: bool,
765}
766
767impl GetContractRequest {
768    pub fn new(contract_id: ContractInstanceId) -> Self {
769        Self {
770            contract_id,
771            context: Default::default(),
772            processed: false,
773        }
774    }
775}
776
777/// Response containing contract state for a delegate.
778#[derive(Serialize, Deserialize, Debug, Clone)]
779pub struct GetContractResponse {
780    pub contract_id: ContractInstanceId,
781    /// The contract state, or None if the contract was not found locally.
782    pub state: Option<WrappedState>,
783    pub context: DelegateContext,
784}
785
786/// Request to store a new contract from within a delegate.
787#[derive(Serialize, Deserialize, Debug, Clone)]
788pub struct PutContractRequest {
789    /// The contract code and parameters.
790    pub contract: ContractContainer,
791    /// The initial state for the contract.
792    pub state: WrappedState,
793    /// Related contracts that this contract depends on.
794    #[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
795    pub related_contracts: RelatedContracts<'static>,
796    /// Context for the delegate.
797    pub context: DelegateContext,
798    /// Whether this request has been processed.
799    pub processed: bool,
800}
801
802impl PutContractRequest {
803    pub fn new(
804        contract: ContractContainer,
805        state: WrappedState,
806        related_contracts: RelatedContracts<'static>,
807    ) -> Self {
808        Self {
809            contract,
810            state,
811            related_contracts,
812            context: Default::default(),
813            processed: false,
814        }
815    }
816}
817
818/// Response after attempting to store a contract from a delegate.
819#[derive(Serialize, Deserialize, Debug, Clone)]
820pub struct PutContractResponse {
821    /// The ID of the contract that was (attempted to be) stored.
822    pub contract_id: ContractInstanceId,
823    /// Success (Ok) or error message (Err).
824    pub result: Result<(), String>,
825    /// Context for the delegate.
826    pub context: DelegateContext,
827}
828
829/// Request to update an existing contract's state from within a delegate.
830#[derive(Serialize, Deserialize, Debug, Clone)]
831pub struct UpdateContractRequest {
832    /// The contract to update.
833    pub contract_id: ContractInstanceId,
834    /// The update to apply (full state or delta).
835    #[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
836    pub update: UpdateData<'static>,
837    /// Context for the delegate.
838    pub context: DelegateContext,
839    /// Whether this request has been processed.
840    pub processed: bool,
841}
842
843impl UpdateContractRequest {
844    pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
845        Self {
846            contract_id,
847            update,
848            context: Default::default(),
849            processed: false,
850        }
851    }
852
853    fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
854    where
855        D: Deserializer<'de>,
856    {
857        let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
858        Ok(value.into_owned())
859    }
860}
861
862/// Response after attempting to update a contract from a delegate.
863#[derive(Serialize, Deserialize, Debug, Clone)]
864pub struct UpdateContractResponse {
865    /// The contract that was updated.
866    pub contract_id: ContractInstanceId,
867    /// Success (Ok) or error message (Err).
868    pub result: Result<(), String>,
869    /// Context for the delegate.
870    pub context: DelegateContext,
871}
872
873/// Request to subscribe to a contract's state changes from within a delegate.
874#[derive(Serialize, Deserialize, Debug, Clone)]
875pub struct SubscribeContractRequest {
876    /// The contract to subscribe to.
877    pub contract_id: ContractInstanceId,
878    /// Context for the delegate.
879    pub context: DelegateContext,
880    /// Whether this request has been processed.
881    pub processed: bool,
882}
883
884impl SubscribeContractRequest {
885    pub fn new(contract_id: ContractInstanceId) -> Self {
886        Self {
887            contract_id,
888            context: Default::default(),
889            processed: false,
890        }
891    }
892}
893
894/// Response after attempting to subscribe to a contract from a delegate.
895#[derive(Serialize, Deserialize, Debug, Clone)]
896pub struct SubscribeContractResponse {
897    /// The contract subscribed to.
898    pub contract_id: ContractInstanceId,
899    /// Success (Ok) or error message (Err).
900    pub result: Result<(), String>,
901    /// Context for the delegate.
902    pub context: DelegateContext,
903}
904
905/// A message sent from one delegate to another.
906///
907/// Delegates can communicate with each other by emitting
908/// `OutboundDelegateMsg::SendDelegateMessage` with a `DelegateMessage` targeting
909/// another delegate. The runtime delivers it as `InboundDelegateMsg::DelegateMessage`
910/// to the target delegate's `process()` function.
911///
912/// The `sender` field is overwritten by the runtime with the actual sender's key
913/// (sender attestation), so delegates cannot spoof their identity.
914#[derive(Serialize, Deserialize, Debug, Clone)]
915pub struct DelegateMessage {
916    /// The delegate to deliver this message to.
917    pub target: DelegateKey,
918    /// The delegate that sent this message (overwritten by runtime for attestation).
919    pub sender: DelegateKey,
920    /// Arbitrary message payload.
921    pub payload: Vec<u8>,
922    /// Delegate context, carried through the processing pipeline.
923    pub context: DelegateContext,
924    /// Runtime protocol flag indicating whether this message has been delivered.
925    pub processed: bool,
926}
927
928impl DelegateMessage {
929    pub fn new(target: DelegateKey, sender: DelegateKey, payload: Vec<u8>) -> Self {
930        Self {
931            target,
932            sender,
933            payload,
934            context: DelegateContext::default(),
935            processed: false,
936        }
937    }
938}
939
940/// Notification delivered to a delegate when a subscribed contract's state changes.
941#[derive(Serialize, Deserialize, Debug, Clone)]
942pub struct ContractNotification {
943    /// The contract whose state changed.
944    pub contract_id: ContractInstanceId,
945    /// The new state of the contract.
946    pub new_state: WrappedState,
947    /// Context for the delegate.
948    pub context: DelegateContext,
949}
950
951#[serde_as]
952#[derive(Serialize, Deserialize, Debug, Clone)]
953pub struct NotificationMessage<'a>(
954    #[serde_as(as = "serde_with::Bytes")]
955    #[serde(borrow)]
956    Cow<'a, [u8]>,
957);
958
959impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
960    type Error = ();
961
962    fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
963        // todo: validate format when we have a better idea of what we want here
964        let bytes = serde_json::to_vec(json).unwrap();
965        Ok(Self(Cow::Owned(bytes)))
966    }
967}
968
969impl NotificationMessage<'_> {
970    pub fn into_owned(self) -> NotificationMessage<'static> {
971        NotificationMessage(self.0.into_owned().into())
972    }
973    pub fn bytes(&self) -> &[u8] {
974        self.0.as_ref()
975    }
976}
977
978#[serde_as]
979#[derive(Serialize, Deserialize, Debug, Clone)]
980pub struct ClientResponse<'a>(
981    #[serde_as(as = "serde_with::Bytes")]
982    #[serde(borrow)]
983    Cow<'a, [u8]>,
984);
985
986impl Deref for ClientResponse<'_> {
987    type Target = [u8];
988
989    fn deref(&self) -> &Self::Target {
990        &self.0
991    }
992}
993
994impl ClientResponse<'_> {
995    pub fn new(response: Vec<u8>) -> Self {
996        Self(response.into())
997    }
998    pub fn into_owned(self) -> ClientResponse<'static> {
999        ClientResponse(self.0.into_owned().into())
1000    }
1001    pub fn bytes(&self) -> &[u8] {
1002        self.0.as_ref()
1003    }
1004}
1005
1006#[derive(Serialize, Deserialize, Debug, Clone)]
1007pub struct UserInputRequest<'a> {
1008    pub request_id: u32,
1009    #[serde(borrow)]
1010    /// An interpretable message by the notification system.
1011    pub message: NotificationMessage<'a>,
1012    /// If a response is required from the user they can be chosen from this list.
1013    pub responses: Vec<ClientResponse<'a>>,
1014}
1015
1016impl UserInputRequest<'_> {
1017    pub fn into_owned(self) -> UserInputRequest<'static> {
1018        UserInputRequest {
1019            request_id: self.request_id,
1020            message: self.message.into_owned(),
1021            responses: self.responses.into_iter().map(|r| r.into_owned()).collect(),
1022        }
1023    }
1024}
1025
1026#[doc(hidden)]
1027pub(crate) mod wasm_interface {
1028    //! Contains all the types to interface between the host environment and
1029    //! the wasm module execution.
1030    use super::*;
1031    use crate::memory::WasmLinearMem;
1032
1033    #[repr(C)]
1034    #[derive(Debug, Clone, Copy)]
1035    pub struct DelegateInterfaceResult {
1036        ptr: i64,
1037        size: u32,
1038    }
1039
1040    impl DelegateInterfaceResult {
1041        pub unsafe fn from_raw(ptr: i64, mem: &WasmLinearMem) -> Self {
1042            let result = Box::leak(Box::from_raw(crate::memory::buf::compute_ptr(
1043                ptr as *mut Self,
1044                mem,
1045            )));
1046            #[cfg(feature = "trace")]
1047            {
1048                tracing::trace!(
1049                    "got FFI result @ {ptr} ({:p}) -> {result:?}",
1050                    ptr as *mut Self
1051                );
1052            }
1053            *result
1054        }
1055
1056        #[cfg(feature = "contract")]
1057        pub fn into_raw(self) -> i64 {
1058            #[cfg(feature = "trace")]
1059            {
1060                tracing::trace!("returning FFI -> {self:?}");
1061            }
1062            let ptr = Box::into_raw(Box::new(self));
1063            #[cfg(feature = "trace")]
1064            {
1065                tracing::trace!("FFI result ptr: {ptr:p} ({}i64)", ptr as i64);
1066            }
1067            ptr as _
1068        }
1069
1070        pub unsafe fn unwrap(
1071            self,
1072            mem: WasmLinearMem,
1073        ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
1074            let ptr = crate::memory::buf::compute_ptr(self.ptr as *mut u8, &mem);
1075            let serialized = std::slice::from_raw_parts(ptr as *const u8, self.size as _);
1076            let value: Result<Vec<OutboundDelegateMsg>, DelegateError> =
1077                bincode::deserialize(serialized)
1078                    .map_err(|e| DelegateError::Other(format!("{e}")))?;
1079            #[cfg(feature = "trace")]
1080            {
1081                tracing::trace!(
1082                    "got result through FFI; addr: {:p} ({}i64, mapped: {ptr:p})
1083                     serialized: {serialized:?}
1084                     value: {value:?}",
1085                    self.ptr as *mut u8,
1086                    self.ptr
1087                );
1088            }
1089            value
1090        }
1091    }
1092
1093    impl From<Result<Vec<OutboundDelegateMsg>, DelegateError>> for DelegateInterfaceResult {
1094        fn from(value: Result<Vec<OutboundDelegateMsg>, DelegateError>) -> Self {
1095            let serialized = bincode::serialize(&value).unwrap();
1096            let size = serialized.len() as _;
1097            let ptr = serialized.as_ptr();
1098            #[cfg(feature = "trace")]
1099            {
1100                tracing::trace!(
1101                    "sending result through FFI; addr: {ptr:p} ({}),\n  serialized: {serialized:?}\n  value: {value:?}",
1102                    ptr as i64
1103                );
1104            }
1105            std::mem::forget(serialized);
1106            Self {
1107                ptr: ptr as i64,
1108                size,
1109            }
1110        }
1111    }
1112}