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::{fixed_size_field, unknown_union_discriminant, TryFromFbs, WsApiError};
22use crate::contract_interface::{RelatedContracts, UpdateData, CONTRACT_KEY_SIZE};
23use crate::prelude::{ContractInstanceId, WrappedState};
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        // Both fields are `(required)` in the schema and BOTH need an explicit
282        // length check, because the verifier only guarantees presence. `key`
283        // used to be a bare `copy_from_slice` into a `[0; 32]`, which panics on
284        // a length mismatch, while `code_hash` one line below was already
285        // length-checked inside `CodeHash::try_from`. Keep them symmetric: a
286        // future field added here needs the same treatment.
287        let key_bytes =
288            fixed_size_field::<DELEGATE_HASH_LENGTH>("DelegateKey.key", key.key().bytes())?;
289        // `CodeHash::try_from` DOES length-check, so this field never panicked —
290        // but its error stringifies to "invalid data", naming neither the field
291        // nor the length. Symmetric treatment means the same message shape, not
292        // merely the same safety, so it goes through the same helper.
293        let code_hash = CodeHash::new(fixed_size_field::<CONTRACT_KEY_SIZE>(
294            "DelegateKey.code_hash",
295            key.code_hash().bytes(),
296        )?);
297        Ok(DelegateKey {
298            key: key_bytes,
299            code_hash,
300        })
301    }
302}
303
304/// Type of errors during interaction with a delegate.
305///
306/// Marked `#[non_exhaustive]` so future error variants can be added without a
307/// source-level break. Downstream `match` sites must include a wildcard arm.
308#[non_exhaustive]
309#[derive(Debug, thiserror::Error, Serialize, Deserialize)]
310pub enum DelegateError {
311    #[error("de/serialization error: {0}")]
312    Deser(String),
313    #[error("{0}")]
314    Other(String),
315}
316
317fn generate_id<'a>(
318    parameters: &Parameters<'a>,
319    code_data: &DelegateCode<'a>,
320) -> [u8; DELEGATE_HASH_LENGTH] {
321    let contract_hash = code_data.hash();
322
323    let mut hasher = Blake3::new();
324    hasher.update(contract_hash.0.as_slice());
325    hasher.update(parameters.as_ref());
326    let full_key_arr = hasher.finalize();
327
328    debug_assert_eq!(full_key_arr[..].len(), DELEGATE_HASH_LENGTH);
329    let mut key = [0; DELEGATE_HASH_LENGTH];
330    key.copy_from_slice(&full_key_arr);
331    key
332}
333
334#[serde_as]
335#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
336pub struct SecretsId {
337    #[serde_as(as = "serde_with::Bytes")]
338    key: Vec<u8>,
339    #[serde_as(as = "[_; 32]")]
340    hash: [u8; 32],
341}
342
343impl SecretsId {
344    pub fn new(key: Vec<u8>) -> Self {
345        let mut hasher = Blake3::new();
346        hasher.update(&key);
347        let hashed = hasher.finalize();
348        let mut hash = [0; 32];
349        hash.copy_from_slice(&hashed);
350        Self { key, hash }
351    }
352
353    pub fn encode(&self) -> String {
354        bs58::encode(self.hash)
355            .with_alphabet(bs58::Alphabet::BITCOIN)
356            .into_string()
357    }
358
359    pub fn hash(&self) -> &[u8; 32] {
360        &self.hash
361    }
362    pub fn key(&self) -> &[u8] {
363        self.key.as_slice()
364    }
365}
366
367impl Display for SecretsId {
368    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
369        write!(f, "{}", self.encode())
370    }
371}
372
373impl<'a> TryFromFbs<&FbsSecretsId<'a>> for SecretsId {
374    fn try_decode_fbs(key: &FbsSecretsId<'a>) -> Result<Self, WsApiError> {
375        // No production caller reaches this decoder today — `common.SecretsId`
376        // appears in no client-request table. It is fixed anyway because the
377        // `copy_from_slice` it replaces is a loaded gun for whoever wires it up:
378        // `hash` is `(required)`, which the verifier reads as "present", not
379        // "32 bytes", so the first client to send a short one would have
380        // panicked the connection task.
381        let key_hash = fixed_size_field::<32>("SecretsId.hash", key.hash().bytes())?;
382        Ok(SecretsId {
383            key: key.key().bytes().to_vec(),
384            hash: key_hash,
385        })
386    }
387}
388
389/// Identifies where an inbound application message originated from.
390///
391/// When a web app sends a message to a delegate through the WebSocket API with
392/// an authentication token, the runtime resolves the token to the originating
393/// contract and wraps it in `MessageOrigin::WebApp`. When one delegate sends a
394/// message to another via [`OutboundDelegateMsg::SendDelegateMessage`], the
395/// runtime attests the caller's identity in `MessageOrigin::Delegate`.
396/// Delegates receive this as the `origin` parameter of
397/// [`DelegateInterface::process`].
398///
399/// This enum is `#[non_exhaustive]`: downstream code matching on it must
400/// include a wildcard arm so future variants can be added without a
401/// source-level breaking change.
402#[non_exhaustive]
403#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
404pub enum MessageOrigin {
405    /// The message was sent by a web application backed by the given contract.
406    WebApp(ContractInstanceId),
407    /// The message was sent by another delegate via
408    /// [`OutboundDelegateMsg::SendDelegateMessage`]. The carried key is the
409    /// runtime-attested identity of the calling delegate; the receiver can
410    /// trust it to make authorization decisions.
411    ///
412    /// Note: an inter-delegate message **replaces** rather than composes with
413    /// any inherited `WebApp` origin the calling delegate may itself hold.
414    /// The receiver sees only `Delegate(caller_key)` for the duration of the
415    /// call, and does not gain contract access on behalf of any web app the
416    /// caller was acting for. Authorization should be made on the calling
417    /// delegate's identity alone.
418    Delegate(DelegateKey),
419}
420
421/// A Delegate is a webassembly code designed to act as an agent for the user on
422/// Freenet. Delegates can:
423///
424///  * Store private data on behalf of the user
425///  * Create, read, and modify contracts
426///  * Create other delegates
427///  * Send and receive messages from other delegates and user interfaces
428///  * Ask the user questions and receive answers
429///
430/// Example use cases:
431///
432///  * A delegate stores a private key for the user, other components can ask
433///    the delegate to sign messages, it will ask the user for permission
434///  * A delegate monitors an inbox contract and downloads new messages when
435///    they arrive
436///
437/// # Example
438///
439/// ```ignore
440/// use freenet_stdlib::prelude::*;
441///
442/// struct MyDelegate;
443///
444/// #[delegate]
445/// impl DelegateInterface for MyDelegate {
446///     fn process(
447///         ctx: &mut DelegateCtx,
448///         _params: Parameters<'static>,
449///         _origin: Option<MessageOrigin>,
450///         message: InboundDelegateMsg,
451///     ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
452///         // Access secrets synchronously - no round-trip needed!
453///         if let Some(key) = ctx.get_secret(b"private_key") {
454///             // use key...
455///         }
456///         ctx.set_secret(b"new_key", b"value");
457///
458///         // Read/write context for temporary state within a batch
459///         ctx.write(b"some state");
460///
461///         Ok(vec![])
462///     }
463/// }
464/// ```
465pub trait DelegateInterface {
466    /// Process inbound message, producing zero or more outbound messages in response.
467    ///
468    /// # Arguments
469    /// - `ctx`: Mutable handle to the delegate's execution environment. Provides:
470    ///   - **Context** (temporary): `read()`, `write()`, `len()`, `clear()` - state within a batch
471    ///   - **Secrets** (persistent): `get_secret()`, `set_secret()`, `has_secret()`, `remove_secret()`
472    /// - `parameters`: The delegate's initialization parameters.
473    /// - `origin`: An optional [`MessageOrigin`] identifying where the message came from.
474    ///   For messages sent by web applications, this is `MessageOrigin::WebApp(contract_id)`.
475    /// - `message`: The inbound message to process.
476    fn process(
477        ctx: &mut crate::delegate_host::DelegateCtx,
478        parameters: Parameters<'static>,
479        origin: Option<MessageOrigin>,
480        message: InboundDelegateMsg,
481    ) -> Result<Vec<OutboundDelegateMsg>, DelegateError>;
482}
483
484#[serde_as]
485#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
486pub struct DelegateContext(#[serde_as(as = "serde_with::Bytes")] Vec<u8>);
487
488impl DelegateContext {
489    pub const MAX_SIZE: usize = 4096 * 10 * 10;
490
491    pub fn new(bytes: Vec<u8>) -> Self {
492        assert!(bytes.len() < Self::MAX_SIZE);
493        Self(bytes)
494    }
495
496    pub fn append(&mut self, bytes: &mut Vec<u8>) {
497        assert!(self.0.len() + bytes.len() < Self::MAX_SIZE);
498        self.0.append(bytes)
499    }
500
501    pub fn replace(&mut self, bytes: Vec<u8>) {
502        assert!(bytes.len() < Self::MAX_SIZE);
503        let _ = std::mem::replace(&mut self.0, bytes);
504    }
505}
506
507impl AsRef<[u8]> for DelegateContext {
508    fn as_ref(&self) -> &[u8] {
509        &self.0
510    }
511}
512
513/// Messages delivered **into** a delegate's `process()` function.
514///
515/// This is the inbound counterpart of [`OutboundDelegateMsg`] and sits on the
516/// host↔delegate wire boundary.
517///
518/// Marked `#[non_exhaustive]` so future variants can be added without a
519/// source-level break; downstream `match` sites must include a wildcard arm.
520/// [`OutboundDelegateMsg`] is deliberately **not** marked, and the asymmetry is
521/// the point — see the rationale on that enum. (An earlier version of this
522/// comment asserted that `OutboundDelegateMsg` already carried the attribute.
523/// It never has.)
524///
525/// # Wire format and compatibility
526///
527/// bincode, variant index 0..=N in **declaration order**. Two rules follow, and
528/// the compiler enforces neither:
529///
530/// - **Never insert or reorder a variant.** That silently reassigns every later
531///   tag, so delegate WASM compiled against an older stdlib decodes the same
532///   bytes into a *different* variant — no error, just a message quietly
533///   reinterpreted as another one. `delegate_msg_variant_tags_are_pinned` pins
534///   the tag of every variant of both enums so a reorder fails CI instead.
535/// - **Appending is compatible in exactly one direction.** An old sender's old
536///   variant always decodes on a new receiver. A **new** sender's **new**
537///   variant does **not** decode on an old receiver: bincode rejects the
538///   unknown tag — as `ErrorKind::Custom("invalid value: integer `N`, expected
539///   variant index 0 <= i < M")`, since bincode hands the index to serde's
540///   derived visitor rather than validating it itself. (Not
541///   `InvalidTagEncoding`, which bincode only ever produces for a bad `Option`
542///   discriminant.) `#[non_exhaustive]` does
543///   not change this — it is a source-level attribute with no effect on the
544///   encoding, and serde has no unknown-variant fallback to fall back to.
545///
546/// For this enum the incompatible direction is a **new host → old delegate**,
547/// and it is mostly unreachable in practice: the host emits a response variant
548/// only in reply to the matching request variant, so a delegate that never
549/// emits a request added in stdlib version X never receives the response added
550/// in X. Deployed delegate WASM therefore keeps working against an upgraded
551/// node. The genuinely constrained direction is delegate → host; see
552/// [`OutboundDelegateMsg`].
553///
554/// The compatibility claims above are asserted, not merely asserted-in-prose,
555/// by the `delegate_wire_compat` test module at the bottom of this file.
556#[non_exhaustive]
557#[derive(Serialize, Deserialize, Debug, Clone)]
558pub enum InboundDelegateMsg<'a> {
559    ApplicationMessage(ApplicationMessage),
560    UserResponse(#[serde(borrow)] UserInputResponse<'a>),
561    GetContractResponse(GetContractResponse),
562    PutContractResponse(PutContractResponse),
563    UpdateContractResponse(UpdateContractResponse),
564    SubscribeContractResponse(SubscribeContractResponse),
565    ContractNotification(ContractNotification),
566    DelegateMessage(DelegateMessage),
567    // Appended in 0.10.0 at tag 8. New variants go at the END, never inserted —
568    // see the wire-format note on this enum.
569    UnsubscribeContractResponse(UnsubscribeContractResponse),
570    /// Delivered by the host when a wakeup previously requested via
571    /// `DelegateCtx::schedule_wakeup` fires. `tag` is the opaque
572    /// value the delegate supplied when scheduling, echoed back verbatim so
573    /// the delegate can identify which wakeup fired. Owned (`'static`).
574    ///
575    /// # What the context cache holds during a wakeup
576    ///
577    /// Nothing the delegate should read. freenet-core's delegate context cache
578    /// is keyed **per delegate**, not per conversation, and entries are pruned
579    /// after `DELEGATE_CONTEXT_TTL` (10 minutes). Two consequences, both
580    /// arguing the same way:
581    ///
582    /// - Any wakeup worth scheduling is far longer than 10 minutes, so whatever
583    ///   context existed when it was scheduled is **gone** by the time it fires.
584    /// - If the delegate happens to have a live context from some *other*
585    ///   in-flight exchange inside that window, it belongs to that exchange.
586    ///   Reading it during a wakeup would be reading another conversation's
587    ///   working state.
588    ///
589    /// This is why the variant carries no `DelegateContext`: there is no
590    /// coherent value to put in it. A delegate needing state across a wakeup
591    /// reads it from its secrets, which is what core's own cache doc
592    /// recommends for exactly this case.
593    ///
594    /// Appended at tag **9**, after `UnsubscribeContractResponse` at tag 8.
595    WakeupFired {
596        tag: Vec<u8>,
597    },
598}
599
600impl InboundDelegateMsg<'_> {
601    pub fn into_owned(self) -> InboundDelegateMsg<'static> {
602        match self {
603            InboundDelegateMsg::ApplicationMessage(r) => InboundDelegateMsg::ApplicationMessage(r),
604            InboundDelegateMsg::UserResponse(r) => InboundDelegateMsg::UserResponse(r.into_owned()),
605            InboundDelegateMsg::GetContractResponse(r) => {
606                InboundDelegateMsg::GetContractResponse(r)
607            }
608            InboundDelegateMsg::PutContractResponse(r) => {
609                InboundDelegateMsg::PutContractResponse(r)
610            }
611            InboundDelegateMsg::UpdateContractResponse(r) => {
612                InboundDelegateMsg::UpdateContractResponse(r)
613            }
614            InboundDelegateMsg::SubscribeContractResponse(r) => {
615                InboundDelegateMsg::SubscribeContractResponse(r)
616            }
617            InboundDelegateMsg::ContractNotification(r) => {
618                InboundDelegateMsg::ContractNotification(r)
619            }
620            InboundDelegateMsg::DelegateMessage(r) => InboundDelegateMsg::DelegateMessage(r),
621            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
622                InboundDelegateMsg::UnsubscribeContractResponse(r)
623            }
624            InboundDelegateMsg::WakeupFired { tag } => InboundDelegateMsg::WakeupFired { tag },
625        }
626    }
627
628    pub fn get_context(&self) -> Option<&DelegateContext> {
629        match self {
630            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
631                Some(context)
632            }
633            // UserResponse carries a context too. It was missing from both
634            // accessors, so this returned None for it — the `_ => None`
635            // wildcard below swallowed the omission silently. Found in review.
636            InboundDelegateMsg::UserResponse(UserInputResponse { context, .. }) => Some(context),
637            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
638                Some(context)
639            }
640            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
641                Some(context)
642            }
643            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
644                context, ..
645            }) => Some(context),
646            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
647                context,
648                ..
649            }) => Some(context),
650            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
651                Some(context)
652            }
653            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
654            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
655                context,
656                ..
657            }) => Some(context),
658            // `WakeupFired` carries no `DelegateContext`, so `None` here is
659            // the honest answer rather than a missing arm. The reasoning lives
660            // on the variant itself -- see `InboundDelegateMsg::WakeupFired`,
661            // which explains both why a wakeup is not a reply and why the
662            // context cache could not supply a coherent value anyway. Kept in
663            // one place deliberately: a maintainer editing this accessor should
664            // not meet a second, older version of the argument.
665            InboundDelegateMsg::WakeupFired { .. } => None,
666            // No wildcard, deliberately. The `_ => None` that used to sit here
667            // is what let UserResponse go unhandled and silently report "no
668            // context". Exhaustive means a new variant is a compile error here
669            // instead — which is how `WakeupFired` above came to be considered
670            // explicitly rather than defaulting into the wildcard.
671            //
672            // Correcting a premise this crate briefly asserted: "every variant
673            // carries a context" was already false before `WakeupFired`, and
674            // false about *this accessor* rather than about the structs. In
675            // 0.8.5 this match listed seven variants, omitted `UserResponse`
676            // — which does have a context field — and ended in `_ => None`. So
677            // the claim was true of the types and wrong about the code. That
678            // is why the `WakeupFired` exemption in the test asserts
679            // `get_context()` is `None`: it pins what this function does, not
680            // what the struct definitions look like.
681        }
682    }
683
684    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
685        match self {
686            InboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
687                Some(context)
688            }
689            // UserResponse carries a context too. It was missing from both
690            // accessors, so this returned None for it — the `_ => None`
691            // wildcard below swallowed the omission silently. Found in review.
692            InboundDelegateMsg::UserResponse(UserInputResponse { context, .. }) => Some(context),
693            InboundDelegateMsg::GetContractResponse(GetContractResponse { context, .. }) => {
694                Some(context)
695            }
696            InboundDelegateMsg::PutContractResponse(PutContractResponse { context, .. }) => {
697                Some(context)
698            }
699            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
700                context, ..
701            }) => Some(context),
702            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
703                context,
704                ..
705            }) => Some(context),
706            InboundDelegateMsg::ContractNotification(ContractNotification { context, .. }) => {
707                Some(context)
708            }
709            InboundDelegateMsg::DelegateMessage(DelegateMessage { context, .. }) => Some(context),
710            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
711                context,
712                ..
713            }) => Some(context),
714            // `WakeupFired` carries no context; see `get_context`.
715            InboundDelegateMsg::WakeupFired { .. } => None,
716            // No wildcard, deliberately. The `_ => None` that used to sit here
717            // is what let UserResponse go unhandled and silently report "no
718            // context". Exhaustive means a new variant is a compile error here
719            // instead.
720        }
721    }
722}
723
724impl From<ApplicationMessage> for InboundDelegateMsg<'_> {
725    fn from(value: ApplicationMessage) -> Self {
726        Self::ApplicationMessage(value)
727    }
728}
729
730impl<'a> TryFromFbs<&FbsInboundDelegateMsg<'a>> for InboundDelegateMsg<'a> {
731    fn try_decode_fbs(msg: &FbsInboundDelegateMsg<'a>) -> Result<Self, WsApiError> {
732        match msg.inbound_type() {
733            InboundDelegateMsgType::common_ApplicationMessage => {
734                let app_msg = msg.inbound_as_common_application_message().unwrap();
735                let app_msg = ApplicationMessage {
736                    payload: app_msg.payload().bytes().to_vec(),
737                    context: DelegateContext::new(app_msg.context().bytes().to_vec()),
738                    processed: app_msg.processed(),
739                };
740                Ok(InboundDelegateMsg::ApplicationMessage(app_msg))
741            }
742            InboundDelegateMsgType::UserInputResponse => {
743                let user_response = msg.inbound_as_user_input_response().unwrap();
744                let user_response = UserInputResponse {
745                    request_id: user_response.request_id(),
746                    response: ClientResponse::new(user_response.response().data().bytes().to_vec()),
747                    context: DelegateContext::new(
748                        user_response.delegate_context().bytes().to_vec(),
749                    ),
750                };
751                Ok(InboundDelegateMsg::UserResponse(user_response))
752            }
753            // Reachable, not `unreachable!()`: the generated verifier for this
754            // union ends in `_ => Ok(())`, so any discriminant a client sets —
755            // including `NONE` — arrives here. See `unknown_union_discriminant`.
756            other => Err(unknown_union_discriminant(
757                "InboundDelegateMsgType",
758                other.0,
759            )),
760        }
761    }
762}
763
764#[non_exhaustive]
765#[derive(Serialize, Deserialize, Debug, Clone)]
766pub struct ApplicationMessage {
767    pub payload: Vec<u8>,
768    pub context: DelegateContext,
769    pub processed: bool,
770}
771
772impl ApplicationMessage {
773    pub fn new(payload: Vec<u8>) -> Self {
774        Self {
775            payload,
776            context: DelegateContext::default(),
777            processed: false,
778        }
779    }
780
781    pub fn with_context(mut self, context: DelegateContext) -> Self {
782        self.context = context;
783        self
784    }
785
786    pub fn processed(mut self, p: bool) -> Self {
787        self.processed = p;
788        self
789    }
790}
791
792#[derive(Serialize, Deserialize, Debug, Clone)]
793pub struct UserInputResponse<'a> {
794    pub request_id: u32,
795    #[serde(borrow)]
796    pub response: ClientResponse<'a>,
797    pub context: DelegateContext,
798}
799
800impl UserInputResponse<'_> {
801    pub fn into_owned(self) -> UserInputResponse<'static> {
802        UserInputResponse {
803            request_id: self.request_id,
804            response: self.response.into_owned(),
805            context: self.context,
806        }
807    }
808}
809
810/// Messages emitted **out of** a delegate's `process()` function.
811///
812/// This is the outbound counterpart of [`InboundDelegateMsg`] and sits on the
813/// same host↔delegate wire boundary.
814///
815/// # Deliberately not `#[non_exhaustive]`
816///
817/// Adding a variant here is a source-level break for any downstream crate that
818/// matches on it exhaustively. That is the intended behaviour and it should not
819/// be "fixed" by marking the enum.
820///
821/// Every variant of this enum is a **request the host must act on**. There is
822/// one host — freenet-core — and it dispatches these in exhaustive matches with
823/// no wildcard (`crates/core/src/contract.rs`, in the request loop and again in
824/// the app-message filter). Marking this enum `#[non_exhaustive]` would force
825/// those matches to grow `_ =>` arms, and a newly added variant would then
826/// compile against the host with **no arm of its own**: the delegate's request
827/// would fall into the wildcard, the call would appear to succeed, and nothing
828/// would report that it did nothing.
829///
830/// The compile error is what stops that, and it is the only mechanism that
831/// does. Keep it.
832///
833/// Two honest limits on this argument, because it is easy to claim more:
834///
835/// - **It forces an arm to exist, not a handler to be correct.** This crate's
836///   own FlatBuffers encoder (`client_api::client_events`) has explicit arms
837///   for six outbound variants that log an error and drop the message. The
838///   compile error made someone write those arms deliberately; it could not
839///   make them do anything useful.
840/// - **It is not the bug behind this workstream.** A delegate
841///   `SubscribeContractRequest` *is* handled by the host today. Its defect is
842///   different and subtler: it registers no demand in the network, so the
843///   subscription does not pin the contract (freenet-core#4669). Do not read
844///   the compile-error argument as a fix for that; it is a guard against a
845///   different failure that has not happened yet, which is the point of a
846///   guard.
847///
848/// [`InboundDelegateMsg`] carries the opposite trade-off, and is marked: its
849/// consumers are third-party delegate WASM, which can reasonably ignore a
850/// variant it does not know about.
851///
852/// # Wire format and compatibility
853///
854/// bincode, variant index 0..=N in **declaration order**. Never insert or
855/// reorder a variant: that silently reassigns every later tag, and deployed
856/// delegate WASM built against an older stdlib would encode into what the host
857/// now reads as a different variant. `delegate_msg_variant_tags_are_pinned`
858/// pins every tag so a reorder fails CI rather than production.
859///
860/// Appending is compatible in one direction only, and this enum is the
861/// direction that bites:
862///
863/// - **Old delegate → new host: fine, for appended VARIANTS.** The host
864///   understands every tag an older delegate can emit, so deployed delegate
865///   WASM keeps working against an upgraded node with no rebuild. This does
866///   **not** extend to appending a FIELD to an existing variant's payload
867///   struct, because a field breaks in the opposite direction. See
868///   `struct_field_wire_compat` in `client_api::client_events`.
869///   (`ApplicationMessage` is `#[non_exhaustive]`, which invites precisely that
870///   edit. It is the only payload struct here that is.)
871/// - **New delegate → old host: fails, and fails loudly.** bincode rejects the
872///   unknown variant tag — as `ErrorKind::Custom("invalid value: integer `N`,
873///   expected variant index 0 <= i < M")`, since it hands the index to serde's
874///   derived visitor rather than validating it itself — so the host surfaces a
875///   decode error on that message rather than misreading it.
876///
877/// There is deliberately **no feature-detection handshake**. A delegate cannot
878/// ask the host which variants it understands, and adding a probe would itself
879/// be a wire change with the same bootstrapping problem. The rule is therefore
880/// the blunt one: **a delegate that emits a variant introduced in stdlib
881/// version X requires a host built against stdlib >= X.**
882///
883/// A delegate that must work against older hosts has one good alternative: the
884/// V2 host-function API (the `freenet_delegate_contracts` import namespace).
885/// Host functions are resolved **by name at module instantiation**, so an
886/// import an old host does not provide fails at load time with a named
887/// missing-import error, instead of mid-protocol on a decode. That is the
888/// better failure mode, and it is why new capabilities should prefer a host
889/// function over a new variant where there is a choice.
890#[derive(Serialize, Deserialize, Debug, Clone)]
891pub enum OutboundDelegateMsg {
892    // for the apps
893    ApplicationMessage(ApplicationMessage),
894    RequestUserInput(
895        #[serde(deserialize_with = "OutboundDelegateMsg::deser_user_input_req")]
896        UserInputRequest<'static>,
897    ),
898    // todo: remove when context can be accessed from the delegate environment and we pass it as reference
899    ContextUpdated(DelegateContext),
900    GetContractRequest(GetContractRequest),
901    PutContractRequest(PutContractRequest),
902    UpdateContractRequest(UpdateContractRequest),
903    SubscribeContractRequest(SubscribeContractRequest),
904    SendDelegateMessage(DelegateMessage),
905    // Appended in 0.10.0 at tag 8. New variants go at the END, never inserted —
906    // see the wire-format note on this enum.
907    UnsubscribeContractRequest(UnsubscribeContractRequest),
908}
909
910impl From<ApplicationMessage> for OutboundDelegateMsg {
911    fn from(req: ApplicationMessage) -> Self {
912        Self::ApplicationMessage(req)
913    }
914}
915
916impl From<GetContractRequest> for OutboundDelegateMsg {
917    fn from(req: GetContractRequest) -> Self {
918        Self::GetContractRequest(req)
919    }
920}
921
922impl From<PutContractRequest> for OutboundDelegateMsg {
923    fn from(req: PutContractRequest) -> Self {
924        Self::PutContractRequest(req)
925    }
926}
927
928impl From<UpdateContractRequest> for OutboundDelegateMsg {
929    fn from(req: UpdateContractRequest) -> Self {
930        Self::UpdateContractRequest(req)
931    }
932}
933
934impl From<SubscribeContractRequest> for OutboundDelegateMsg {
935    fn from(req: SubscribeContractRequest) -> Self {
936        Self::SubscribeContractRequest(req)
937    }
938}
939
940impl From<UnsubscribeContractRequest> for OutboundDelegateMsg {
941    fn from(req: UnsubscribeContractRequest) -> Self {
942        Self::UnsubscribeContractRequest(req)
943    }
944}
945
946impl From<DelegateMessage> for OutboundDelegateMsg {
947    fn from(msg: DelegateMessage) -> Self {
948        Self::SendDelegateMessage(msg)
949    }
950}
951
952impl OutboundDelegateMsg {
953    fn deser_user_input_req<'de, D>(deser: D) -> Result<UserInputRequest<'static>, D::Error>
954    where
955        D: serde::Deserializer<'de>,
956    {
957        let value = <UserInputRequest<'de> as Deserialize>::deserialize(deser)?;
958        Ok(value.into_owned())
959    }
960
961    pub fn processed(&self) -> bool {
962        match self {
963            OutboundDelegateMsg::ApplicationMessage(msg) => msg.processed,
964            OutboundDelegateMsg::GetContractRequest(msg) => msg.processed,
965            OutboundDelegateMsg::PutContractRequest(msg) => msg.processed,
966            OutboundDelegateMsg::UpdateContractRequest(msg) => msg.processed,
967            OutboundDelegateMsg::SubscribeContractRequest(msg) => msg.processed,
968            OutboundDelegateMsg::UnsubscribeContractRequest(msg) => msg.processed,
969            OutboundDelegateMsg::SendDelegateMessage(msg) => msg.processed,
970            OutboundDelegateMsg::RequestUserInput(_) => true,
971            OutboundDelegateMsg::ContextUpdated(_) => true,
972        }
973    }
974
975    pub fn get_context(&self) -> Option<&DelegateContext> {
976        match self {
977            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
978                Some(context)
979            }
980            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
981                Some(context)
982            }
983            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
984                Some(context)
985            }
986            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
987                context, ..
988            }) => Some(context),
989            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
990                context,
991                ..
992            }) => Some(context),
993            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest {
994                context,
995                ..
996            }) => Some(context),
997            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
998                Some(context)
999            }
1000            _ => None,
1001        }
1002    }
1003
1004    pub fn get_mut_context(&mut self) -> Option<&mut DelegateContext> {
1005        match self {
1006            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage { context, .. }) => {
1007                Some(context)
1008            }
1009            OutboundDelegateMsg::GetContractRequest(GetContractRequest { context, .. }) => {
1010                Some(context)
1011            }
1012            OutboundDelegateMsg::PutContractRequest(PutContractRequest { context, .. }) => {
1013                Some(context)
1014            }
1015            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest {
1016                context, ..
1017            }) => Some(context),
1018            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest {
1019                context,
1020                ..
1021            }) => Some(context),
1022            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest {
1023                context,
1024                ..
1025            }) => Some(context),
1026            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage { context, .. }) => {
1027                Some(context)
1028            }
1029            _ => None,
1030        }
1031    }
1032}
1033
1034/// Request to get contract state from within a delegate.
1035#[derive(Serialize, Deserialize, Debug, Clone)]
1036pub struct GetContractRequest {
1037    pub contract_id: ContractInstanceId,
1038    pub context: DelegateContext,
1039    pub processed: bool,
1040}
1041
1042impl GetContractRequest {
1043    pub fn new(contract_id: ContractInstanceId) -> Self {
1044        Self {
1045            contract_id,
1046            context: Default::default(),
1047            processed: false,
1048        }
1049    }
1050}
1051
1052/// Response containing contract state for a delegate.
1053#[derive(Serialize, Deserialize, Debug, Clone)]
1054pub struct GetContractResponse {
1055    pub contract_id: ContractInstanceId,
1056    /// The contract state, or None if the contract was not found locally.
1057    pub state: Option<WrappedState>,
1058    pub context: DelegateContext,
1059}
1060
1061/// Request to store a new contract from within a delegate.
1062#[derive(Serialize, Deserialize, Debug, Clone)]
1063pub struct PutContractRequest {
1064    /// The contract code and parameters.
1065    pub contract: ContractContainer,
1066    /// The initial state for the contract.
1067    pub state: WrappedState,
1068    /// Related contracts that this contract depends on.
1069    #[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
1070    pub related_contracts: RelatedContracts<'static>,
1071    /// Context for the delegate.
1072    pub context: DelegateContext,
1073    /// Whether this request has been processed.
1074    pub processed: bool,
1075}
1076
1077impl PutContractRequest {
1078    pub fn new(
1079        contract: ContractContainer,
1080        state: WrappedState,
1081        related_contracts: RelatedContracts<'static>,
1082    ) -> Self {
1083        Self {
1084            contract,
1085            state,
1086            related_contracts,
1087            context: Default::default(),
1088            processed: false,
1089        }
1090    }
1091}
1092
1093/// Response after attempting to store a contract from a delegate.
1094#[derive(Serialize, Deserialize, Debug, Clone)]
1095pub struct PutContractResponse {
1096    /// The ID of the contract that was (attempted to be) stored.
1097    pub contract_id: ContractInstanceId,
1098    /// Success (Ok) or error message (Err).
1099    pub result: Result<(), String>,
1100    /// Context for the delegate.
1101    pub context: DelegateContext,
1102}
1103
1104/// Request to update an existing contract's state from within a delegate.
1105#[derive(Serialize, Deserialize, Debug, Clone)]
1106pub struct UpdateContractRequest {
1107    /// The contract to update.
1108    pub contract_id: ContractInstanceId,
1109    /// The update to apply (full state or delta).
1110    #[serde(deserialize_with = "UpdateContractRequest::deser_update_data")]
1111    pub update: UpdateData<'static>,
1112    /// Context for the delegate.
1113    pub context: DelegateContext,
1114    /// Whether this request has been processed.
1115    pub processed: bool,
1116}
1117
1118impl UpdateContractRequest {
1119    pub fn new(contract_id: ContractInstanceId, update: UpdateData<'static>) -> Self {
1120        Self {
1121            contract_id,
1122            update,
1123            context: Default::default(),
1124            processed: false,
1125        }
1126    }
1127
1128    fn deser_update_data<'de, D>(deser: D) -> Result<UpdateData<'static>, D::Error>
1129    where
1130        D: Deserializer<'de>,
1131    {
1132        let value = <UpdateData<'de> as Deserialize>::deserialize(deser)?;
1133        Ok(value.into_owned())
1134    }
1135}
1136
1137/// Response after attempting to update a contract from a delegate.
1138#[derive(Serialize, Deserialize, Debug, Clone)]
1139pub struct UpdateContractResponse {
1140    /// The contract that was updated.
1141    pub contract_id: ContractInstanceId,
1142    /// Success (Ok) or error message (Err).
1143    pub result: Result<(), String>,
1144    /// Context for the delegate.
1145    pub context: DelegateContext,
1146}
1147
1148/// Request to subscribe to a contract's state changes from within a delegate.
1149#[derive(Serialize, Deserialize, Debug, Clone)]
1150pub struct SubscribeContractRequest {
1151    /// The contract to subscribe to.
1152    pub contract_id: ContractInstanceId,
1153    /// Context for the delegate.
1154    pub context: DelegateContext,
1155    /// Whether this request has been processed.
1156    pub processed: bool,
1157}
1158
1159impl SubscribeContractRequest {
1160    pub fn new(contract_id: ContractInstanceId) -> Self {
1161        Self {
1162            contract_id,
1163            context: Default::default(),
1164            processed: false,
1165        }
1166    }
1167}
1168
1169/// Response after attempting to subscribe to a contract from a delegate.
1170#[derive(Serialize, Deserialize, Debug, Clone)]
1171pub struct SubscribeContractResponse {
1172    /// The contract subscribed to.
1173    pub contract_id: ContractInstanceId,
1174    /// Success (Ok) or error message (Err).
1175    pub result: Result<(), String>,
1176    /// Context for the delegate.
1177    pub context: DelegateContext,
1178}
1179
1180/// Request to stop receiving a contract's state changes, from within a delegate.
1181///
1182/// The counterpart of [`SubscribeContractRequest`]. Before 0.10.0 a delegate had
1183/// no way to drop a subscription it had taken: the only release path was the
1184/// implicit cleanup when the delegate itself was unregistered, so a delegate
1185/// that had finished with a contract went on holding interest in it for as long
1186/// as the delegate existed. Specified in freenet-core#2830 alongside subscribe;
1187/// only subscribe was built.
1188///
1189/// Answered with [`InboundDelegateMsg::UnsubscribeContractResponse`].
1190///
1191/// Field order is the wire format. Do not reorder.
1192#[derive(Serialize, Deserialize, Debug, Clone)]
1193pub struct UnsubscribeContractRequest {
1194    /// The contract to stop receiving notifications for.
1195    pub contract_id: ContractInstanceId,
1196    /// Context for the delegate.
1197    pub context: DelegateContext,
1198    /// Whether this request has been processed.
1199    pub processed: bool,
1200}
1201
1202impl UnsubscribeContractRequest {
1203    pub fn new(contract_id: ContractInstanceId) -> Self {
1204        Self {
1205            contract_id,
1206            context: Default::default(),
1207            processed: false,
1208        }
1209    }
1210}
1211
1212/// Response after attempting to unsubscribe from a contract from a delegate.
1213///
1214/// **Unsubscribing a contract the delegate is not subscribed to reports
1215/// `Ok(())`, not an error.** That is not a convenience: it is what the host
1216/// actually does. Teardown goes through the same removal path that a
1217/// no-longer-present client id already takes as a no-op, so returning an error
1218/// would have the host inventing a failure it did not have. It also matches the
1219/// subscribe side, where a repeat subscribe is a set insert.
1220///
1221/// Field order is the wire format. Do not reorder.
1222#[derive(Serialize, Deserialize, Debug, Clone)]
1223pub struct UnsubscribeContractResponse {
1224    /// The contract unsubscribed from.
1225    pub contract_id: ContractInstanceId,
1226    /// Success (Ok) or error message (Err). Unsubscribing a contract the
1227    /// delegate was not subscribed to reports `Ok(())`.
1228    pub result: Result<(), String>,
1229    /// Context for the delegate.
1230    pub context: DelegateContext,
1231}
1232
1233/// A message sent from one delegate to another.
1234///
1235/// Delegates can communicate with each other by emitting
1236/// `OutboundDelegateMsg::SendDelegateMessage` with a `DelegateMessage` targeting
1237/// another delegate. The runtime delivers it as `InboundDelegateMsg::DelegateMessage`
1238/// to the target delegate's `process()` function.
1239///
1240/// The `sender` field is overwritten by the runtime with the actual sender's key
1241/// (sender attestation), so delegates cannot spoof their identity.
1242#[derive(Serialize, Deserialize, Debug, Clone)]
1243pub struct DelegateMessage {
1244    /// The delegate to deliver this message to.
1245    pub target: DelegateKey,
1246    /// The delegate that sent this message (overwritten by runtime for attestation).
1247    pub sender: DelegateKey,
1248    /// Arbitrary message payload.
1249    pub payload: Vec<u8>,
1250    /// Delegate context, carried through the processing pipeline.
1251    pub context: DelegateContext,
1252    /// Runtime protocol flag indicating whether this message has been delivered.
1253    pub processed: bool,
1254}
1255
1256impl DelegateMessage {
1257    pub fn new(target: DelegateKey, sender: DelegateKey, payload: Vec<u8>) -> Self {
1258        Self {
1259            target,
1260            sender,
1261            payload,
1262            context: DelegateContext::default(),
1263            processed: false,
1264        }
1265    }
1266}
1267
1268/// Notification delivered to a delegate when a subscribed contract's state changes.
1269#[derive(Serialize, Deserialize, Debug, Clone)]
1270pub struct ContractNotification {
1271    /// The contract whose state changed.
1272    pub contract_id: ContractInstanceId,
1273    /// The new state of the contract.
1274    pub new_state: WrappedState,
1275    /// Context for the delegate.
1276    pub context: DelegateContext,
1277}
1278
1279#[serde_as]
1280#[derive(Serialize, Deserialize, Debug, Clone)]
1281pub struct NotificationMessage<'a>(
1282    #[serde_as(as = "serde_with::Bytes")]
1283    #[serde(borrow)]
1284    Cow<'a, [u8]>,
1285);
1286
1287impl TryFrom<&serde_json::Value> for NotificationMessage<'static> {
1288    type Error = ();
1289
1290    fn try_from(json: &serde_json::Value) -> Result<NotificationMessage<'static>, ()> {
1291        // todo: validate format when we have a better idea of what we want here
1292        let bytes = serde_json::to_vec(json).unwrap();
1293        Ok(Self(Cow::Owned(bytes)))
1294    }
1295}
1296
1297impl NotificationMessage<'_> {
1298    pub fn into_owned(self) -> NotificationMessage<'static> {
1299        NotificationMessage(self.0.into_owned().into())
1300    }
1301    pub fn bytes(&self) -> &[u8] {
1302        self.0.as_ref()
1303    }
1304}
1305
1306#[serde_as]
1307#[derive(Serialize, Deserialize, Debug, Clone)]
1308pub struct ClientResponse<'a>(
1309    #[serde_as(as = "serde_with::Bytes")]
1310    #[serde(borrow)]
1311    Cow<'a, [u8]>,
1312);
1313
1314impl Deref for ClientResponse<'_> {
1315    type Target = [u8];
1316
1317    fn deref(&self) -> &Self::Target {
1318        &self.0
1319    }
1320}
1321
1322impl ClientResponse<'_> {
1323    pub fn new(response: Vec<u8>) -> Self {
1324        Self(response.into())
1325    }
1326    pub fn into_owned(self) -> ClientResponse<'static> {
1327        ClientResponse(self.0.into_owned().into())
1328    }
1329    pub fn bytes(&self) -> &[u8] {
1330        self.0.as_ref()
1331    }
1332}
1333
1334#[derive(Serialize, Deserialize, Debug, Clone)]
1335pub struct UserInputRequest<'a> {
1336    pub request_id: u32,
1337    #[serde(borrow)]
1338    /// An interpretable message by the notification system.
1339    pub message: NotificationMessage<'a>,
1340    /// If a response is required from the user they can be chosen from this list.
1341    pub responses: Vec<ClientResponse<'a>>,
1342}
1343
1344impl UserInputRequest<'_> {
1345    pub fn into_owned(self) -> UserInputRequest<'static> {
1346        UserInputRequest {
1347            request_id: self.request_id,
1348            message: self.message.into_owned(),
1349            responses: self.responses.into_iter().map(|r| r.into_owned()).collect(),
1350        }
1351    }
1352}
1353
1354#[doc(hidden)]
1355pub(crate) mod wasm_interface {
1356    //! Contains all the types to interface between the host environment and
1357    //! the wasm module execution.
1358    use super::*;
1359    use crate::memory::WasmLinearMem;
1360
1361    #[repr(C)]
1362    #[derive(Debug, Clone, Copy)]
1363    pub struct DelegateInterfaceResult {
1364        ptr: i64,
1365        size: u32,
1366    }
1367
1368    impl DelegateInterfaceResult {
1369        pub unsafe fn from_raw(ptr: i64, mem: &WasmLinearMem) -> Self {
1370            let result = Box::leak(Box::from_raw(crate::memory::buf::compute_ptr(
1371                ptr as *mut Self,
1372                mem,
1373            )));
1374            #[cfg(feature = "trace")]
1375            {
1376                tracing::trace!(
1377                    "got FFI result @ {ptr} ({:p}) -> {result:?}",
1378                    ptr as *mut Self
1379                );
1380            }
1381            *result
1382        }
1383
1384        #[cfg(feature = "contract")]
1385        pub fn into_raw(self) -> i64 {
1386            #[cfg(feature = "trace")]
1387            {
1388                tracing::trace!("returning FFI -> {self:?}");
1389            }
1390            let ptr = Box::into_raw(Box::new(self));
1391            #[cfg(feature = "trace")]
1392            {
1393                tracing::trace!("FFI result ptr: {ptr:p} ({}i64)", ptr as i64);
1394            }
1395            ptr as _
1396        }
1397
1398        pub unsafe fn unwrap(
1399            self,
1400            mem: WasmLinearMem,
1401        ) -> Result<Vec<OutboundDelegateMsg>, DelegateError> {
1402            let ptr = crate::memory::buf::compute_ptr(self.ptr as *mut u8, &mem);
1403            let serialized = std::slice::from_raw_parts(ptr as *const u8, self.size as _);
1404            let value: Result<Vec<OutboundDelegateMsg>, DelegateError> =
1405                bincode::deserialize(serialized)
1406                    .map_err(|e| DelegateError::Other(format!("{e}")))?;
1407            #[cfg(feature = "trace")]
1408            {
1409                tracing::trace!(
1410                    "got result through FFI; addr: {:p} ({}i64, mapped: {ptr:p})
1411                     serialized: {serialized:?}
1412                     value: {value:?}",
1413                    self.ptr as *mut u8,
1414                    self.ptr
1415                );
1416            }
1417            value
1418        }
1419    }
1420
1421    impl From<Result<Vec<OutboundDelegateMsg>, DelegateError>> for DelegateInterfaceResult {
1422        fn from(value: Result<Vec<OutboundDelegateMsg>, DelegateError>) -> Self {
1423            let serialized = bincode::serialize(&value).unwrap();
1424            let size = serialized.len() as _;
1425            let ptr = serialized.as_ptr();
1426            #[cfg(feature = "trace")]
1427            {
1428                tracing::trace!(
1429                    "sending result through FFI; addr: {ptr:p} ({}),\n  serialized: {serialized:?}\n  value: {value:?}",
1430                    ptr as i64
1431                );
1432            }
1433            std::mem::forget(serialized);
1434            Self {
1435                ptr: ptr as i64,
1436                size,
1437            }
1438        }
1439    }
1440}
1441
1442#[cfg(test)]
1443mod message_origin_tests {
1444    use super::*;
1445
1446    /// Wire-format pin: bincode encoding of `MessageOrigin::WebApp(..)` must
1447    /// stay byte-identical across stdlib releases. Deployed delegate WASM
1448    /// compiled against an older stdlib will receive these bytes from a
1449    /// host running the new stdlib and must continue to deserialize them.
1450    /// If this test ever fails, it is a wire-format break and is NOT
1451    /// publishable as a non-major bump.
1452    #[test]
1453    fn webapp_origin_wire_format_is_stable() {
1454        let id = ContractInstanceId::new([0xABu8; 32]);
1455        let origin = MessageOrigin::WebApp(id);
1456        let encoded = bincode::serialize(&origin).unwrap();
1457
1458        // Variant tag 0 (4-byte LE u32 in default bincode config) followed by
1459        // the 32 raw bytes of the ContractInstanceId.
1460        let mut expected = vec![0u8, 0, 0, 0];
1461        expected.extend_from_slice(&[0xABu8; 32]);
1462        assert_eq!(encoded, expected);
1463    }
1464
1465    /// Wire-format pin for the `Delegate` variant. Locks the full byte
1466    /// layout (variant tag + serde repr of `DelegateKey`) so that any future
1467    /// change to either `DelegateKey`'s serde or the workspace bincode
1468    /// config is caught loudly. If `DelegateKey`'s on-the-wire encoding
1469    /// changes, deployed delegates compiled against a previous stdlib will
1470    /// silently fail to deserialize inter-delegate origins — which is
1471    /// exactly the failure mode this test exists to prevent.
1472    #[test]
1473    fn delegate_origin_wire_format_is_stable() {
1474        let key = DelegateKey::new([0x11u8; 32], crate::code_hash::CodeHash::new([0x22u8; 32]));
1475        let origin = MessageOrigin::Delegate(key);
1476        let encoded = bincode::serialize(&origin).unwrap();
1477
1478        // Variant tag 1 (4-byte LE u32 in default bincode config), followed
1479        // by the 32-byte `key` field, followed by the 32-byte `code_hash`
1480        // field of `DelegateKey`.
1481        let mut expected = vec![1u8, 0, 0, 0];
1482        expected.extend_from_slice(&[0x11u8; 32]);
1483        expected.extend_from_slice(&[0x22u8; 32]);
1484        assert_eq!(encoded, expected);
1485
1486        // And it must still round-trip.
1487        let decoded: MessageOrigin = bincode::deserialize(&encoded).unwrap();
1488        assert!(matches!(decoded, MessageOrigin::Delegate(_)));
1489    }
1490
1491    /// Wire-format pin for the first variant of [`InboundDelegateMsg`]. Pins
1492    /// the tag so that reordering the enum cannot silently shift existing
1493    /// deployed delegate WASM off the correct variant. Only tag+payload
1494    /// prefix is asserted (not the full ApplicationMessage byte layout),
1495    /// since ApplicationMessage's internal fields have their own stability
1496    /// expectations handled at a different layer. What matters here is that
1497    /// variant 0 stays `ApplicationMessage` on the wire.
1498    #[test]
1499    fn inbound_delegate_msg_wire_format_is_stable() {
1500        let msg = InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC]));
1501        let encoded = bincode::serialize(&msg).unwrap();
1502        assert_eq!(
1503            encoded[..4],
1504            [0, 0, 0, 0],
1505            "ApplicationMessage must stay at variant tag 0 on the wire; \
1506             reordering InboundDelegateMsg variants is a wire-format break"
1507        );
1508        // And it must still round-trip into the same variant.
1509        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&encoded).unwrap();
1510        assert!(matches!(decoded, InboundDelegateMsg::ApplicationMessage(_)));
1511    }
1512
1513    /// Wire-format pin for [`InboundDelegateMsg::WakeupFired`]. It is the 10th
1514    /// variant (declaration index 9), so its bincode tag must be `9` (4-byte
1515    /// LE) — it sits behind `UnsubscribeContractResponse` at tag 8. Once
1516    /// shipped this tag is frozen: reordering or inserting a variant ahead of
1517    /// it would silently redirect a host's wakeup delivery to the wrong variant
1518    /// on a delegate compiled against this stdlib.
1519    #[test]
1520    fn inbound_wakeup_fired_wire_format_is_stable() {
1521        let msg = InboundDelegateMsg::WakeupFired {
1522            tag: vec![0xAA, 0xBB],
1523        };
1524        let encoded = bincode::serialize(&msg).unwrap();
1525
1526        // tag 9 (u32 LE) + Vec<u8> len (u64 LE = 2) + the two tag bytes.
1527        let mut expected = vec![9u8, 0, 0, 0];
1528        expected.extend_from_slice(&[2, 0, 0, 0, 0, 0, 0, 0]);
1529        expected.extend_from_slice(&[0xAA, 0xBB]);
1530        assert_eq!(
1531            encoded, expected,
1532            "WakeupFired must stay at variant tag 9 with a stable payload layout"
1533        );
1534
1535        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&encoded).unwrap();
1536        assert!(matches!(
1537            decoded,
1538            InboundDelegateMsg::WakeupFired { tag } if tag == vec![0xAA, 0xBB]
1539        ));
1540    }
1541}
1542
1543/// Executable evidence for the wire-compatibility rules documented on
1544/// [`InboundDelegateMsg`] and [`OutboundDelegateMsg`].
1545///
1546/// The claims those doc comments make about bincode's behaviour are asserted
1547/// here rather than believed, because every one of them is the kind of claim
1548/// that is easy to state, easy to get backwards, and impossible to notice being
1549/// wrong until deployed delegate WASM misreads a message in production.
1550#[cfg(test)]
1551mod delegate_wire_compat {
1552    use super::*;
1553    use crate::contract_interface::WrappedContract;
1554    use crate::prelude::ContractCode;
1555    use crate::versioning::ContractWasmAPIVersion;
1556    use std::sync::Arc;
1557
1558    /// The number of variants each enum has **today**. These are not free
1559    /// parameters: see `an_unpinned_variant_fails_this_test`, which is what
1560    /// makes them fail closed rather than drift.
1561    const INBOUND_VARIANT_COUNT: u32 = 10;
1562    const OUTBOUND_VARIANT_COUNT: u32 = 9;
1563
1564    fn instance_id() -> ContractInstanceId {
1565        ContractInstanceId::new([0x5Au8; 32])
1566    }
1567
1568    fn delegate_key() -> DelegateKey {
1569        DelegateKey::new([0x11u8; 32], CodeHash::new([0x22u8; 32]))
1570    }
1571
1572    fn contract_container() -> ContractContainer {
1573        ContractContainer::Wasm(ContractWasmAPIVersion::V1(WrappedContract::new(
1574            Arc::new(ContractCode::from(vec![1u8, 2, 3])),
1575            Parameters::from(vec![9u8, 8, 7]),
1576        )))
1577    }
1578
1579    /// The bincode variant tag actually on the wire: a 4-byte little-endian
1580    /// u32 prefix (this workspace's bincode config uses fixint encoding).
1581    fn wire_tag(encoded: &[u8]) -> u32 {
1582        u32::from_le_bytes(
1583            encoded[..4]
1584                .try_into()
1585                .expect("a bincode enum encoding starts with a 4-byte tag"),
1586        )
1587    }
1588
1589    /// The tag each [`InboundDelegateMsg`] variant is frozen at, forever.
1590    ///
1591    /// This match is **exhaustive on purpose**. `#[non_exhaustive]` has no
1592    /// effect inside the crate that defines the enum, so adding a variant
1593    /// without adding an arm here is a **compile error** — which is the point.
1594    /// A new variant cannot slip in unpinned.
1595    ///
1596    /// If you are here because you added a variant: give it the next unused
1597    /// number, append it at the END of the enum, add it to `every_inbound`
1598    /// below, and bump `INBOUND_VARIANT_COUNT`. Do not renumber anything.
1599    fn pinned_inbound_tag(msg: &InboundDelegateMsg<'_>) -> u32 {
1600        match msg {
1601            InboundDelegateMsg::ApplicationMessage(_) => 0,
1602            InboundDelegateMsg::UserResponse(_) => 1,
1603            InboundDelegateMsg::GetContractResponse(_) => 2,
1604            InboundDelegateMsg::PutContractResponse(_) => 3,
1605            InboundDelegateMsg::UpdateContractResponse(_) => 4,
1606            InboundDelegateMsg::SubscribeContractResponse(_) => 5,
1607            InboundDelegateMsg::ContractNotification(_) => 6,
1608            InboundDelegateMsg::DelegateMessage(_) => 7,
1609            InboundDelegateMsg::UnsubscribeContractResponse(_) => 8,
1610            InboundDelegateMsg::WakeupFired { .. } => 9,
1611        }
1612    }
1613
1614    /// The tag each [`OutboundDelegateMsg`] variant is frozen at, forever.
1615    /// Exhaustive for the same reason as [`pinned_inbound_tag`].
1616    fn pinned_outbound_tag(msg: &OutboundDelegateMsg) -> u32 {
1617        match msg {
1618            OutboundDelegateMsg::ApplicationMessage(_) => 0,
1619            OutboundDelegateMsg::RequestUserInput(_) => 1,
1620            OutboundDelegateMsg::ContextUpdated(_) => 2,
1621            OutboundDelegateMsg::GetContractRequest(_) => 3,
1622            OutboundDelegateMsg::PutContractRequest(_) => 4,
1623            OutboundDelegateMsg::UpdateContractRequest(_) => 5,
1624            OutboundDelegateMsg::SubscribeContractRequest(_) => 6,
1625            OutboundDelegateMsg::SendDelegateMessage(_) => 7,
1626            OutboundDelegateMsg::UnsubscribeContractRequest(_) => 8,
1627        }
1628    }
1629
1630    /// One value of every [`InboundDelegateMsg`] variant.
1631    fn every_inbound() -> Vec<InboundDelegateMsg<'static>> {
1632        let id = instance_id();
1633        let ctx = DelegateContext::default();
1634        vec![
1635            InboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC])),
1636            InboundDelegateMsg::UserResponse(UserInputResponse {
1637                request_id: 7,
1638                response: ClientResponse::new(vec![0x01]),
1639                context: ctx.clone(),
1640            }),
1641            InboundDelegateMsg::GetContractResponse(GetContractResponse {
1642                contract_id: id,
1643                state: None,
1644                context: ctx.clone(),
1645            }),
1646            InboundDelegateMsg::PutContractResponse(PutContractResponse {
1647                contract_id: id,
1648                result: Ok(()),
1649                context: ctx.clone(),
1650            }),
1651            InboundDelegateMsg::UpdateContractResponse(UpdateContractResponse {
1652                contract_id: id,
1653                result: Ok(()),
1654                context: ctx.clone(),
1655            }),
1656            InboundDelegateMsg::SubscribeContractResponse(SubscribeContractResponse {
1657                contract_id: id,
1658                result: Ok(()),
1659                context: ctx.clone(),
1660            }),
1661            InboundDelegateMsg::ContractNotification(ContractNotification {
1662                contract_id: id,
1663                new_state: WrappedState::new(vec![0xAB]),
1664                context: ctx.clone(),
1665            }),
1666            InboundDelegateMsg::DelegateMessage(DelegateMessage::new(
1667                delegate_key(),
1668                delegate_key(),
1669                vec![0xEE],
1670            )),
1671            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
1672                contract_id: id,
1673                result: Ok(()),
1674                context: ctx.clone(),
1675            }),
1676            InboundDelegateMsg::WakeupFired {
1677                tag: vec![0xAA, 0xBB],
1678            },
1679        ]
1680    }
1681
1682    /// One value of every [`OutboundDelegateMsg`] variant.
1683    ///
1684    /// Every variant is covered, `PutContractRequest` included: building a
1685    /// `ContractContainer` is four lines (see `contract_container`), and a pin
1686    /// test with a hole in it is exactly the shape of guard that reads as
1687    /// coverage while providing none.
1688    fn every_outbound() -> Vec<OutboundDelegateMsg> {
1689        let id = instance_id();
1690        vec![
1691            OutboundDelegateMsg::ApplicationMessage(ApplicationMessage::new(vec![0xCC])),
1692            OutboundDelegateMsg::RequestUserInput(UserInputRequest {
1693                request_id: 7,
1694                message: NotificationMessage(Cow::Owned(vec![0x02])),
1695                responses: vec![],
1696            }),
1697            OutboundDelegateMsg::ContextUpdated(DelegateContext::default()),
1698            OutboundDelegateMsg::GetContractRequest(GetContractRequest::new(id)),
1699            OutboundDelegateMsg::PutContractRequest(PutContractRequest::new(
1700                contract_container(),
1701                WrappedState::new(vec![0xAB]),
1702                RelatedContracts::default(),
1703            )),
1704            OutboundDelegateMsg::UpdateContractRequest(UpdateContractRequest::new(
1705                id,
1706                UpdateData::State(vec![0xAB].into()),
1707            )),
1708            OutboundDelegateMsg::SubscribeContractRequest(SubscribeContractRequest::new(id)),
1709            OutboundDelegateMsg::SendDelegateMessage(DelegateMessage::new(
1710                delegate_key(),
1711                delegate_key(),
1712                vec![0xEE],
1713            )),
1714            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest::new(id)),
1715        ]
1716    }
1717
1718    /// Pins the bincode variant tag of **every** variant of both delegate
1719    /// message enums.
1720    ///
1721    /// The pin this replaces covered `InboundDelegateMsg`'s variant 0 alone, so
1722    /// any reorder that happened to leave `ApplicationMessage` first — swapping
1723    /// `UserResponse` and `GetContractResponse`, say — went undetected. That is
1724    /// not a theoretical gap: exactly that swap was written, and staged, during
1725    /// the work that produced this test.
1726    ///
1727    /// A reorder is the dangerous edit precisely because it is silent. The
1728    /// bytes still decode. They decode into the wrong variant, and the failure
1729    /// surfaces as a delegate acting on a message it was never sent.
1730    ///
1731    /// **If this test fails, do not update the expected numbers.** Either a
1732    /// variant was inserted or reordered (revert it; append instead), or one
1733    /// was removed — which reassigns every later tag and is a wire break
1734    /// needing a deliberate release decision. See the
1735    /// `RegisterDelegateWithPredecessors` removal in 0.9.0 for the shape of
1736    /// that decision: it was appended last specifically so that removing it
1737    /// renumbered nothing.
1738    #[test]
1739    fn delegate_msg_variant_tags_are_pinned() {
1740        for msg in every_inbound() {
1741            let expected = pinned_inbound_tag(&msg);
1742            let encoded = bincode::serialize(&msg).expect("inbound must serialize");
1743            assert_eq!(
1744                wire_tag(&encoded),
1745                expected,
1746                "InboundDelegateMsg::{msg:?} moved off wire tag {expected}; inserting, \
1747                 reordering or removing variants breaks deployed delegate WASM"
1748            );
1749        }
1750
1751        for msg in every_outbound() {
1752            let expected = pinned_outbound_tag(&msg);
1753            let encoded = bincode::serialize(&msg).expect("outbound must serialize");
1754            assert_eq!(
1755                wire_tag(&encoded),
1756                expected,
1757                "OutboundDelegateMsg::{msg:?} moved off wire tag {expected}; inserting, \
1758                 reordering or removing variants breaks deployed delegate WASM"
1759            );
1760        }
1761    }
1762
1763    /// Every variant is actually exercised by the pin above.
1764    ///
1765    /// [`pinned_inbound_tag`] is exhaustive, so a new variant cannot be left
1766    /// unpinned without a compile error — but it *could* be left out of
1767    /// `every_inbound`, and then the pin would silently stop covering it.
1768    /// Asserting that the sampled tags are exactly `0..COUNT`, with no gaps and
1769    /// no repeats, closes that.
1770    #[test]
1771    fn every_variant_is_covered_by_the_pin() {
1772        let mut inbound: Vec<u32> = every_inbound().iter().map(pinned_inbound_tag).collect();
1773        inbound.sort_unstable();
1774        assert_eq!(
1775            inbound,
1776            (0..INBOUND_VARIANT_COUNT).collect::<Vec<_>>(),
1777            "every_inbound must contain each InboundDelegateMsg variant exactly once"
1778        );
1779
1780        let mut outbound: Vec<u32> = every_outbound().iter().map(pinned_outbound_tag).collect();
1781        outbound.sort_unstable();
1782        assert_eq!(
1783            outbound,
1784            (0..OUTBOUND_VARIANT_COUNT).collect::<Vec<_>>(),
1785            "every_outbound must contain each OutboundDelegateMsg variant exactly once"
1786        );
1787    }
1788
1789    /// The count constants above cannot be allowed to drift, so this probes the
1790    /// enums themselves: a payload whose tag is one past the last known variant
1791    /// must fail to decode.
1792    ///
1793    /// This is the test that fails **closed**. Add a variant and forget
1794    /// everything else here, and the tag that was previously undecodable
1795    /// becomes decodable, and this fails. Without it, `INBOUND_VARIANT_COUNT`
1796    /// would be a number asserted only against a list written by the same hand
1797    /// in the same commit — which is not a check, it is a restatement.
1798    ///
1799    /// The payload is a run of zero bytes after the tag, which decodes as
1800    /// empty vectors, `None`, `Ok`, `false` and zeroed arrays, so it satisfies
1801    /// essentially any variant shape a new variant is likely to have. Trailing
1802    /// bytes are ignored: `bincode::deserialize` configures
1803    /// `allow_trailing_bytes()` (bincode-1.3.3 `src/lib.rs`), which is also why
1804    /// a fixed-size probe is safe here.
1805    #[test]
1806    fn an_unpinned_variant_fails_this_test() {
1807        // The probe must fail because the TAG is unknown, not because a
1808        // payload of zeros happened not to parse. Asserting only `is_err()`
1809        // would let a new variant whose first field rejects zeros (a
1810        // `DateTime`, a `NonZero*`, a validating `deserialize_with`) go
1811        // undetected: the tag would be valid, the decode would still fail, and
1812        // this test would stay green while the counts drifted.
1813        //
1814        // bincode hands an out-of-range variant index to serde's derived
1815        // visitor, which rejects it as `invalid value: integer `N`, expected
1816        // variant index 0 <= i < M` — an `ErrorKind::Custom`. Match on that
1817        // wording rather than on `InvalidTagEncoding`, which bincode produces
1818        // only for a bad `Option` discriminant.
1819        fn assert_rejected_as_unknown_variant(err: &bincode::Error, tag: u32, which: &str) {
1820            let msg = err.to_string();
1821            assert!(
1822                msg.contains("variant index"),
1823                "tag {tag} on {which} failed for the wrong reason ({msg}); the tag itself must \
1824                 still be unknown, otherwise a variant was added without updating the count, \
1825                 the pinned_*_tag match and the every_* list"
1826            );
1827        }
1828
1829        let mut probe = INBOUND_VARIANT_COUNT.to_le_bytes().to_vec();
1830        probe.extend_from_slice(&[0u8; 256]);
1831        let err = match bincode::deserialize::<InboundDelegateMsg<'_>>(&probe) {
1832            Ok(v) => panic!(
1833                "tag {INBOUND_VARIANT_COUNT} must not decode as an InboundDelegateMsg, got {v:?}"
1834            ),
1835            Err(e) => e,
1836        };
1837        assert_rejected_as_unknown_variant(&err, INBOUND_VARIANT_COUNT, "InboundDelegateMsg");
1838
1839        let mut probe = OUTBOUND_VARIANT_COUNT.to_le_bytes().to_vec();
1840        probe.extend_from_slice(&[0u8; 256]);
1841        let err = match bincode::deserialize::<OutboundDelegateMsg>(&probe) {
1842            Ok(v) => panic!(
1843                "tag {OUTBOUND_VARIANT_COUNT} must not decode as an OutboundDelegateMsg, got {v:?}"
1844            ),
1845            Err(e) => e,
1846        };
1847        assert_rejected_as_unknown_variant(&err, OUTBOUND_VARIANT_COUNT, "OutboundDelegateMsg");
1848
1849        // Control, so the probe cannot pass vacuously from the other end: the
1850        // LAST known tag must still decode from the same all-zero payload. If
1851        // this ever fails, the zero payload has stopped being a valid encoding
1852        // for the final variant, and the probes above are no longer testing
1853        // what they claim.
1854        let mut control = (INBOUND_VARIANT_COUNT - 1).to_le_bytes().to_vec();
1855        control.extend_from_slice(&[0u8; 256]);
1856        bincode::deserialize::<InboundDelegateMsg<'_>>(&control).expect(
1857            "the LAST inbound variant's payload must be decodable from zeros, or this probe can \
1858             no longer tell an unknown tag from an unparseable payload. If a variant whose \
1859             payload rejects zeros was just appended, do not delete this — point the control at \
1860             a variant that still decodes from zeros",
1861        );
1862
1863        let mut control = (OUTBOUND_VARIANT_COUNT - 1).to_le_bytes().to_vec();
1864        control.extend_from_slice(&[0u8; 256]);
1865        bincode::deserialize::<OutboundDelegateMsg>(&control).expect(
1866            "the LAST outbound variant's payload must be decodable from zeros — see the inbound \
1867             control above for what to do if that stops being true",
1868        );
1869    }
1870
1871    /// Direction 1 of the append rule: **old sender to new receiver works.**
1872    ///
1873    /// The payload is hand-built rather than produced by this crate's own
1874    /// encoder, so it stands in for bytes emitted by a delegate compiled
1875    /// against an older stdlib; an encoder-produced value would only prove the
1876    /// code agrees with itself.
1877    ///
1878    /// Named for what it actually pins. Nothing here appends a variant — the
1879    /// test cannot fail *because of* an append, only because a tag moved or a
1880    /// payload layout changed, which `delegate_msg_variant_tags_are_pinned`
1881    /// also covers. Its distinct value is that the expected bytes are written
1882    /// out by hand, so a change to `ContractNotification`'s field order or to
1883    /// the bincode config fails here with a concrete byte string to compare
1884    /// against. Direction 2, which genuinely models an old receiver, is
1885    /// `a_new_variant_does_not_decode_on_an_old_receiver` below.
1886    #[test]
1887    fn a_hand_built_old_encoder_payload_decodes_into_the_same_variant() {
1888        // InboundDelegateMsg tag 6 = ContractNotification { contract_id,
1889        // new_state: WrappedState (empty), context: DelegateContext (empty) }.
1890        let mut old_payload = vec![6u8, 0, 0, 0];
1891        old_payload.extend_from_slice(&[0x5Au8; 32]);
1892        old_payload.extend_from_slice(&0u64.to_le_bytes()); // new_state: len 0
1893        old_payload.extend_from_slice(&0u64.to_le_bytes()); // context: len 0
1894
1895        let decoded: InboundDelegateMsg<'_> = bincode::deserialize(&old_payload)
1896            .expect("a payload predating any appended variant must still decode");
1897        match decoded {
1898            InboundDelegateMsg::ContractNotification(n) => {
1899                assert_eq!(n.contract_id, instance_id());
1900            }
1901            other => panic!("an old ContractNotification decoded as {other:?}"),
1902        }
1903    }
1904
1905    /// Direction 2 of the append rule: **new sender to old receiver fails, and
1906    /// fails loudly.** This is the direction the docs warn about, so it is
1907    /// asserted rather than assumed.
1908    ///
1909    /// An old receiver is modelled by an enum with a truncated tag space,
1910    /// which is exactly what an older stdlib's version of these types is. The
1911    /// point is that the failure is an `Err` — not a silent mis-decode into
1912    /// whatever variant happens to sit at that index.
1913    #[test]
1914    fn a_new_variant_does_not_decode_on_an_old_receiver() {
1915        // An "old" OutboundDelegateMsg that knows tags 0..=6 only, i.e. one
1916        // built before `SendDelegateMessage` was appended at 7.
1917        // Variants are only ever produced by deserialization, never
1918        // constructed here — which is the whole point of the test.
1919        #[allow(dead_code)]
1920        #[derive(serde::Deserialize, Debug)]
1921        enum OldOutboundTagSpace {
1922            V0,
1923            V1,
1924            V2,
1925            V3,
1926            V4,
1927            V5,
1928            V6,
1929        }
1930
1931        let new_msg = bincode::serialize(&OutboundDelegateMsg::SendDelegateMessage(
1932            DelegateMessage::new(delegate_key(), delegate_key(), vec![0xEE]),
1933        ))
1934        .expect("outbound must serialize");
1935        assert_eq!(wire_tag(&new_msg), 7);
1936
1937        let decoded = bincode::deserialize::<OldOutboundTagSpace>(&new_msg);
1938        assert!(
1939            decoded.is_err(),
1940            "a receiver that predates a variant must REJECT it, not mis-decode it; \
1941             if this ever passes, the compatibility rule documented on \
1942             OutboundDelegateMsg is wrong and delegates are silently misreading messages"
1943        );
1944    }
1945
1946    /// The unsubscribe pair added in 0.10.0 round-trips, and adding it did not
1947    /// disturb any payload that predates it.
1948    ///
1949    /// The pre-0.10.0 byte string is hand-built rather than produced by this
1950    /// crate, so it stands in for bytes from a delegate compiled before the
1951    /// pair existed. Both halves matter: the new variant must work, and the old
1952    /// ones must be untouched by its arrival.
1953    #[test]
1954    fn the_unsubscribe_pair_round_trips_and_disturbs_nothing_older() {
1955        let id = instance_id();
1956
1957        let req =
1958            OutboundDelegateMsg::UnsubscribeContractRequest(UnsubscribeContractRequest::new(id));
1959        let encoded = bincode::serialize(&req).expect("request must serialize");
1960        assert_eq!(wire_tag(&encoded), 8, "unsubscribe request is frozen at 8");
1961        match bincode::deserialize::<OutboundDelegateMsg>(&encoded).expect("must round-trip") {
1962            OutboundDelegateMsg::UnsubscribeContractRequest(r) => {
1963                assert_eq!(r.contract_id, id);
1964                assert!(!r.processed);
1965            }
1966            other => panic!("round-tripped into {other:?}"),
1967        }
1968
1969        let resp = InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
1970            contract_id: id,
1971            result: Ok(()),
1972            context: DelegateContext::default(),
1973        });
1974        let encoded = bincode::serialize(&resp).expect("response must serialize");
1975        assert_eq!(wire_tag(&encoded), 8, "unsubscribe response is frozen at 8");
1976        match bincode::deserialize::<InboundDelegateMsg<'_>>(&encoded).expect("must round-trip") {
1977            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
1978                // Assert the VALUES, not merely the variant. Checking only
1979                // `matches!` is what lets a field reorder through: the encoder
1980                // and decoder would still agree with each other.
1981                assert_eq!(r.contract_id, id);
1982                assert!(r.result.is_ok());
1983            }
1984            other => panic!("round-tripped into {other:?}"),
1985        }
1986
1987        // Both structs' doc comments say the field ORDER is the wire format.
1988        // A round-trip through this crate's own encoder cannot establish that —
1989        // it proves the code agrees with itself, and a swap of `contract_id`
1990        // and `result` would round-trip just as happily. So the layout is
1991        // frozen as hand-written bytes, the same way ContractNotification is.
1992        let mut expected_resp = vec![8u8, 0, 0, 0];
1993        expected_resp.extend_from_slice(&[0x5Au8; 32]); // contract_id
1994        expected_resp.extend_from_slice(&0u32.to_le_bytes()); // result: Ok variant tag
1995        expected_resp.extend_from_slice(&0u64.to_le_bytes()); // context: empty
1996        assert_eq!(
1997            encoded, expected_resp,
1998            "UnsubscribeContractResponse layout is frozen: tag, contract_id, result, context"
1999        );
2000
2001        let expected_req = {
2002            let mut v = vec![8u8, 0, 0, 0];
2003            v.extend_from_slice(&[0x5Au8; 32]); // contract_id
2004            v.extend_from_slice(&0u64.to_le_bytes()); // context: empty
2005            v.push(0u8); // processed: false
2006            v
2007        };
2008        assert_eq!(
2009            bincode::serialize(&req).expect("request must serialize"),
2010            expected_req,
2011            "UnsubscribeContractRequest layout is frozen: tag, contract_id, context, processed"
2012        );
2013
2014        // The error path has a different bincode shape from Ok and is part of
2015        // the same frozen layout, so it is exercised rather than assumed.
2016        let err_resp =
2017            InboundDelegateMsg::UnsubscribeContractResponse(UnsubscribeContractResponse {
2018                contract_id: id,
2019                result: Err("nope".to_string()),
2020                context: DelegateContext::default(),
2021            });
2022        match bincode::deserialize::<InboundDelegateMsg<'_>>(
2023            &bincode::serialize(&err_resp).expect("must serialize"),
2024        )
2025        .expect("must round-trip")
2026        {
2027            InboundDelegateMsg::UnsubscribeContractResponse(r) => {
2028                assert_eq!(r.result.unwrap_err(), "nope");
2029            }
2030            other => panic!("error response round-tripped into {other:?}"),
2031        }
2032
2033        // A ContractNotification encoded before 0.10.0 existed: tag 6, the 32
2034        // raw id bytes, an empty state and an empty context. Appending at 8
2035        // must leave it decoding exactly as it always did.
2036        let mut pre_0_9_0 = vec![6u8, 0, 0, 0];
2037        pre_0_9_0.extend_from_slice(&[0x5Au8; 32]);
2038        pre_0_9_0.extend_from_slice(&0u64.to_le_bytes());
2039        pre_0_9_0.extend_from_slice(&0u64.to_le_bytes());
2040        match bincode::deserialize::<InboundDelegateMsg<'_>>(&pre_0_9_0)
2041            .expect("a pre-0.10.0 payload must still decode")
2042        {
2043            InboundDelegateMsg::ContractNotification(n) => assert_eq!(n.contract_id, id),
2044            other => panic!("a pre-0.10.0 ContractNotification decoded as {other:?}"),
2045        }
2046    }
2047
2048    /// Every inbound variant whose payload carries a `context` must return it.
2049    ///
2050    /// Both `get_context` and `get_mut_context` end in `_ => None`, so a
2051    /// missing arm is not a compile error — it silently reports "no context".
2052    /// That wildcard had already swallowed one: `UserResponse` carries a
2053    /// context and returned `None` for it, undetected, because nothing in the
2054    /// crate called either accessor.
2055    ///
2056    /// Driven off `every_inbound`, so a newly appended variant is covered the
2057    /// moment it is added to that list — which the tag pin already forces.
2058    #[test]
2059    fn every_inbound_variant_with_a_context_exposes_it() {
2060        for mut msg in every_inbound() {
2061            let tag = pinned_inbound_tag(&msg);
2062
2063            // `WakeupFired` is the one inbound variant with no context field,
2064            // and it is named here rather than skipped by a wildcard, matching
2065            // the outbound test below. See `get_context` for why it has none:
2066            // a context is per-conversation working state handed back on a
2067            // reply, and a wakeup opens a conversation rather than continuing
2068            // one. Carrying one would commit the host to persisting delegate
2069            // context across arbitrary wall-clock time, which is #5467 Phase 3.
2070            //
2071            // This asserts the accessor returns `None`, not that the struct
2072            // lacks a field. That distinction is the point: the claim "every
2073            // variant carries a context" was already false of this accessor in
2074            // 0.8.5, where it omitted `UserResponse` behind a `_ => None`
2075            // wildcard. Pin the behaviour, not the shape.
2076            if matches!(msg, InboundDelegateMsg::WakeupFired { .. }) {
2077                assert!(
2078                    msg.get_context().is_none() && msg.get_mut_context().is_none(),
2079                    "WakeupFired is documented as carrying no context; if it grew one,                      remove this exemption rather than widening it"
2080                );
2081                continue;
2082            }
2083
2084            assert!(
2085                msg.get_context().is_some(),
2086                "InboundDelegateMsg tag {tag} has a context field but get_context returned None; \
2087                 the `_ => None` wildcard hides a missing arm"
2088            );
2089            assert!(
2090                msg.get_mut_context().is_some(),
2091                "InboundDelegateMsg tag {tag} has a context field but get_mut_context returned \
2092                 None; the two accessors must agree"
2093            );
2094        }
2095    }
2096
2097    /// The same, for the outbound side.
2098    ///
2099    /// `RequestUserInput` and `ContextUpdated` genuinely have no context field
2100    /// to return, so they are the two exceptions and are named explicitly
2101    /// rather than skipped by a wildcard.
2102    #[test]
2103    fn every_outbound_variant_with_a_context_exposes_it() {
2104        for mut msg in every_outbound() {
2105            let tag = pinned_outbound_tag(&msg);
2106            let has_no_context = matches!(
2107                msg,
2108                OutboundDelegateMsg::RequestUserInput(_) | OutboundDelegateMsg::ContextUpdated(_)
2109            );
2110            if has_no_context {
2111                continue;
2112            }
2113            assert!(
2114                msg.get_context().is_some(),
2115                "OutboundDelegateMsg tag {tag} has a context field but get_context returned None"
2116            );
2117            assert!(
2118                msg.get_mut_context().is_some(),
2119                "OutboundDelegateMsg tag {tag} has a context field but get_mut_context returned \
2120                 None; the two accessors must agree"
2121            );
2122        }
2123    }
2124
2125    // ---------------------------------------------------------------------
2126    // `#[serde(other)]` — the one rule in WIRE-FORMAT.md that contradicts the
2127    // common advice, so it is the one a future reader will doubt and re-derive.
2128    // These three tests are that derivation, kept where it cannot rot.
2129    //
2130    // Mock types, deliberately: the real enums must never grow a catch-all, so
2131    // the property has to be demonstrated on stand-ins.
2132    // ---------------------------------------------------------------------
2133
2134    // The appended variants sit at tag 2, and `OldMsgWithCatchAll` declares
2135    // only 0 and 1. That gap is load-bearing: at tag 1 the catch-all's own
2136    // declared index, a plain unit variant decodes identically and the
2137    // attribute does no work at all — so mocks aligned that way pass with
2138    // `#[serde(other)]` deleted, testing nothing. Verified: they did.
2139    //
2140    // Both cases occur on a real append. The FIRST new variant lands exactly at
2141    // the catch-all's index, where the attribute is unnecessary; the SECOND is
2142    // out of range, where it is the only thing between a hard error and silent
2143    // corruption. The out-of-range case is the one the rule depends on, so it
2144    // is the one the mocks must produce.
2145    #[derive(Serialize, Deserialize, Debug, PartialEq)]
2146    enum NewMsgWithPayload {
2147        First(u32),
2148        Second(bool),
2149        Appended(String),
2150    }
2151
2152    #[derive(Serialize, Deserialize, Debug, PartialEq)]
2153    enum OldMsgWithCatchAll {
2154        First(u32),
2155        // Deliberately stops here: real variants 0 only, catch-all at 1. The
2156        // appended variants above are at tag 2, which is OUT OF RANGE for this
2157        // enum — that gap is what the attribute has to bridge.
2158        #[serde(other)]
2159        Unknown,
2160    }
2161
2162    #[derive(Serialize, Deserialize, Debug, PartialEq)]
2163    enum NewMsgUnitAppended {
2164        First(u32),
2165        Second(bool),
2166        AppendedUnit,
2167    }
2168
2169    /// The mocks' tag gap is asserted, not merely commented — and asserted
2170    /// against **the two enums whose alignment actually matters**.
2171    ///
2172    /// The vacuity condition is precisely: the tag `Appended` encodes to is the
2173    /// same as the index `OldMsgWithCatchAll` absorbs into `Unknown`. At that
2174    /// index a plain unit variant behaves identically and `#[serde(other)]`
2175    /// does no work, so the three tests below stop testing the attribute while
2176    /// still passing.
2177    ///
2178    /// Both numbers are measured from the types rather than written down, so
2179    /// this fires whichever side moves — adding a variant to the old enum, or
2180    /// removing the filler from the new ones. An earlier version of this guard
2181    /// compared against a separate no-attribute copy of the old enum and
2182    /// **missed the first case entirely**, because that copy did not move when
2183    /// the real one did. A control that can drift from what it controls is not
2184    /// a control.
2185    ///
2186    /// This exists because the alignment has broken **three times** in this
2187    /// file, twice at the hands of someone actively fixing it. A comment cannot
2188    /// catch the fourth.
2189    #[test]
2190    fn the_attribute_is_what_bridges_the_gap() {
2191        fn tag_of(bytes: &[u8]) -> u32 {
2192            u32::from_le_bytes(
2193                bytes[..4]
2194                    .try_into()
2195                    .expect("a bincode enum tag is 4 bytes"),
2196            )
2197        }
2198
2199        let appended =
2200            tag_of(&bincode::serialize(&NewMsgWithPayload::Appended("x".into())).unwrap());
2201
2202        // The lowest tag `OldMsgWithCatchAll` absorbs into `Unknown` is its
2203        // catch-all index; below it, real variants decode as themselves.
2204        let absorbed_from = (0u32..16)
2205            .find(|t| {
2206                let mut probe = t.to_le_bytes().to_vec();
2207                probe.extend_from_slice(&[0u8; 32]);
2208                matches!(
2209                    bincode::deserialize::<OldMsgWithCatchAll>(&probe),
2210                    Ok(OldMsgWithCatchAll::Unknown)
2211                )
2212            })
2213            .expect("OldMsgWithCatchAll must absorb some tag; it has #[serde(other)]");
2214
2215        assert!(
2216            appended > absorbed_from,
2217            "`Appended` is at tag {appended} and OldMsgWithCatchAll absorbs from tag \
2218             {absorbed_from}: the mocks have re-aligned, so the serde(other) tests below \
2219             are vacuous and pass with the attribute deleted. Move `Appended` above the \
2220             catch-all index again rather than adjusting this test."
2221        );
2222    }
2223
2224    /// Contradicts the usual "self-describing formats only" claim: bincode 1.x
2225    /// **does** let `#[serde(other)]` absorb an unknown variant tag.
2226    ///
2227    /// That is the trap, not a feature — see the next test for why.
2228    #[test]
2229    fn serde_other_does_absorb_an_unknown_tag_in_bincode() {
2230        let encoded = bincode::serialize(&NewMsgWithPayload::Appended("x".into())).unwrap();
2231        let decoded: OldMsgWithCatchAll =
2232            bincode::deserialize(&encoded).expect("serde(other) absorbs the unknown tag");
2233        assert_eq!(decoded, OldMsgWithCatchAll::Unknown);
2234    }
2235
2236    /// The absorption consumes the **tag only**, never the unknown variant's
2237    /// payload, so everything after it in the buffer is silently misread.
2238    ///
2239    /// A hard decode error would have been strictly better: this turns a loud,
2240    /// immediate failure into a wrong value with no error anywhere.
2241    #[test]
2242    fn the_catch_all_silently_corrupts_trailing_data() {
2243        let encoded =
2244            bincode::serialize(&(NewMsgWithPayload::Appended("hello-future".into()), 4242u32))
2245                .unwrap();
2246
2247        let (variant, trailing): (OldMsgWithCatchAll, u32) =
2248            bincode::deserialize(&encoded).expect("decodes, which is the problem");
2249
2250        assert_eq!(variant, OldMsgWithCatchAll::Unknown);
2251        assert_ne!(
2252            trailing, 4242,
2253            "if this ever equals 4242, serde(other) stopped eating the payload \
2254             and this section of WIRE-FORMAT.md needs revisiting"
2255        );
2256    }
2257
2258    /// And the reason the trap works: against a **unit** unknown variant there
2259    /// is no payload to leave behind, nothing after it is misread, and the
2260    /// decode really is clean.
2261    ///
2262    /// So a developer who tries `#[serde(other)]` on a unit variant sees it
2263    /// work and concludes the warning is overstated. The corruption is
2264    /// conditional on a property of a variant that does not exist yet — you are
2265    /// betting nobody ever gives a future variant a field.
2266    #[test]
2267    fn the_catch_all_is_clean_for_a_unit_variant() {
2268        let encoded = bincode::serialize(&(NewMsgUnitAppended::AppendedUnit, 4242u32)).unwrap();
2269
2270        let (variant, trailing): (OldMsgWithCatchAll, u32) =
2271            bincode::deserialize(&encoded).expect("unit variant leaves nothing behind");
2272
2273        assert_eq!(variant, OldMsgWithCatchAll::Unknown);
2274        assert_eq!(
2275            trailing, 4242,
2276            "a unit unknown variant must NOT corrupt what follows — this is the \
2277             case that misleads, and it is why the rule is unconditional"
2278        );
2279    }
2280}