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
use super::{
    events::EventType,
    subscription::{
        single::{OverallSubscription, UtxosChangedSubscription, VirtualChainChangedSubscription},
        Single,
    },
};
use std::fmt::{Debug, Display};

pub trait Notification: Clone + Debug + Display + Send + Sync + 'static {
    fn apply_overall_subscription(&self, subscription: &OverallSubscription) -> Option<Self>;

    fn apply_virtual_chain_changed_subscription(&self, subscription: &VirtualChainChangedSubscription) -> Option<Self>;

    fn apply_utxos_changed_subscription(&self, subscription: &UtxosChangedSubscription) -> Option<Self>;

    fn apply_subscription(&self, subscription: &dyn Single) -> Option<Self> {
        match subscription.event_type() {
            EventType::VirtualChainChanged => self.apply_virtual_chain_changed_subscription(
                subscription.as_any().downcast_ref::<VirtualChainChangedSubscription>().unwrap(),
            ),
            EventType::UtxosChanged => {
                self.apply_utxos_changed_subscription(subscription.as_any().downcast_ref::<UtxosChangedSubscription>().unwrap())
            }
            _ => self.apply_overall_subscription(subscription.as_any().downcast_ref::<OverallSubscription>().unwrap()),
        }
    }

    fn event_type(&self) -> EventType;
}

#[macro_export]
macro_rules! full_featured {
    ($(#[$meta:meta])* $vis:vis enum $name:ident {
    $($(#[$variant_meta:meta])* $variant_name:ident($field_name:path),)*
    }) => {
        paste::paste! {
        $(#[$meta])*
        $vis enum $name {
            $($(#[$variant_meta])* $variant_name($field_name)),*
        }

        impl std::convert::From<&$name> for kaspa_notify::events::EventType {
            fn from(value: &$name) -> Self {
                match value {
                    $($name::$variant_name(_) => kaspa_notify::events::EventType::$variant_name),*
                }
            }
        }

        impl std::convert::From<&$name> for kaspa_notify::scope::Scope {
            fn from(value: &$name) -> Self {
                match value {
                    $($name::$variant_name(_) => kaspa_notify::scope::Scope::$variant_name(kaspa_notify::scope::[<$variant_name Scope>]::default())),*
                }
            }
        }

        impl AsRef<$name> for $name {
            fn as_ref(&self) -> &Self {
                self
            }
        }
    }
    }
}

pub use full_featured;

pub mod test_helpers {
    use super::*;
    use derive_more::Display;
    use kaspa_addresses::Address;
    use kaspa_core::trace;
    use std::sync::Arc;

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    pub struct BlockAddedNotification {
        pub data: u64,
    }

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    pub struct VirtualChainChangedNotification {
        pub data: u64,
        pub accepted_transaction_ids: Option<u64>,
    }

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    pub struct UtxosChangedNotification {
        pub data: u64,
        pub addresses: Arc<Vec<Address>>,
    }

    full_featured! {
    #[derive(Clone, Debug, Display, PartialEq, Eq)]
    pub enum TestNotification {
        #[display(fmt = "BlockAdded #{}", "_0.data")]
        BlockAdded(BlockAddedNotification),
        #[display(fmt = "VirtualChainChanged #{}", "_0.data")]
        VirtualChainChanged(VirtualChainChangedNotification),
        #[display(fmt = "UtxosChanged #{}", "_0.data")]
        UtxosChanged(UtxosChangedNotification),
    }
    }

    impl Notification for TestNotification {
        fn apply_overall_subscription(&self, subscription: &OverallSubscription) -> Option<Self> {
            trace!("apply_overall_subscription: {self:?}, {subscription:?}");
            match subscription.active() {
                true => Some(self.clone()),
                false => None,
            }
        }

        fn apply_virtual_chain_changed_subscription(&self, subscription: &VirtualChainChangedSubscription) -> Option<Self> {
            match subscription.active() {
                true => {
                    if let TestNotification::VirtualChainChanged(ref payload) = self {
                        if !subscription.include_accepted_transaction_ids() && payload.accepted_transaction_ids.is_some() {
                            return Some(TestNotification::VirtualChainChanged(VirtualChainChangedNotification {
                                data: payload.data,
                                accepted_transaction_ids: None,
                            }));
                        }
                    }
                    Some(self.clone())
                }
                false => None,
            }
        }

        fn apply_utxos_changed_subscription(&self, subscription: &UtxosChangedSubscription) -> Option<Self> {
            match subscription.active() {
                true => {
                    if let TestNotification::UtxosChanged(ref payload) = self {
                        if !subscription.to_all() {
                            let addresses = payload
                                .addresses
                                .iter()
                                .filter_map(|x| if subscription.addresses().contains(x) { Some((*x).clone()) } else { None })
                                .collect::<Vec<_>>();
                            if !addresses.is_empty() {
                                return Some(TestNotification::UtxosChanged(UtxosChangedNotification {
                                    data: payload.data,
                                    addresses: Arc::new(addresses),
                                }));
                            } else {
                                return None;
                            }
                        }
                    }
                    Some(self.clone())
                }
                false => None,
            }
        }

        fn event_type(&self) -> EventType {
            self.into()
        }
    }

    /// A trait to help tests match notification received and expected thanks to some predefined data
    pub trait Data {
        fn data(&self) -> u64;
        fn data_mut(&mut self) -> &mut u64;
    }
    impl Data for BlockAddedNotification {
        fn data(&self) -> u64 {
            self.data
        }

        fn data_mut(&mut self) -> &mut u64 {
            &mut self.data
        }
    }
    impl Data for VirtualChainChangedNotification {
        fn data(&self) -> u64 {
            self.data
        }

        fn data_mut(&mut self) -> &mut u64 {
            &mut self.data
        }
    }
    impl Data for UtxosChangedNotification {
        fn data(&self) -> u64 {
            self.data
        }

        fn data_mut(&mut self) -> &mut u64 {
            &mut self.data
        }
    }
    impl Data for TestNotification {
        fn data(&self) -> u64 {
            match self {
                TestNotification::BlockAdded(n) => n.data(),
                TestNotification::VirtualChainChanged(n) => n.data(),
                TestNotification::UtxosChanged(n) => n.data(),
            }
        }

        fn data_mut(&mut self) -> &mut u64 {
            match self {
                TestNotification::BlockAdded(n) => n.data_mut(),
                TestNotification::VirtualChainChanged(n) => n.data_mut(),
                TestNotification::UtxosChanged(n) => n.data_mut(),
            }
        }
    }
}