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
use crate::{
    campaign::Validators, config::Config, Address, Campaign, ChainOf, UnifiedNum, ValidatorId,
};
use chrono::Utc;
use std::cmp::PartialEq;
use thiserror::Error;

pub trait Validator {
    fn validate(
        self,
        config: &Config,
        validator_identity: ValidatorId,
    ) -> Result<ChainOf<Campaign>, Error>;
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Validation {
    /// When the Adapter address is not listed in the `campaign.validators` & `campaign.channel.(leader/follower)`
    /// which in terms means, that the adapter shouldn't handle this Campaign
    AdapterNotIncluded,
    /// when `channel.active.to` has passed (i.e. < now), the Campaign should not be handled
    // campaign.active.to must be in the future
    InvalidActiveTo,
    UnlistedValidator,
    UnlistedCreator,
    UnlistedAsset,
    MinimumDepositNotMet,
    MinimumValidatorFeeNotMet,
    FeeConstraintViolated,
}

#[derive(Debug, Eq, PartialEq, Clone, Copy, Error)]
pub enum Error {
    #[error("Summing the Validators fee results in overflow")]
    FeeSumOverflow,
    #[error("Validation error: {0:?}")]
    Validation(Validation),
}

impl From<Validation> for Error {
    fn from(v: Validation) -> Self {
        Self::Validation(v)
    }
}

impl Validator for Campaign {
    fn validate(
        self,
        config: &Config,
        validator_identity: ValidatorId,
    ) -> Result<ChainOf<Campaign>, Error> {
        // check if the channel validators include our adapter identity
        let whoami_validator = match self.find_validator(&validator_identity) {
            Some(role) => role.into_inner(),
            None => return Err(Validation::AdapterNotIncluded.into()),
        };

        if self.active.to < Utc::now() {
            return Err(Validation::InvalidActiveTo.into());
        }

        if !all_validators_listed(&self.validators, &config.validators_whitelist) {
            return Err(Validation::UnlistedValidator.into());
        }

        if !creator_listed(&self, &config.creators_whitelist) {
            return Err(Validation::UnlistedCreator.into());
        }

        // Check if Channel token is listed in the configuration token Chain ID & Address
        let chain_context = config
            .find_chain_of(self.channel.token)
            .ok_or(Validation::UnlistedAsset)?;

        // Check if the campaign budget is above the minimum campaign budget configured
        if self
            .budget
            .to_precision(chain_context.token.precision.get())
            < chain_context.token.min_campaign_budget
        {
            return Err(Validation::MinimumDepositNotMet.into());
        }

        // Check if the validator fee is greater than the minimum configured fee
        if whoami_validator
            .fee
            .to_precision(chain_context.token.precision.get())
            < chain_context.token.min_validator_fee
        {
            return Err(Validation::MinimumValidatorFeeNotMet.into());
        }

        let total_validator_fee: UnifiedNum = self
            .validators
            .iter()
            .map(|v| &v.fee)
            .sum::<Option<_>>()
            // on overflow return an error
            .ok_or(Error::FeeSumOverflow)?;

        if total_validator_fee >= self.budget {
            return Err(Validation::FeeConstraintViolated.into());
        }

        Ok(chain_context.with_campaign(self))
    }
}

pub fn all_validators_listed(validators: &Validators, whitelist: &[ValidatorId]) -> bool {
    if whitelist.is_empty() {
        true
    } else {
        let found_validators = whitelist
            .iter()
            .filter(|&allowed| validators.find(allowed).is_some())
            // this will ensure that if we find the 2 validators earlier
            // we don't go over the other values of the whitelist
            .take(2);
        // the found validators should be exactly 2, if they are not, then 1 or 2 are missing
        found_validators.count() == 2
    }
}

pub fn creator_listed(campaign: &Campaign, whitelist: &[Address]) -> bool {
    // if the list is empty, return true, as we don't have a whitelist to restrict us to
    // or if we have a list, check if it includes the `channel.creator`
    whitelist.is_empty()
        || whitelist
            .iter()
            .any(|allowed| allowed.eq(&campaign.creator))
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        config::{self, GANACHE_CONFIG},
        test_util::{
            ADVERTISER, DUMMY_CAMPAIGN, DUMMY_VALIDATOR_FOLLOWER, DUMMY_VALIDATOR_LEADER, FOLLOWER,
            GUARDIAN, IDS, LEADER, PUBLISHER,
        },
        BigNum,
    };
    use chrono::{TimeZone, Utc};
    use std::str::FromStr;

    #[test]
    fn are_validators_listed() {
        let validators = Validators::new((
            DUMMY_VALIDATOR_LEADER.clone(),
            DUMMY_VALIDATOR_FOLLOWER.clone(),
        ));

        // empty whitelist
        let are_listed = all_validators_listed(&validators, &[]);
        assert!(are_listed);
        // no validators listed
        let are_listed = all_validators_listed(&validators, &[IDS[&ADVERTISER], IDS[&GUARDIAN]]);
        assert!(!are_listed);
        // one validator listed
        let are_listed = all_validators_listed(
            &validators,
            &[IDS[&ADVERTISER], IDS[&GUARDIAN], IDS[&LEADER]],
        );
        assert!(!are_listed);
        // both validators lister
        let are_listed = all_validators_listed(
            &validators,
            &[
                IDS[&ADVERTISER],
                IDS[&GUARDIAN],
                IDS[&LEADER],
                IDS[&FOLLOWER],
            ],
        );
        assert!(are_listed);
    }

    #[test]
    fn is_creator_listed() {
        let campaign = DUMMY_CAMPAIGN.clone();

        // empty whitelist
        let is_listed = creator_listed(&campaign, &[]);
        assert!(is_listed);

        // not listed
        let is_listed = creator_listed(&campaign, &[*PUBLISHER]);
        assert!(!is_listed);

        // listed
        let is_listed = creator_listed(&campaign, &[*PUBLISHER, campaign.creator]);
        assert!(is_listed);
    }

    #[test]
    fn chain_and_token_whitelist_validation() {
        let campaign = DUMMY_CAMPAIGN.clone();

        // no configured Chains & Tokens
        {
            let mut config = GANACHE_CONFIG.clone();
            config.chains.clear();

            let result = campaign.clone().validate(&config, campaign.channel.leader);

            assert!(matches!(
                result,
                Err(Error::Validation(Validation::UnlistedAsset))
            ));
        }

        {
            let config = GANACHE_CONFIG.clone();

            let _campaign_context = campaign
                .clone()
                .validate(&config, campaign.channel.leader)
                .expect(
                    "Default development config should contain the dummy campaign.channel.token",
                );
        }
    }

    #[test]
    fn are_campaigns_validated() {
        let config = config::GANACHE_CONFIG.clone();

        // Validator not in campaign
        {
            let campaign = DUMMY_CAMPAIGN.clone();

            let validation_error = campaign
                .validate(&config, IDS[&GUARDIAN])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::AdapterNotIncluded),
                validation_error,
            );
        }

        // active.to has passed
        {
            let mut campaign = DUMMY_CAMPAIGN.clone();
            campaign.active.to = Utc.ymd(2019, 1, 30).and_hms(0, 0, 0);

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::InvalidActiveTo),
                validation_error,
            );
        }

        // all_validators not listed
        {
            let campaign = DUMMY_CAMPAIGN.clone();
            let mut config = config::GANACHE_CONFIG.clone();
            config.validators_whitelist = vec![IDS[&LEADER], IDS[&GUARDIAN]];

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::UnlistedValidator),
                validation_error,
            );
        }

        // creator not listed
        {
            let campaign = DUMMY_CAMPAIGN.clone();
            let mut config = config::GANACHE_CONFIG.clone();
            config.creators_whitelist = vec![*PUBLISHER];

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::UnlistedCreator),
                validation_error,
            );
        }

        // token not listed
        {
            let mut campaign = DUMMY_CAMPAIGN.clone();
            campaign.channel.token = "0x0000000000000000000000000000000000000000"
                .parse::<Address>()
                .expect("Should parse");

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::UnlistedAsset),
                validation_error,
            );
        }

        // budget < min_deposit
        {
            let mut campaign = DUMMY_CAMPAIGN.clone();
            campaign.budget = UnifiedNum::from_u64(0);

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::MinimumDepositNotMet),
                validation_error,
            );
        }

        // validator_fee < min_fee
        {
            let campaign = DUMMY_CAMPAIGN.clone();
            let mut config = config::GANACHE_CONFIG.clone();

            let mut token_info = config
                .chains
                .values_mut()
                .find_map(|chain_info| {
                    chain_info
                        .tokens
                        .values_mut()
                        .find(|token_info| token_info.address == campaign.channel.token)
                })
                .expect("Should find Dummy campaign.channel.token");
            token_info.min_validator_fee = BigNum::from_str("999999999999999999999999999999999999")
                .expect("Should parse BigNum");

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::MinimumValidatorFeeNotMet),
                validation_error,
            );
        }

        let sum_fees = |validators: &Validators| -> UnifiedNum {
            validators
                .iter()
                .map(|validator| validator.fee)
                .sum::<Option<_>>()
                .expect("Validators sum of fees should not overflow")
        };

        // total_fee > budget
        // budget = total_fee - 1
        {
            let mut campaign = DUMMY_CAMPAIGN.clone();
            let campaign_token = config.find_chain_of(campaign.channel.token).unwrap().token;

            // makes the sum of all validator fees = 2 * min token units for deposit
            campaign.validators = {
                let new_validators = campaign
                    .validators
                    .iter()
                    .map(|validator| {
                        let mut new_validator = validator.clone();
                        new_validator.fee = UnifiedNum::from_precision(
                            campaign_token.min_campaign_budget.clone(),
                            campaign_token.precision.into(),
                        )
                        .expect("Should not overflow");

                        new_validator
                    })
                    .collect::<Vec<_>>();

                assert_eq!(
                    2,
                    new_validators.len(),
                    "Dummy Campaign validators should always be 2 - a leader & a follower"
                );

                Validators::new((new_validators[0].clone(), new_validators[1].clone()))
            };

            campaign.budget = sum_fees(&campaign.validators) - UnifiedNum::from(1);

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::FeeConstraintViolated),
                validation_error,
            );
        }

        // total_fee = budget
        {
            let mut campaign = DUMMY_CAMPAIGN.clone();

            let campaign_token = config.find_chain_of(campaign.channel.token).unwrap().token;

            // makes the sum of all validator fees = 2 * min token units for deposit
            campaign.validators = {
                let new_validators = campaign
                    .validators
                    .iter()
                    .map(|validator| {
                        let mut new_validator = validator.clone();
                        new_validator.fee = UnifiedNum::from_precision(
                            campaign_token.min_campaign_budget.clone(),
                            campaign_token.precision.into(),
                        )
                        .expect("Should not overflow");

                        new_validator
                    })
                    .collect::<Vec<_>>();

                assert_eq!(
                    2,
                    new_validators.len(),
                    "Dummy Campaign validators should always be 2 - a leader & a follower"
                );

                Validators::new((new_validators[0].clone(), new_validators[1].clone()))
            };

            campaign.budget = sum_fees(&campaign.validators);

            let validation_error = campaign
                .validate(&config, IDS[&LEADER])
                .expect_err("Should trigger validation error");
            assert_eq!(
                Error::Validation(Validation::FeeConstraintViolated),
                validation_error,
            );
        }

        // should validate
        {
            let campaign = DUMMY_CAMPAIGN.clone();
            let _campaign_context = campaign
                .validate(&config, IDS[&LEADER])
                .expect("Should pass validation");
        }
    }
}