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