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
use async_trait::async_trait;
use tokio::sync::RwLock;

use crate::chain_observer::interface::*;
use crate::chain_observer::{ChainAddress, TxDatum};
use crate::crypto_helper::{KESPeriod, OpCert};
use crate::{entities::*, test_utils::fake_data};

/// A Fake [ChainObserver] for testing purpose using fixed data.
pub struct FakeObserver {
    /// A list of [SignerWithStake], used for [get_current_stake_distribution].
    ///
    /// [get_current_stake_distribution]: ChainObserver::get_current_stake_distribution
    pub signers: RwLock<Vec<SignerWithStake>>,

    /// A [TimePoint], used by [get_current_epoch]
    ///
    /// [get_current_epoch]: ChainObserver::get_current_epoch
    pub current_time_point: RwLock<Option<TimePoint>>,

    /// A list of [TxDatum], used by [get_current_datums]
    ///
    /// [get_current_datums]: ChainObserver::get_current_datums
    pub datums: RwLock<Vec<TxDatum>>,

    /// A Cardano era, used by [get_current_era]
    ///
    /// [get_current_era]: ChainObserver::get_current_era
    pub current_era: RwLock<String>,
}

impl FakeObserver {
    /// FakeObserver factory
    pub fn new(current_time_point: Option<TimePoint>) -> Self {
        Self {
            signers: RwLock::new(vec![]),
            current_time_point: RwLock::new(current_time_point.clone()),
            datums: RwLock::new(vec![]),
            current_era: RwLock::new(String::new()),
        }
    }

    /// Increase by one the epoch of the [current_time_point][`FakeObserver::current_time_point`].
    pub async fn next_epoch(&self) -> Option<Epoch> {
        let mut current_time_point = self.current_time_point.write().await;
        *current_time_point = current_time_point.as_ref().map(|time_point| TimePoint {
            epoch: time_point.epoch + 1,
            ..time_point.clone()
        });

        current_time_point.as_ref().map(|b| b.epoch)
    }

    /// Increase the block number of the [current_time_point][`FakeObserver::current_time_point`] by
    /// the given increment.
    pub async fn increase_block_number(&self, increment: u64) -> Option<BlockNumber> {
        self.change_block_number(|actual_block_number| actual_block_number + increment)
            .await
    }

    /// Decrease the block number of the [current_time_point][`FakeObserver::current_time_point`] by
    /// the given decrement.
    pub async fn decrease_block_number(&self, decrement: u64) -> Option<BlockNumber> {
        self.change_block_number(|actual_block_number| actual_block_number - decrement)
            .await
    }

    async fn change_block_number(
        &self,
        change_to_apply: impl Fn(BlockNumber) -> BlockNumber,
    ) -> Option<BlockNumber> {
        let mut current_time_point = self.current_time_point.write().await;

        *current_time_point = current_time_point.as_ref().map(|time_point| TimePoint {
            chain_point: ChainPoint {
                block_number: change_to_apply(time_point.chain_point.block_number),
                ..time_point.chain_point.clone()
            },
            ..time_point.clone()
        });

        current_time_point
            .as_ref()
            .map(|b| b.chain_point.block_number)
    }

    /// Increase the slot number of the [current_time_point][`FakeObserver::current_time_point`] by
    /// the given increment.
    pub async fn increase_slot_number(&self, increment: u64) -> Option<SlotNumber> {
        self.change_slot_number(|actual_slot_number| actual_slot_number + increment)
            .await
    }

    /// Decrease the slot number of the [current_time_point][`FakeObserver::current_time_point`] by
    /// the given decrement.
    pub async fn decrease_slot_number(&self, decrement: u64) -> Option<SlotNumber> {
        self.change_slot_number(|actual_slot_number| actual_slot_number - decrement)
            .await
    }

    async fn change_slot_number(
        &self,
        change_to_apply: impl Fn(SlotNumber) -> SlotNumber,
    ) -> Option<SlotNumber> {
        let mut current_time_point = self.current_time_point.write().await;

        *current_time_point = current_time_point.as_ref().map(|time_point| TimePoint {
            chain_point: ChainPoint {
                slot_number: change_to_apply(time_point.chain_point.slot_number),
                ..time_point.chain_point.clone()
            },
            ..time_point.clone()
        });

        current_time_point
            .as_ref()
            .map(|b| b.chain_point.slot_number)
    }

    /// Set the signers that will use to compute the result of
    /// [get_current_stake_distribution][ChainObserver::get_current_stake_distribution].
    pub async fn set_signers(&self, new_signers: Vec<SignerWithStake>) {
        let mut signers = self.signers.write().await;
        *signers = new_signers;
    }

    /// Set the time point
    pub async fn set_current_time_point(&self, new_current_time_point: Option<TimePoint>) {
        let mut current_time_point = self.current_time_point.write().await;
        *current_time_point = new_current_time_point;
    }

    /// Set the datums that will use to compute the result of
    /// [get_current_datums][ChainObserver::get_current_datums].
    pub async fn set_datums(&self, new_datums: Vec<TxDatum>) {
        let mut datums = self.datums.write().await;
        *datums = new_datums;
    }

    /// Set the current Era
    /// [get_current_era][ChainObserver::get_current_era].
    pub async fn set_current_era(&self, new_current_era: String) {
        let mut current_era = self.current_era.write().await;
        *current_era = new_current_era;
    }
}

impl Default for FakeObserver {
    fn default() -> Self {
        let mut observer = Self::new(Some(TimePoint::dummy()));
        observer.signers = RwLock::new(fake_data::signers_with_stakes(2));

        observer
    }
}

#[async_trait]
impl ChainObserver for FakeObserver {
    async fn get_current_datums(
        &self,
        _address: &ChainAddress,
    ) -> Result<Vec<TxDatum>, ChainObserverError> {
        let datums = self.datums.read().await;
        Ok(datums.to_vec())
    }

    async fn get_current_era(&self) -> Result<Option<String>, ChainObserverError> {
        Ok(Some(self.current_era.read().await.clone()))
    }

    async fn get_current_epoch(&self) -> Result<Option<Epoch>, ChainObserverError> {
        Ok(self
            .current_time_point
            .read()
            .await
            .as_ref()
            .map(|time_point| time_point.epoch))
    }

    async fn get_current_chain_point(&self) -> Result<Option<ChainPoint>, ChainObserverError> {
        Ok(self
            .current_time_point
            .read()
            .await
            .as_ref()
            .map(|time_point| time_point.chain_point.clone()))
    }

    async fn get_current_stake_distribution(
        &self,
    ) -> Result<Option<StakeDistribution>, ChainObserverError> {
        Ok(Some(
            self.signers
                .read()
                .await
                .iter()
                .map(|signer| (signer.party_id.clone() as PartyId, signer.stake as Stake))
                .collect::<StakeDistribution>(),
        ))
    }

    async fn get_current_kes_period(
        &self,
        _opcert: &OpCert,
    ) -> Result<Option<KESPeriod>, ChainObserverError> {
        Ok(Some(0))
    }
}

#[cfg(test)]
mod tests {
    use crate::test_utils::fake_data;

    use super::*;

    #[tokio::test]
    async fn test_get_current_epoch() {
        let time_point = TimePoint::dummy();
        let fake_observer = FakeObserver::new(Some(time_point.clone()));
        let current_epoch = fake_observer.get_current_epoch().await.unwrap();

        assert_eq!(Some(time_point.epoch), current_epoch);
    }

    #[tokio::test]
    async fn test_get_current_chain_point() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_current_time_point(Some(TimePoint::dummy()))
            .await;
        let chain_point = fake_observer.get_current_chain_point().await.unwrap();

        assert_eq!(
            Some(TimePoint::dummy().chain_point),
            chain_point,
            "get current chain point should not fail"
        );
    }

    #[tokio::test]
    async fn test_get_current_stake_distribution() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_signers(fake_data::signers_with_stakes(2))
            .await;
        let stake_distribution = fake_observer.get_current_stake_distribution().await;

        assert_eq!(
            2,
            stake_distribution.unwrap().unwrap().len(),
            "get current stake distribution should not fail and should not be empty"
        );
    }

    #[tokio::test]
    async fn test_get_current_datums() {
        let fake_address = "addr_test_123456".to_string();
        let fake_datums = vec![
            TxDatum("tx_datum_1".to_string()),
            TxDatum("tx_datum_2".to_string()),
        ];
        let fake_observer = FakeObserver::new(None);
        fake_observer.set_datums(fake_datums.clone()).await;
        let datums = fake_observer
            .get_current_datums(&fake_address)
            .await
            .expect("get_current_datums should not fail");

        assert_eq!(fake_datums, datums);
    }

    #[tokio::test]
    async fn test_increase_block_number() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_current_time_point(Some(TimePoint::dummy()))
            .await;
        fake_observer.increase_block_number(375).await;

        let chain_point = fake_observer.get_current_chain_point().await.unwrap();
        assert_eq!(
            Some(ChainPoint {
                block_number: TimePoint::dummy().chain_point.block_number + 375,
                ..TimePoint::dummy().chain_point
            }),
            chain_point,
            "get current chain point should not fail"
        );
    }

    #[tokio::test]
    async fn test_decrease_block_number() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_current_time_point(Some(TimePoint {
                chain_point: ChainPoint {
                    block_number: BlockNumber(1000),
                    ..TimePoint::dummy().chain_point
                },
                ..TimePoint::dummy()
            }))
            .await;
        fake_observer.decrease_block_number(800).await;

        let chain_point = fake_observer.get_current_chain_point().await.unwrap();
        assert_eq!(
            Some(ChainPoint {
                block_number: BlockNumber(200),
                ..TimePoint::dummy().chain_point
            }),
            chain_point,
            "get current chain point should not fail"
        );
    }

    #[tokio::test]
    async fn test_increase_slot_number() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_current_time_point(Some(TimePoint::dummy()))
            .await;
        fake_observer.increase_slot_number(375).await;

        let chain_point = fake_observer.get_current_chain_point().await.unwrap();
        assert_eq!(
            Some(ChainPoint {
                slot_number: TimePoint::dummy().chain_point.slot_number + 375,
                ..TimePoint::dummy().chain_point
            }),
            chain_point,
            "get current chain point should not fail"
        );
    }

    #[tokio::test]
    async fn test_decrease_slot_number() {
        let fake_observer = FakeObserver::new(None);
        fake_observer
            .set_current_time_point(Some(TimePoint {
                chain_point: ChainPoint {
                    slot_number: SlotNumber(1000),
                    ..TimePoint::dummy().chain_point
                },
                ..TimePoint::dummy()
            }))
            .await;
        fake_observer.decrease_slot_number(800).await;

        let chain_point = fake_observer.get_current_chain_point().await.unwrap();
        assert_eq!(
            Some(ChainPoint {
                slot_number: SlotNumber(200),
                ..TimePoint::dummy().chain_point
            }),
            chain_point,
            "get current chain point should not fail"
        );
    }

    #[tokio::test]
    async fn test_get_current_era() {
        let fake_observer = FakeObserver::new(None);

        let current_era = fake_observer
            .get_current_era()
            .await
            .expect("get_current_era should not fail");
        assert_ne!(Some("Conway".to_string()), current_era);

        fake_observer.set_current_era("Conway".to_string()).await;
        let current_era = fake_observer
            .get_current_era()
            .await
            .expect("get_current_era should not fail");
        assert_eq!(Some("Conway".to_string()), current_era);
    }
}