-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
2074 lines (1861 loc) · 67.2 KB
/
lib.rs
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019 Alain Brenzikofer
// This file is part of Encointer
//
// Encointer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Encointer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Encointer. If not, see <http://www.gnu.org/licenses/>.
//! # Encointer Ceremonies Module
//!
//! The Encointer Ceremonies module provides functionality for
//! - registering for upcoming ceremony
//! - meetup assignment
//! - attestation registry
//! - issuance of basic income
//!
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use encointer_ceremonies_assignment::{
assignment_fn_inverse, generate_assignment_function_params, get_meetup_location_index,
math::{checked_ceil_division, find_prime_below, find_random_coprime_below},
meetup_index, meetup_location, meetup_time,
};
use encointer_meetup_validation::*;
use encointer_primitives::{
balances::BalanceType,
ceremonies::*,
communities::{CommunityIdentifier, Location, NominalIncome},
scheduler::{CeremonyIndexType, CeremonyPhaseType},
RandomNumberGenerator,
};
use encointer_scheduler::OnCeremonyPhaseChange;
use frame_support::{
dispatch::{DispatchResult, DispatchResultWithPostInfo},
ensure,
sp_std::cmp::min,
traits::{Get, Randomness},
weights::Pays,
};
use frame_system::ensure_signed;
use log::{debug, error, info, trace, warn};
use scale_info::TypeInfo;
use sp_runtime::traits::{CheckedSub, IdentifyAccount, Member, Verify};
use sp_std::{cmp::max, prelude::*, vec};
// Logger target
const LOG: &str = "encointer";
pub use pallet::*;
pub use weights::WeightInfo;
mod storage_helper;
#[allow(clippy::unused_unit)]
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub (super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_timestamp::Config
+ encointer_communities::Config
+ encointer_balances::Config
+ encointer_scheduler::Config
{
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
type CeremonyMaster: EnsureOrigin<Self::Origin>;
type Public: IdentifyAccount<AccountId = Self::AccountId>;
type Signature: Verify<Signer = Self::Public> + Member + Decode + Encode + TypeInfo;
type RandomnessSource: Randomness<Self::Hash, Self::BlockNumber>;
// Target number of participants per meetup
#[pallet::constant]
type MeetupSizeTarget: Get<u64>;
// Minimum meetup size
#[pallet::constant]
type MeetupMinSize: Get<u64>;
// Divisor used to determine the ratio of newbies allowed in relation to other participants
#[pallet::constant]
type MeetupNewbieLimitDivider: Get<u64>;
type WeightInfo: WeightInfo;
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight((<T as Config>::WeightInfo::register_participant(), DispatchClass::Normal, Pays::Yes))]
pub fn register_participant(
origin: OriginFor<T>,
cid: CommunityIdentifier,
proof: Option<ProofOfAttendance<T::Signature, T::AccountId>>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let current_phase = <encointer_scheduler::Pallet<T>>::current_phase();
ensure!(
CeremonyPhaseType::is_registering_or_attesting(¤t_phase),
Error::<T>::RegisteringOrAttestationPhaseRequired
);
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
let mut cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
if current_phase == CeremonyPhaseType::Attesting {
cindex += 1
};
if Self::is_registered(cid, cindex, &sender) {
return Err(<Error<T>>::ParticipantAlreadyRegistered.into())
}
if let Some(p) = &proof {
// we accept proofs from other communities as well. no need to ensure cid
ensure!(sender == p.prover_public, Error::<T>::WrongProofSubject);
ensure!(p.ceremony_index < cindex, Error::<T>::ProofAcausal);
ensure!(
p.ceremony_index >= cindex.saturating_sub(Self::reputation_lifetime()),
Error::<T>::ProofOutdated
);
ensure!(
Self::participant_reputation(
&(p.community_identifier, p.ceremony_index),
&p.attendee_public
) == Reputation::VerifiedUnlinked,
Error::<T>::AttendanceUnverifiedOrAlreadyUsed
);
if Self::verify_attendee_signature(p.clone()).is_err() {
return Err(<Error<T>>::BadProofOfAttendanceSignature.into())
};
// this reputation must now be burned so it can not be used again
<ParticipantReputation<T>>::insert(
&(p.community_identifier, p.ceremony_index),
&p.attendee_public,
Reputation::VerifiedLinked,
);
// register participant as reputable
<ParticipantReputation<T>>::insert(
(cid, cindex),
&sender,
Reputation::UnverifiedReputable,
);
};
let participant_type = Self::register(cid, cindex, &sender, proof.is_some())?;
// invalidate reputation cache
sp_io::offchain_index::set(&reputation_cache_dirty_key(&sender), &true.encode());
debug!(target: LOG, "registered participant: {:?} as {:?}", sender, participant_type);
Self::deposit_event(Event::ParticipantRegistered(cid, participant_type, sender));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::upgrade_registration(), DispatchClass::Normal, Pays::Yes))]
pub fn upgrade_registration(
origin: OriginFor<T>,
cid: CommunityIdentifier,
proof: ProofOfAttendance<T::Signature, T::AccountId>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin.clone())?;
let current_phase = <encointer_scheduler::Pallet<T>>::current_phase();
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
ensure!(
CeremonyPhaseType::is_registering_or_attesting(¤t_phase),
Error::<T>::RegisteringOrAttestationPhaseRequired
);
let mut cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
if current_phase == CeremonyPhaseType::Attesting {
cindex += 1
};
let participant_type = Self::get_participant_type((cid, cindex), &sender)
.ok_or(<Error<T>>::ParticipantIsNotRegistered)?;
if participant_type == ParticipantType::Newbie {
Self::remove_participant_from_registry(cid, cindex, &sender)?;
Self::register_participant(origin, cid, Some(proof))?;
} else {
return Err(<Error<T>>::MustBeNewbieToUpgradeRegistration.into())
}
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::unregister_participant(), DispatchClass::Normal, Pays::Yes))]
pub fn unregister_participant(
origin: OriginFor<T>,
cid: CommunityIdentifier,
maybe_reputation_community_ceremony: Option<CommunityCeremony>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
let current_phase = <encointer_scheduler::Pallet<T>>::current_phase();
ensure!(
CeremonyPhaseType::is_registering_or_attesting(¤t_phase),
Error::<T>::RegisteringOrAttestationPhaseRequired
);
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
let mut cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
if current_phase == CeremonyPhaseType::Attesting {
cindex += 1
};
let participant_type = Self::get_participant_type((cid, cindex), &sender)
.ok_or(<Error<T>>::ParticipantIsNotRegistered)?;
if participant_type == ParticipantType::Reputable {
let cc = maybe_reputation_community_ceremony
.ok_or(<Error<T>>::ReputationCommunityCeremonyRequired)?;
ensure!(
cc.1 >= cindex.saturating_sub(Self::reputation_lifetime()),
Error::<T>::ProofOutdated
);
ensure!(
Self::participant_reputation(&cc, &sender) == Reputation::VerifiedLinked,
Error::<T>::ReputationMustBeLinked
);
<ParticipantReputation<T>>::insert(&cc, &sender, Reputation::VerifiedUnlinked);
<ParticipantReputation<T>>::remove((cid, cindex), &sender);
}
Self::remove_participant_from_registry(cid, cindex, &sender)?;
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::attest_attendees(), DispatchClass::Normal, Pays::Yes))]
pub fn attest_attendees(
origin: OriginFor<T>,
cid: CommunityIdentifier,
number_of_participants_vote: u32,
attestations: Vec<T::AccountId>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(
<encointer_scheduler::Pallet<T>>::current_phase() == CeremonyPhaseType::Attesting,
Error::<T>::AttestationPhaseRequired
);
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
let (cindex, meetup_index, meetup_participants, _meetup_location, _meetup_time) =
Self::gather_meetup_data(&cid, &sender)?;
ensure!(meetup_participants.contains(&sender), Error::<T>::OriginNotParticipant);
ensure!(
attestations.len() < meetup_participants.len(),
Error::<T>::TooManyAttestations
);
debug!(
target: LOG,
"{:?} attempts to submit {:?} attestations",
sender,
attestations.len()
);
<MeetupParticipantCountVote<T>>::insert(
(cid, cindex),
&sender,
&number_of_participants_vote,
);
Self::add_attestations_to_registry(
sender,
&cid,
cindex,
meetup_index,
&meetup_participants,
&attestations,
)?;
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::attest_claims(), DispatchClass::Normal, Pays::Yes))]
pub fn attest_claims(
origin: OriginFor<T>,
claims: Vec<ClaimOfAttendance<T::Signature, T::AccountId, T::Moment>>,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(
<encointer_scheduler::Pallet<T>>::current_phase() == CeremonyPhaseType::Attesting,
Error::<T>::AttestationPhaseRequired
);
let cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
ensure!(!claims.is_empty(), Error::<T>::NoValidClaims);
let cid = claims[0].community_identifier; //safe; claims not empty checked above
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
let meetup_index = Self::get_meetup_index((cid, cindex), &sender)
.ok_or(<Error<T>>::ParticipantIsNotRegistered)?;
let mut meetup_participants =
Self::get_meetup_participants((cid, cindex), meetup_index)
.ok_or(<Error<T>>::GetMeetupParticipantsError)?;
ensure!(meetup_participants.contains(&sender), Error::<T>::OriginNotParticipant);
meetup_participants.retain(|x| x != &sender);
let num_registered = meetup_participants.len();
ensure!(claims.len() <= num_registered, Error::<T>::TooManyClaims);
let mut verified_attestees = vec![];
let mlocation = Self::get_meetup_location((cid, cindex), meetup_index)
.ok_or(<Error<T>>::MeetupLocationNotFound)?;
let mtime =
Self::get_meetup_time(mlocation).ok_or(<Error<T>>::MeetupTimeCalculationError)?;
debug!(
target: LOG,
"{:?} attempts to register {:?} attested claims",
sender,
claims.len()
);
debug!(
target: LOG,
"meetup {} at location {:?} planned to happen at {:?} for cid {:?}",
meetup_index,
mlocation,
mtime,
cid
);
for claim in claims.iter() {
let claimant = &claim.claimant_public;
if claimant == &sender {
warn!(target: LOG, "ignoring claim for self: {:?}", claimant);
continue
};
if !meetup_participants.contains(claimant) {
warn!(
target: LOG,
"ignoring claim that isn't a meetup participant: {:?}", claimant
);
continue
};
if claim.ceremony_index != cindex {
warn!(
target: LOG,
"ignoring claim with wrong ceremony index: {}", claim.ceremony_index
);
continue
};
if claim.community_identifier != cid {
warn!(
target: LOG,
"ignoring claim with wrong community identifier: {:?}",
claim.community_identifier
);
continue
};
if claim.meetup_index != meetup_index {
warn!(
target: LOG,
"ignoring claim with wrong meetup index: {}", claim.meetup_index
);
continue
};
if !<encointer_communities::Pallet<T>>::is_valid_location(&claim.location) {
warn!(
target: LOG,
"ignoring claim with illegal geolocation: {:?}", claim.location
);
continue
};
if <encointer_communities::Pallet<T>>::haversine_distance(
&mlocation,
&claim.location,
) > Self::location_tolerance()
{
warn!(
target: LOG,
"ignoring claim beyond location tolerance: {:?}", claim.location
);
continue
};
if let Some(dt) = mtime.checked_sub(&claim.timestamp) {
if dt > Self::time_tolerance() {
warn!(
target: LOG,
"ignoring claim beyond time tolerance (too early): {:?}",
claim.timestamp
);
continue
};
} else if let Some(dt) = claim.timestamp.checked_sub(&mtime) {
if dt > Self::time_tolerance() {
warn!(
target: LOG,
"ignoring claim beyond time tolerance (too late): {:?}",
claim.timestamp
);
continue
};
}
if !claim.verify_signature() {
warn!(target: LOG, "ignoring claim with bad signature for {:?}", claimant);
continue
};
// claim is legit. insert it!
verified_attestees.insert(0, claimant.clone());
// is it a problem if this number isn't equal for all claims? Guess not.
// is it a problem that this gets inserted multiple times? Guess not.
<MeetupParticipantCountVote<T>>::insert(
(cid, cindex),
&claimant,
&claim.number_of_participants_confirmed,
);
}
if verified_attestees.is_empty() {
return Err(<Error<T>>::NoValidClaims.into())
}
let count = <AttestationCount<T>>::get((cid, cindex));
let mut idx = count.checked_add(1).ok_or(Error::<T>::CheckedMath)?;
if <AttestationIndex<T>>::contains_key((cid, cindex), &sender) {
// update previously registered set
idx = <AttestationIndex<T>>::get((cid, cindex), &sender);
} else {
// add new set of attestees
let new_count = count
.checked_add(1)
.ok_or("[EncointerCeremonies]: Overflow adding set of attestees to registry")?;
<AttestationCount<T>>::insert((cid, cindex), new_count);
}
<AttestationRegistry<T>>::insert((cid, cindex), &idx, &verified_attestees);
<AttestationIndex<T>>::insert((cid, cindex), &sender, &idx);
let verified_count = verified_attestees.len() as u32;
debug!(target: LOG, "successfully registered {} claims", verified_count);
Self::deposit_event(Event::AttestationsRegistered(
cid,
meetup_index,
verified_count,
sender,
));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::endorse_newcomer(), DispatchClass::Normal, Pays::Yes))]
pub fn endorse_newcomer(
origin: OriginFor<T>,
cid: CommunityIdentifier,
newbie: T::AccountId,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(
<encointer_communities::Pallet<T>>::community_identifiers().contains(&cid),
Error::<T>::InexistentCommunity
);
let mut cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
if <encointer_scheduler::Pallet<T>>::current_phase() != CeremonyPhaseType::Registering {
cindex += 1; //safe; cindex comes from within, will not overflow at +1/d
}
ensure!(
Self::is_endorsed(&newbie, &(cid, cindex)).is_none(),
Error::<T>::AlreadyEndorsed
);
if <encointer_communities::Pallet<T>>::bootstrappers(&cid).contains(&sender) {
ensure!(
<BurnedBootstrapperNewbieTickets<T>>::get(&cid, &sender) <
Self::endorsement_tickets_per_bootstrapper(),
Error::<T>::NoMoreNewbieTickets
);
<BurnedBootstrapperNewbieTickets<T>>::mutate(&cid, sender.clone(), |b| *b += 1);
// safe; limited by AMOUNT_NEWBIE_TICKETS
} else if Self::has_reputation(&sender, &cid) {
ensure!(
<BurnedReputableNewbieTickets<T>>::get(&(cid, cindex), &sender) <
Self::endorsement_tickets_per_reputable(),
Error::<T>::NoMoreNewbieTickets
);
<BurnedReputableNewbieTickets<T>>::mutate(&(cid, cindex), sender.clone(), |b| {
*b += 1
}); // safe; limited by AMOUNT_NEWBIE_TICKETS
} else {
return Err(Error::<T>::AuthorizationRequired.into())
}
<Endorsees<T>>::insert((cid, cindex), newbie.clone(), ());
let new_endorsee_count = Self::endorsee_count((cid, cindex))
.checked_add(1)
.ok_or(<Error<T>>::RegistryOverflow)?;
<EndorseesCount<T>>::insert((cid, cindex), new_endorsee_count);
if <NewbieIndex<T>>::contains_key((cid, cindex), &newbie) {
Self::remove_participant_from_registry(cid, cindex, &newbie)?;
Self::register(cid, cindex, &newbie, false)?;
}
debug!(target: LOG, "bootstrapper {:?} endorsed newbie: {:?}", sender, newbie);
Self::deposit_event(Event::EndorsedParticipant(cid, sender, newbie));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::claim_rewards(), DispatchClass::Normal, Pays::Yes))]
pub fn claim_rewards(
origin: OriginFor<T>,
cid: CommunityIdentifier,
maybe_meetup_index: Option<MeetupIndexType>,
) -> DispatchResultWithPostInfo {
let participant = &ensure_signed(origin)?;
let current_phase = <encointer_scheduler::Pallet<T>>::current_phase();
let mut cindex = <encointer_scheduler::Pallet<T>>::current_ceremony_index();
match current_phase {
CeremonyPhaseType::Registering => cindex -= 1,
CeremonyPhaseType::Attesting => (),
CeremonyPhaseType::Assigning =>
return Err(<Error<T>>::WrongPhaseForClaimingRewards.into()),
}
let meetup_index = match maybe_meetup_index {
Some(index) => index,
None => Self::get_meetup_index((cid, cindex), participant)
.ok_or(<Error<T>>::ParticipantIsNotRegistered)?,
};
if <IssuedRewards<T>>::contains_key((cid, cindex), meetup_index) {
return Err(<Error<T>>::RewardsAlreadyIssued.into())
}
info!(
target: LOG,
"validating meetup {:?} for cid {:?} triggered by {:?}",
meetup_index,
&cid,
participant
);
//gather all data
let meetup_participants = Self::get_meetup_participants((cid, cindex), meetup_index)
.ok_or(<Error<T>>::GetMeetupParticipantsError)?;
let (participant_votes, participant_attestations) =
Self::gather_meetup_validation_data(cid, cindex, meetup_participants.clone());
// initialize an array of local participant indices that are eligible for the reward
// indices will be deleted in the following based on various rules
let mut participants_eligible_for_rewards: Vec<usize> =
(0..meetup_participants.len()).collect();
let attestation_threshold_fn =
|i: usize| max(if i > 5 { i.saturating_sub(2) } else { i.saturating_sub(1) }, 1);
let participant_judgements = match get_participant_judgements(
&participants_eligible_for_rewards,
&participant_votes,
&participant_attestations,
attestation_threshold_fn,
) {
Ok(participant_judgements) => participant_judgements,
// handle errors
Err(err) => {
// only mark issuance as complete in registering phase
// because in attesting phase there could be a failing early payout attempt
if current_phase == CeremonyPhaseType::Registering {
info!(target: LOG, "marking issuance as completed for failed meetup.");
<IssuedRewards<T>>::insert((cid, cindex), meetup_index, ());
}
match err {
MeetupValidationError::BallotEmpty => {
debug!(
target: LOG,
"ballot empty for meetup {:?}, cid: {:?}", meetup_index, cid
);
return Err(<Error<T>>::VotesNotDependable.into())
},
MeetupValidationError::NoDependableVote => {
debug!(
target: LOG,
"ballot doesn't reach dependable majority for meetup {:?}, cid: {:?}",
meetup_index,
cid
);
return Err(<Error<T>>::VotesNotDependable.into())
},
MeetupValidationError::IndexOutOfBounds => {
debug!(
target: LOG,
"index out of bounds for meetup {:?}, cid: {:?}", meetup_index, cid
);
return Err(<Error<T>>::MeetupValidationIndexOutOfBounds.into())
},
}
},
};
if current_phase == CeremonyPhaseType::Attesting &&
!participant_judgements.early_rewards_possible
{
debug!(
target: LOG,
"early rewards not possible for meetup {:?}, cid: {:?}", meetup_index, cid
);
return Err(<Error<T>>::EarlyRewardsNotPossible.into())
}
participants_eligible_for_rewards = participant_judgements.legit;
// emit events
for p in participant_judgements.excluded {
let participant = meetup_participants
.get(p.index)
.ok_or(Error::<T>::MeetupValidationIndexOutOfBounds)?
.clone();
Self::deposit_event(Event::NoReward {
cid,
cindex,
meetup_index,
account: participant,
reason: p.reason,
});
}
Self::issue_rewards(
cid,
cindex,
meetup_index,
meetup_participants,
participants_eligible_for_rewards,
)?;
Ok(Pays::No.into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_inactivity_timeout(), DispatchClass::Normal, Pays::Yes))]
pub fn set_inactivity_timeout(
origin: OriginFor<T>,
inactivity_timeout: InactivityTimeoutType,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<InactivityTimeout<T>>::put(inactivity_timeout);
info!(target: LOG, "set inactivity timeout to {}", inactivity_timeout);
Self::deposit_event(Event::InactivityTimeoutUpdated(inactivity_timeout));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_endorsement_tickets_per_bootstrapper(), DispatchClass::Normal, Pays::Yes))]
pub fn set_endorsement_tickets_per_bootstrapper(
origin: OriginFor<T>,
endorsement_tickets_per_bootstrapper: EndorsementTicketsType,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<EndorsementTicketsPerBootstrapper<T>>::put(endorsement_tickets_per_bootstrapper);
info!(
target: LOG,
"set endorsement tickets per bootstrapper to {}",
endorsement_tickets_per_bootstrapper
);
Self::deposit_event(Event::EndorsementTicketsPerBootstrapperUpdated(
endorsement_tickets_per_bootstrapper,
));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_endorsement_tickets_per_reputable(), DispatchClass::Normal, Pays::Yes))]
pub fn set_endorsement_tickets_per_reputable(
origin: OriginFor<T>,
endorsement_tickets_per_reputable: EndorsementTicketsType,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<EndorsementTicketsPerReputable<T>>::put(endorsement_tickets_per_reputable);
info!(
target: LOG,
"set endorsement tickets per reputable to {}", endorsement_tickets_per_reputable
);
Self::deposit_event(Event::EndorsementTicketsPerReputableUpdated(
endorsement_tickets_per_reputable,
));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_reputation_lifetime(), DispatchClass::Normal, Pays::Yes))]
pub fn set_reputation_lifetime(
origin: OriginFor<T>,
reputation_lifetime: ReputationLifetimeType,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<ReputationLifetime<T>>::put(reputation_lifetime);
info!(target: LOG, "set reputation lifetime to {}", reputation_lifetime);
Self::deposit_event(Event::ReputationLifetimeUpdated(reputation_lifetime));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_meetup_time_offset(), DispatchClass::Normal, Pays::Yes))]
pub fn set_meetup_time_offset(
origin: OriginFor<T>,
meetup_time_offset: MeetupTimeOffsetType,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
if <encointer_scheduler::Pallet<T>>::current_phase() != CeremonyPhaseType::Registering {
return Err(<Error<T>>::WrongPhaseForChangingMeetupTimeOffset.into())
}
// Meetup time offset needs to be in [-8h, 8h]
if meetup_time_offset.abs() > 8 * 3600 * 1000 {
return Err(<Error<T>>::InvalidMeetupTimeOffset.into())
}
<MeetupTimeOffset<T>>::put(meetup_time_offset);
info!(target: LOG, "set meetup time offset to {} ms", meetup_time_offset);
Self::deposit_event(Event::MeetupTimeOffsetUpdated(meetup_time_offset));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_time_tolerance(), DispatchClass::Normal, Pays::Yes))]
pub fn set_time_tolerance(
origin: OriginFor<T>,
time_tolerance: T::Moment,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<TimeTolerance<T>>::put(time_tolerance);
info!(target: LOG, "set meetup time tolerance to {:?}", time_tolerance);
Self::deposit_event(Event::TimeToleranceUpdated(time_tolerance));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::set_location_tolerance(), DispatchClass::Normal, Pays::Yes))]
pub fn set_location_tolerance(
origin: OriginFor<T>,
location_tolerance: u32,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
<LocationTolerance<T>>::put(location_tolerance);
info!(target: LOG, "set meetup location tolerance to {}", location_tolerance);
Self::deposit_event(Event::LocationToleranceUpdated(location_tolerance));
Ok(().into())
}
#[pallet::weight((<T as Config>::WeightInfo::purge_community_ceremony(), DispatchClass::Normal, Pays::Yes))]
pub fn purge_community_ceremony(
origin: OriginFor<T>,
community_ceremony: CommunityCeremony,
) -> DispatchResultWithPostInfo {
<T as pallet::Config>::CeremonyMaster::ensure_origin(origin)?;
Self::purge_community_ceremony_internal(community_ceremony);
Ok(().into())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Participant registered for next ceremony [community, participant type, who]
ParticipantRegistered(CommunityIdentifier, ParticipantType, T::AccountId),
/// A bootstrapper (first accountid) has endorsed a participant (second accountid) who can now register as endorsee for this ceremony
EndorsedParticipant(CommunityIdentifier, T::AccountId, T::AccountId),
/// A participant has registered N attestations for fellow meetup participants
AttestationsRegistered(CommunityIdentifier, MeetupIndexType, u32, T::AccountId),
/// rewards have been claimed and issued successfully for N participants for their meetup at the previous ceremony
RewardsIssued(CommunityIdentifier, MeetupIndexType, u8),
/// inactivity timeout has changed. affects how many ceremony cycles a community can be idle before getting purged
InactivityTimeoutUpdated(InactivityTimeoutType),
/// The number of endorsement tickets which bootstrappers can give out has changed
EndorsementTicketsPerBootstrapperUpdated(EndorsementTicketsType),
/// The number of endorsement tickets which bootstrappers can give out has changed
EndorsementTicketsPerReputableUpdated(EndorsementTicketsType),
/// reputation lifetime has changed. After this many ceremony cycles, reputations is outdated
ReputationLifetimeUpdated(ReputationLifetimeType),
/// meetup time offset has changed. affects the exact time the upcoming ceremony meetups will take place
MeetupTimeOffsetUpdated(MeetupTimeOffsetType),
/// meetup time tolerance has changed
TimeToleranceUpdated(T::Moment),
/// meetup location tolerance changed [m]
LocationToleranceUpdated(u32),
/// the registry for given ceremony index and community has been purged
CommunityCeremonyHistoryPurged(CommunityIdentifier, CeremonyIndexType),
NoReward {
cid: CommunityIdentifier,
cindex: CeremonyIndexType,
meetup_index: MeetupIndexType,
account: T::AccountId,
reason: ExclusionReason,
},
/// The inactivity counter of a community has been increased
InactivityCounterUpdated(CommunityIdentifier, u32),
}
#[pallet::error]
pub enum Error<T> {
/// the participant is already registered
ParticipantAlreadyRegistered,
/// verification of signature of attendee failed
BadProofOfAttendanceSignature,
/// verification of signature of attendee failed
BadAttendeeSignature,
/// meetup location was not found
MeetupLocationNotFound,
/// meetup time calculation failed
MeetupTimeCalculationError,
/// no valid claims were supplied
NoValidClaims,
/// sender doesn't have the necessary authority to perform action
AuthorizationRequired,
/// the action can only be performed during REGISTERING phase
RegisteringPhaseRequired,
/// the action can only be performed during ATTESTING phase
AttestationPhaseRequired,
/// the action can only be performed during REGISTERING or ATTESTING phase
RegisteringOrAttestationPhaseRequired,
/// CommunityIdentifier not found
InexistentCommunity,
/// proof is outdated
ProofOutdated,
/// proof is acausal
ProofAcausal,
/// supplied proof is not proving sender
WrongProofSubject,
/// former attendance has not been verified or has already been linked to other account
AttendanceUnverifiedOrAlreadyUsed,
/// origin not part of this meetup
OriginNotParticipant,
/// can't have more attestations than other meetup participants
TooManyAttestations,
/// can't have more claims than other meetup participants
TooManyClaims,
/// bootstrapper has run out of newbie tickets
NoMoreNewbieTickets,
/// newbie is already endorsed
AlreadyEndorsed,
/// Participant is not registered
ParticipantIsNotRegistered,
/// No locations are available for assigning participants
NoLocationsAvailable,
/// Trying to issue rewards in a phase that is not REGISTERING
WrongPhaseForClaimingRewards,
/// Trying to issue rewards for a meetup for which UBI was already issued
RewardsAlreadyIssued,
/// Trying to claim UBI for a meetup where votes are not dependable
VotesNotDependable,
/// Overflow adding user to registry
RegistryOverflow,
/// CheckedMath operation error
CheckedMath,
/// Only Bootstrappers are allowed to be registered at this time
OnlyBootstrappers,
/// MeetupTimeOffset can only be changed during registering
WrongPhaseForChangingMeetupTimeOffset,
/// MeetupTimeOffset needs to be in [-8h, 8h]
InvalidMeetupTimeOffset,
/// the history for given ceremony index and community has been purged
CommunityCeremonyHistoryPurged,
/// Unregistering can only be performed during the registering phase
WrongPhaseForUnregistering,
/// Error while finding meetup participants
GetMeetupParticipantsError,
// index out of bounds while validating the meetup
MeetupValidationIndexOutOfBounds,
// Attestations beyond time tolerance
AttestationsBeyondTimeTolerance,
// Not possible to pay rewards in attestations phase
EarlyRewardsNotPossible,
// Only newbies can upgrade their registration
MustBeNewbieToUpgradeRegistration,
// To unregister as a reputable you need to provide a provide a community ceremony where you have a linked reputation
ReputationCommunityCeremonyRequired,
// In order to unregister a reputable, the provided reputation must be linked
ReputationMustBeLinked,
}
#[pallet::storage]
#[pallet::getter(fn bootstrapper_newbie_tickets)]
pub(super) type BurnedBootstrapperNewbieTickets<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityIdentifier,
Blake2_128Concat,
T::AccountId,
u8,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn reputable_newbie_tickets)]
pub(super) type BurnedReputableNewbieTickets<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
T::AccountId,
u8,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn bootstrapper_registry)]
pub(super) type BootstrapperRegistry<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
ParticipantIndexType,
T::AccountId,
OptionQuery,
>;
#[pallet::storage]
#[pallet::getter(fn bootstrapper_index)]
pub(super) type BootstrapperIndex<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
T::AccountId,
ParticipantIndexType,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn bootstrapper_count)]
pub(super) type BootstrapperCount<T: Config> =
StorageMap<_, Blake2_128Concat, CommunityCeremony, ParticipantIndexType, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn reputable_registry)]
pub(super) type ReputableRegistry<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
ParticipantIndexType,
T::AccountId,
OptionQuery,
>;
#[pallet::storage]
#[pallet::getter(fn reputable_index)]
pub(super) type ReputableIndex<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
T::AccountId,
ParticipantIndexType,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn reputable_count)]
pub(super) type ReputableCount<T: Config> =
StorageMap<_, Blake2_128Concat, CommunityCeremony, ParticipantIndexType, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn endorsee_registry)]
pub(super) type EndorseeRegistry<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,
ParticipantIndexType,
T::AccountId,
OptionQuery,
>;
#[pallet::storage]
#[pallet::getter(fn endorsee_index)]
pub(super) type EndorseeIndex<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
CommunityCeremony,
Blake2_128Concat,