aleph-types 0.9.1

Definitions for the most commonly used types in the Aleph Cloud network.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use crate::chain::{Address, Chain, Signature};
use crate::channel::Channel;
use crate::item_hash::{AlephItemHash, ItemHash};
use crate::message::aggregate::AggregateContent;
use crate::message::forget::ForgetContent;
use crate::message::instance::InstanceContent;
use crate::message::post::PostContent;
use crate::message::program::ProgramContent;
use crate::message::store::StoreContent;
use crate::timestamp::Timestamp;
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use std::fmt::Formatter;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum MessageVerificationError {
    #[error("Item hash verification failed: expected {expected}, got {actual}")]
    ItemHashVerificationFailed {
        expected: ItemHash,
        actual: ItemHash,
    },
    #[error("Cannot verify non-inline message locally; use the client to verify via /storage/raw/")]
    NonInlineMessage,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MessageType {
    Aggregate,
    Forget,
    Instance,
    Post,
    Program,
    Store,
}

impl std::fmt::Display for MessageType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            MessageType::Aggregate => "AGGREGATE",
            MessageType::Forget => "FORGET",
            MessageType::Instance => "INSTANCE",
            MessageType::Post => "POST",
            MessageType::Program => "PROGRAM",
            MessageType::Store => "STORE",
        };

        f.write_str(s)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageStatus {
    Pending,
    Processed,
    Removing,
    Removed,
    Forgotten,
    Rejected,
}

impl std::fmt::Display for MessageStatus {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            MessageStatus::Pending => "pending",
            MessageStatus::Processed => "processed",
            MessageStatus::Removing => "removing",
            MessageStatus::Removed => "removed",
            MessageStatus::Forgotten => "forgotten",
            MessageStatus::Rejected => "rejected",
        };

        f.write_str(s)
    }
}

/// Content variants for different message types.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContentEnum {
    Aggregate(AggregateContent),
    Forget(ForgetContent),
    Instance(InstanceContent),
    Post(PostContent),
    Program(ProgramContent),
    Store(StoreContent),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MessageContent {
    pub address: Address,
    pub time: Timestamp,
    #[serde(flatten)]
    pub content: MessageContentEnum,
}

impl MessageContent {
    /// Deserializes message content from raw JSON bytes, using `message_type` to select
    /// the correct content variant. This is the type-directed deserialization used by
    /// the verified message path.
    pub fn deserialize_with_type(
        message_type: MessageType,
        raw: &[u8],
    ) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_slice(raw)?;
        Self::from_json_value(message_type, &value)
    }

    fn from_json_value(
        message_type: MessageType,
        value: &serde_json::Value,
    ) -> Result<Self, serde_json::Error> {
        let address = Address::deserialize(&value["address"])?;
        let time = Timestamp::deserialize(&value["time"])?;

        let variant = match message_type {
            MessageType::Aggregate => {
                MessageContentEnum::Aggregate(AggregateContent::deserialize(value)?)
            }
            MessageType::Forget => MessageContentEnum::Forget(ForgetContent::deserialize(value)?),
            MessageType::Instance => {
                MessageContentEnum::Instance(InstanceContent::deserialize(value)?)
            }
            MessageType::Post => MessageContentEnum::Post(PostContent::deserialize(value)?),
            MessageType::Program => {
                MessageContentEnum::Program(ProgramContent::deserialize(value)?)
            }
            MessageType::Store => MessageContentEnum::Store(StoreContent::deserialize(value)?),
        };

        Ok(MessageContent {
            address,
            time,
            content: variant,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MessageConfirmation {
    pub chain: Chain,
    pub height: u64,
    pub hash: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time: Option<Timestamp>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<Address>,
}

/// Where to find the content of the message. Note that this is a mix of ItemType / ItemContent
/// if you are used to the Python SDK.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ContentSource {
    Inline { item_content: String },
    Storage,
    Ipfs,
}

impl<'de> Deserialize<'de> for ContentSource {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct ContentSourceRaw {
            item_type: String,
            item_content: Option<String>,
        }

        let raw = ContentSourceRaw::deserialize(deserializer)?;

        match raw.item_type.as_str() {
            "inline" => {
                let item_content = raw
                    .item_content
                    .ok_or_else(|| de::Error::missing_field("item_content"))?;
                Ok(ContentSource::Inline { item_content })
            }
            "storage" => Ok(ContentSource::Storage),
            "ipfs" => Ok(ContentSource::Ipfs),
            other => Err(de::Error::unknown_variant(
                other,
                &["inline", "storage", "ipfs"],
            )),
        }
    }
}

impl ContentSource {
    /// For inline messages, verifies that `item_content` hashes to `expected_hash`.
    ///
    /// Returns `Some(Ok(()))` if the hash matches, `Some(Err((expected, actual)))` on mismatch,
    /// or `None` for non-inline messages (which require network-based verification).
    pub fn verify_inline_hash(
        &self,
        expected_hash: &ItemHash,
    ) -> Option<Result<(), (ItemHash, ItemHash)>> {
        match self {
            ContentSource::Inline { item_content } => {
                let computed = AlephItemHash::from_bytes(item_content.as_bytes());
                if ItemHash::Native(computed) != *expected_hash {
                    Some(Err((expected_hash.clone(), computed.into())))
                } else {
                    Some(Ok(()))
                }
            }
            ContentSource::Storage | ContentSource::Ipfs => None,
        }
    }
}

/// A message without its deserialized content.
///
/// Used by the verified message path: the client fetches message headers, then downloads
/// and verifies raw content separately before deserializing it. This avoids trusting
/// the CCN's pre-deserialized `content` field.
#[derive(PartialEq, Debug, Clone)]
pub struct MessageHeader {
    /// Blockchain used for this message.
    pub chain: Chain,
    /// Sender address.
    pub sender: Address,
    /// Cryptographic signature of the message by the sender.
    pub signature: Signature,
    /// Content of the message as created by the sender. Can either be inline or stored
    /// on Aleph Cloud.
    pub content_source: ContentSource,
    /// Hash of the content (SHA2-256).
    pub item_hash: ItemHash,
    /// List of confirmations for the message.
    pub confirmations: Vec<MessageConfirmation>,
    /// Unix timestamp or datetime when the message was published.
    pub time: Timestamp,
    /// Channel of the message, one application ideally has one channel.
    pub channel: Option<Channel>,
    /// Message type. (aggregate, forget, instance, post, program, store).
    pub message_type: MessageType,
}

impl MessageHeader {
    /// Assembles a full [`Message`] by combining this header with deserialized content.
    pub fn with_content(self, content: MessageContent) -> Message {
        Message {
            chain: self.chain,
            sender: self.sender,
            signature: self.signature,
            content_source: self.content_source,
            item_hash: self.item_hash,
            confirmations: self.confirmations,
            time: self.time,
            channel: self.channel,
            message_type: self.message_type,
            content,
        }
    }

    /// Verifies that the message signature was produced by the sender.
    ///
    /// Signature verification only depends on header fields (chain, sender,
    /// signature, message_type, item_hash), so it can run before content is
    /// downloaded or deserialized.
    #[cfg(any(feature = "signature-evm", feature = "signature-sol"))]
    pub fn verify_signature(
        &self,
    ) -> Result<(), crate::verify_signature::SignatureVerificationError> {
        crate::verify_signature::verify(
            &self.chain,
            &self.sender,
            &self.signature,
            self.message_type,
            &self.item_hash,
        )
    }
}

impl From<Message> for MessageHeader {
    fn from(message: Message) -> Self {
        MessageHeader {
            chain: message.chain,
            sender: message.sender,
            signature: message.signature,
            content_source: message.content_source,
            item_hash: message.item_hash,
            confirmations: message.confirmations,
            time: message.time,
            channel: message.channel,
            message_type: message.message_type,
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub struct Message {
    /// Blockchain used for this message.
    pub chain: Chain,
    /// Sender address.
    pub sender: Address,
    /// Cryptographic signature of the message by the sender.
    pub signature: Signature,
    /// Content of the message as created by the sender. Can either be inline or stored
    /// on Aleph Cloud.
    pub content_source: ContentSource,
    /// Hash of the content (SHA2-256).
    pub item_hash: ItemHash,
    /// List of confirmations for the message.
    pub confirmations: Vec<MessageConfirmation>,
    /// Unix timestamp or datetime when the message was published.
    pub time: Timestamp,
    /// Channel of the message, one application ideally has one channel.
    pub channel: Option<Channel>,
    /// Message type. (aggregate, forget, instance, post, program, store).
    pub message_type: MessageType,
    /// Message content.
    pub content: MessageContent,
}

impl Message {
    pub fn content(&self) -> &MessageContentEnum {
        &self.content.content
    }

    pub fn confirmed(&self) -> bool {
        !self.confirmations.is_empty()
    }

    /// Returns the address of the sender of the message. Note that the sender is not necessarily
    /// the owner of the resources, as the owner may have delegated their authority to create
    /// specific resources through the permission system.
    pub fn sender(&self) -> &Address {
        &self.sender
    }

    /// Returns the address of the owner of the resources.
    pub fn owner(&self) -> &Address {
        &self.content.address
    }

    /// Returns the time at which the message was sent.
    /// Notes:
    /// * This value is signed by the sender and should not be trusted accordingly.
    /// * We prefer `content.time` over `time` as `time` is not part of the signed payload.
    pub fn sent_at(&self) -> &Timestamp {
        &self.content.time
    }

    /// Returns the earliest confirmation time of the message.
    pub fn confirmed_at(&self) -> Option<&Timestamp> {
        self.confirmations.first().and_then(|c| c.time.as_ref())
    }

    /// Verifies that the item hash of an inline message matches its content.
    ///
    /// For inline messages, the item hash is the SHA-256 hash of the `item_content` string.
    /// For non-inline messages (storage/ipfs), use the client's `verify_message()` method
    /// instead, which downloads the raw content from `/storage/raw/` for verification.
    pub fn verify_item_hash(&self) -> Result<(), MessageVerificationError> {
        match self.content_source.verify_inline_hash(&self.item_hash) {
            Some(Ok(())) => Ok(()),
            Some(Err((expected, actual))) => {
                Err(MessageVerificationError::ItemHashVerificationFailed { expected, actual })
            }
            None => Err(MessageVerificationError::NonInlineMessage),
        }
    }

    /// Verifies that the message signature was produced by the sender.
    ///
    /// Constructs the verification buffer from the message fields, then
    /// dispatches to the chain-specific verification algorithm. Currently
    /// supports EVM-compatible chains (Ethereum, Arbitrum, etc.) and SVM
    /// chains (Solana, Eclipse).
    #[cfg(any(feature = "signature-evm", feature = "signature-sol"))]
    pub fn verify_signature(
        &self,
    ) -> Result<(), crate::verify_signature::SignatureVerificationError> {
        crate::verify_signature::verify(
            &self.chain,
            &self.sender,
            &self.signature,
            self.message_type,
            &self.item_hash,
        )
    }
}

/// Shared helper struct for deserializing message header fields.
/// Used by both `Message` and `MessageHeader` Deserialize impls.
#[derive(Deserialize)]
struct MessageHeaderRaw {
    chain: Chain,
    sender: Address,
    signature: Signature,
    #[serde(flatten)]
    content_source: ContentSource,
    item_hash: ItemHash,
    #[serde(default)]
    confirmations: Option<Vec<MessageConfirmation>>,
    time: Timestamp,
    #[serde(default)]
    channel: Option<Channel>,
    #[serde(rename = "type")]
    message_type: MessageType,
}

impl MessageHeaderRaw {
    fn into_header(self) -> MessageHeader {
        MessageHeader {
            chain: self.chain,
            sender: self.sender,
            signature: self.signature,
            content_source: self.content_source,
            item_hash: self.item_hash,
            confirmations: self.confirmations.unwrap_or_default(),
            time: self.time,
            channel: self.channel,
            message_type: self.message_type,
        }
    }
}

impl<'de> Deserialize<'de> for MessageHeader {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        MessageHeaderRaw::deserialize(deserializer).map(MessageHeaderRaw::into_header)
    }
}

// Custom deserializer that uses message_type to efficiently deserialize content
impl<'de> Deserialize<'de> for Message {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct MessageRaw {
            #[serde(flatten)]
            header: MessageHeaderRaw,
            content: serde_json::Value,
        }

        let raw = MessageRaw::deserialize(deserializer)?;

        let content = MessageContent::from_json_value(raw.header.message_type, &raw.content)
            .map_err(de::Error::custom)?;

        Ok(raw.header.into_header().with_content(content))
    }
}

// Manual Serialize for Message
impl Serialize for Message {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        let mut state = serializer.serialize_struct("Message", 9)?;
        state.serialize_field("chain", &self.chain)?;
        state.serialize_field("sender", &self.sender)?;
        match &self.content_source {
            ContentSource::Inline { item_content } => {
                state.serialize_field("item_type", "inline")?;
                state.serialize_field("item_content", item_content)?;
            }
            ContentSource::Storage => {
                state.serialize_field("item_type", "storage")?;
                state.serialize_field("item_content", &None::<String>)?;
            }
            ContentSource::Ipfs => {
                state.serialize_field("item_type", "ipfs")?;
                state.serialize_field("item_content", &None::<String>)?;
            }
        }
        state.serialize_field("signature", &self.signature)?;
        state.serialize_field("item_hash", &self.item_hash)?;
        if self.confirmed() {
            state.serialize_field("confirmed", &true)?;
            state.serialize_field("confirmations", &self.confirmations)?;
        }
        state.serialize_field("time", &self.time)?;
        if self.channel.is_some() {
            state.serialize_field("channel", &self.channel)?;
        }
        state.serialize_field("type", &self.message_type)?;
        state.serialize_field("content", &self.content)?;
        state.end()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::item_hash;
    use assert_matches::assert_matches;

    #[test]
    fn test_deserialize_item_type_inline() {
        let item_content_str = "test".to_string();
        let content_source_str =
            format!("{{\"item_type\":\"inline\",\"item_content\":\"{item_content_str}\"}}");
        let content_source: ContentSource = serde_json::from_str(&content_source_str).unwrap();

        assert_matches!(
            content_source,
            ContentSource::Inline {
                item_content
            } if item_content == item_content_str
        );
    }

    #[test]
    fn test_deserialize_item_type_storage() {
        let content_source_str = r#"{"item_type":"storage"}"#;
        let content_source: ContentSource = serde_json::from_str(content_source_str).unwrap();
        assert_matches!(content_source, ContentSource::Storage);
    }

    #[test]
    fn test_deserialize_item_type_ipfs() {
        let content_source_str = r#"{"item_type":"ipfs"}"#;
        let content_source: ContentSource = serde_json::from_str(content_source_str).unwrap();
        assert_matches!(content_source, ContentSource::Ipfs);
    }

    #[test]
    fn test_verify_inline_message_item_hash() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let message: Message = serde_json::from_str(json).unwrap();
        message.verify_item_hash().unwrap();

        // STORE message envelope is inline; only the referenced file lives on IPFS.
        let json = include_str!("../../../../fixtures/messages/store/store-ipfs.json");
        let message: Message = serde_json::from_str(json).unwrap();
        message.verify_item_hash().unwrap();
    }

    #[test]
    fn test_verify_inline_message_detects_tampered_hash() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let mut message: Message = serde_json::from_str(json).unwrap();
        message.item_hash =
            item_hash!("0000000000000000000000000000000000000000000000000000000000000000");
        assert_matches!(
            message.verify_item_hash(),
            Err(MessageVerificationError::ItemHashVerificationFailed { .. })
        );
    }

    #[test]
    fn test_verify_inline_message_detects_tampered_content() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let mut message: Message = serde_json::from_str(json).unwrap();
        // Corrupt the item_content while keeping the original item_hash
        if let ContentSource::Inline {
            ref mut item_content,
        } = message.content_source
        {
            item_content.push('!');
        }
        assert_matches!(
            message.verify_item_hash(),
            Err(MessageVerificationError::ItemHashVerificationFailed { .. })
        );
    }

    #[test]
    fn test_verify_non_inline_message_returns_error() {
        let json = include_str!("../../../../fixtures/messages/aggregate/aggregate.json");
        let message: Message = serde_json::from_str(json).unwrap();
        assert_matches!(
            message.verify_item_hash(),
            Err(MessageVerificationError::NonInlineMessage)
        );
    }

    #[test]
    fn test_deserialize_message_header() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let header: MessageHeader = serde_json::from_str(json).unwrap();
        let message: Message = serde_json::from_str(json).unwrap();

        // Header fields should match Message fields
        assert_eq!(header.chain, message.chain);
        assert_eq!(header.sender, message.sender);
        assert_eq!(header.signature, message.signature);
        assert_eq!(header.content_source, message.content_source);
        assert_eq!(header.item_hash, message.item_hash);
        assert_eq!(header.time, message.time);
        assert_eq!(header.channel, message.channel);
        assert_eq!(header.message_type, message.message_type);
    }

    #[test]
    fn test_message_header_with_content_roundtrip() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let message: Message = serde_json::from_str(json).unwrap();

        // Convert to header, then reassemble with original content
        let content = message.content.clone();
        let header = MessageHeader::from(message.clone());
        let reassembled = header.with_content(content);
        assert_eq!(reassembled, message);
    }

    #[test]
    fn test_deserialize_content_with_type() {
        let json = include_str!("../../../../fixtures/messages/post/post.json");
        let message: Message = serde_json::from_str(json).unwrap();

        // For inline messages, deserialize_with_type from item_content should match
        if let ContentSource::Inline { ref item_content } = message.content_source {
            let content = MessageContent::deserialize_with_type(
                message.message_type,
                item_content.as_bytes(),
            )
            .unwrap();
            assert_eq!(content, message.content);
        } else {
            panic!("Expected inline message");
        }
    }

    #[test]
    fn test_deserialize_item_type_invalid_type() {
        let content_source_str = r#"{"item_type":"invalid"}"#;
        let result = serde_json::from_str::<ContentSource>(content_source_str);
        assert!(result.is_err());
    }

    #[test]
    fn test_deserialize_item_type_invalid_format() {
        let content_source_str = r#"{"type":"inline"}"#;
        let result = serde_json::from_str::<ContentSource>(content_source_str);
        assert!(result.is_err());
    }

    #[cfg(any(feature = "signature-evm", feature = "signature-sol"))]
    mod signature_tests {
        use super::*;
        use crate::verify_signature::SignatureVerificationError;

        #[test]
        fn test_verify_signature_unsupported_chain() {
            let json = include_str!("../../../../fixtures/messages/post/post.json");
            let mut message: Message = serde_json::from_str(json).unwrap();
            message.chain = Chain::Tezos;
            assert_matches!(
                message.verify_signature(),
                Err(SignatureVerificationError::UnsupportedChain(_))
            );
        }

        #[cfg(feature = "signature-evm")]
        mod evm {
            use super::*;
            use crate::chain::Signature;

            fn post_message() -> Message {
                let json = include_str!("../../../../fixtures/messages/post/post.json");
                serde_json::from_str(json).unwrap()
            }

            #[test]
            fn test_verify_signature_valid() {
                let message = post_message();
                message.verify_signature().unwrap();
            }

            #[test]
            fn test_verify_signature_tampered_sender() {
                let mut message = post_message();
                message.sender =
                    Address::from("0x0000000000000000000000000000000000000000".to_string());
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::SignatureMismatch { .. })
                );
            }

            #[test]
            fn test_verify_signature_tampered_item_hash() {
                let mut message = post_message();
                message.item_hash =
                    item_hash!("0000000000000000000000000000000000000000000000000000000000000000");
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::SignatureMismatch { .. })
                );
            }

            #[test]
            fn test_verify_signature_invalid_hex() {
                let mut message = post_message();
                message.signature = Signature::from("not-a-hex-string".to_string());
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::InvalidSignature(_))
                );
            }

            #[test]
            fn test_verify_signature_wrong_but_valid_signature() {
                let mut message = post_message();
                message.signature = Signature::from(
                    "0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001\
                     00"
                        .to_string(),
                );
                // May recover to a different address or fail to recover entirely
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::SignatureMismatch { .. }
                        | SignatureVerificationError::InvalidSignature(_))
                );
            }

            #[test]
            fn test_verify_signature_evm_chain_dispatch() {
                let mut message = post_message();
                message.chain = Chain::Arbitrum;
                // Buffer now contains "ARB" instead of "ETH", so signature won't match,
                // but the dispatch should route to the Ethereum verifier (not UnsupportedChain).
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::SignatureMismatch { .. })
                );
            }
        }

        #[cfg(feature = "signature-sol")]
        mod sol {
            use super::*;

            fn sol_post_message() -> Message {
                let json = include_str!("../../../../fixtures/messages/post/post-sol.json");
                serde_json::from_str(json).unwrap()
            }

            #[test]
            fn test_verify_sol_signature_valid() {
                let message = sol_post_message();
                message.verify_signature().unwrap();
            }

            #[test]
            fn test_verify_sol_signature_tampered_sender() {
                let mut message = sol_post_message();
                message.sender = Address::from("11111111111111111111111111111111".to_string());
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::InvalidSignature(_))
                );
            }

            #[test]
            fn test_verify_sol_signature_tampered_item_hash() {
                let mut message = sol_post_message();
                message.item_hash =
                    item_hash!("0000000000000000000000000000000000000000000000000000000000000000");
                assert_matches!(
                    message.verify_signature(),
                    Err(SignatureVerificationError::InvalidSignature(_))
                );
            }

            #[test]
            fn test_deserialize_sol_signature_format() {
                let message = sol_post_message();
                assert!(message.signature.public_key().is_some());
                assert_eq!(
                    message.signature.public_key().unwrap(),
                    "5SwCeHbZ9oY3556YFBEhPTHyy9t4yse26v7MUyGm2bHS"
                );
            }
        }
    }
}