-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathlib.rs
More file actions
1381 lines (1256 loc) · 53.2 KB
/
lib.rs
File metadata and controls
1381 lines (1256 loc) · 53.2 KB
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
// This file is part of the Polymesh distribution (https://github.com/PolymeshAssociation/Polymesh).
// Copyright (c) 2020 Polymesh Association
// This program 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, version 3.
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
//! # Multisig Module
//!
//! The multisig module provides functionality for `n` out of `m` multisigs.
//!
//! ## Overview
//!
//! The multisig module provides functions for:
//!
//! - creating a new multisig,
//! - proposing a multisig transaction,
//! - approving a multisig transaction,
//! - adding new signers to the multisig,
//! - removing existing signers from multisig.
//!
//! ### Terminology
//!
//! - **multisig**: a special type of account that can do transaction only if at least `n` of its `m`
//! signers approve.
//! - **proposal**: a general transaction that the multisig can vote on and accept.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! - `create_multisig` - Creates a new multisig.
//! - `create_proposal` - Creates a multisig proposal given the signer's account key.
//! - `approve` - Approves a multisig proposal given the signer's account key.
//! - `reject` - Rejects a multisig proposal using the caller's secondary key (`AccountId`).
//! - `accept_multisig_signer` - Accepts a multisig signer authorization given the signer's
//! account key.
//! - `add_multisig_signer` - Adds a signer to the multisig.
//! - `remove_multisig_signer` - Removes a signer from the multisig.
//! - `add_multisig_signers_via_admin` - Adds a signer to the multisig when called by the
//! admin of the multisig.
//! - `remove_multisig_signers_via_admin` - Removes a signer from the multisig when called by the
//! admin of the multisig.
//! - `change_sigs_required` - Changes the number of signers required to execute a transaction.
//!
//! ### Other Public Functions
//!
//! - `base_create_multisig` - Creates a multisig account without precondition checks or emitting
//! an event.
//! - `base_create_proposal` - Creates a proposal for a multisig transaction.
//! - `base_accept_multisig_signer` - Accepts and processes an addition of a signer to a multisig.
//! - `get_next_multisig_address` - Gets the next available multisig account ID.
//! - `get_multisig_address` - Constructs a multisig account given a nonce.
//! - `ms_signers` - Helper function that checks if someone is an authorized signer of a multisig or
//! not.
//! - `is_changing_signers_allowed` - Checks whether changing the list of signers is allowed in a
//! multisig.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
use codec::{Decode, Encode};
use core::convert::From;
use frame_support::dispatch::{
DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, PostDispatchInfo,
};
use frame_support::pallet_prelude::DispatchError;
use frame_support::traits::{Get, GetCallMetadata, IsSubType, UnfilteredDispatchable};
use frame_support::weights::Weight;
use frame_support::{ensure, BoundedVec};
use frame_system::ensure_signed;
use sp_runtime::traits::{Dispatchable, Hash};
use sp_std::convert::TryFrom;
use sp_std::prelude::*;
use pallet_identity::{CddAuthForPrimaryKeyRotation, Config as IdentityConfig};
use pallet_permissions::with_call_metadata;
use polymesh_primitives::multisig::{ProposalState, ProposalVoteCount};
use polymesh_primitives::{
extract_auth, storage_migration_ver, AuthorizationData, IdentityId, KeyRecord, Permissions,
RocksDbWeight as DbWeight, Signatory,
};
pub trait WeightInfo {
fn create_multisig(signers: u32) -> Weight;
fn create_proposal() -> Weight;
fn approve() -> Weight;
fn execute_proposal() -> Weight;
fn reject() -> Weight;
fn accept_multisig_signer() -> Weight;
fn add_multisig_signers(signers: u32) -> Weight;
fn remove_multisig_signers(signers: u32) -> Weight;
fn add_multisig_signers_via_admin(signers: u32) -> Weight;
fn remove_multisig_signers_via_admin(signers: u32) -> Weight;
fn change_sigs_required() -> Weight;
fn change_sigs_required_via_admin() -> Weight;
fn add_admin() -> Weight;
fn remove_admin_via_admin() -> Weight;
fn remove_payer() -> Weight;
fn remove_payer_via_payer() -> Weight;
fn create_join_identity() -> Weight;
fn approve_join_identity() -> Weight;
fn join_identity() -> Weight;
fn remove_admin() -> Weight;
fn default_max_weight(max_weight: &Option<Weight>) -> Weight {
max_weight.unwrap_or_else(|| {
// TODO: Use a better default weight.
Self::create_proposal()
})
}
fn approve_and_execute(max_weight: &Option<Weight>) -> Weight {
Self::approve()
.saturating_add(Self::execute_proposal())
.saturating_add(Self::default_max_weight(max_weight))
}
}
type IdentityPallet<T> = pallet_identity::Pallet<T>;
storage_migration_ver!(3);
fn add_base_weight(base_weight: Weight, post_info: &mut PostDispatchInfo) {
if let Some(actual_weight) = &mut post_info.actual_weight {
*actual_weight = actual_weight.saturating_add(base_weight);
} else {
post_info.actual_weight = Some(base_weight);
}
}
fn with_base_weight(
base_weight: Weight,
tx: impl FnOnce() -> DispatchResultWithPostInfo,
) -> DispatchResultWithPostInfo {
match tx() {
Ok(mut post_info) => {
add_base_weight(base_weight, &mut post_info);
Ok(post_info)
}
Err(mut err) => {
add_base_weight(base_weight, &mut err.post_info);
Err(err)
}
}
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config + IdentityConfig {
/// The overarching call type for proposals.
type Proposal: Parameter
+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo>
+ GetCallMetadata
+ GetDispatchInfo
+ From<Call<Self>>
+ From<frame_system::Call<Self>>
+ UnfilteredDispatchable<RuntimeOrigin = Self::RuntimeOrigin>
+ IsSubType<Call<Self>>
+ IsType<<Self as frame_system::Config>::RuntimeCall>;
/// Weight information for extrinsics in the multisig pallet.
type WeightInfo: WeightInfo;
/// Maximum number of signers that can be added/removed in one call.
#[pallet::constant]
type MaxSigners: Get<u32>;
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_runtime_upgrade() -> Weight {
use sp_version::RuntimeVersion;
let mut weight = Weight::zero();
// Clear pending proposals if the transaction version is upgraded
let current_version = <T::Version as Get<RuntimeVersion>>::get().transaction_version;
if TransactionVersion::<T>::get() < current_version {
TransactionVersion::<T>::set(current_version);
// TODO: Multiblock migration.
let mut removed = 0;
let res = Proposals::<T>::clear(u32::max_value(), None);
removed += res.unique;
let res = ProposalVoteCounts::<T>::clear(u32::max_value(), None);
removed += res.unique;
let res = ProposalStates::<T>::clear(u32::max_value(), None);
removed += res.unique;
let res = Votes::<T>::clear(u32::max_value(), None);
removed += res.unique;
weight.saturating_accrue(DbWeight::get().reads_writes(removed as _, removed as _));
}
weight
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Creates a multisig
///
/// # Arguments
/// * `signers` - Signers of the multisig (They need to accept authorization before they are actually added).
/// * `sigs_required` - Number of sigs required to process a multi-sig tx.
/// * `permissions` - optional custom permissions. Only the primary key can provide custom permissions.
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::create_multisig(signers.len() as u32))]
pub fn create_multisig(
origin: OriginFor<T>,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
sigs_required: u64,
permissions: Option<Permissions>,
) -> DispatchResultWithPostInfo {
let (caller, caller_did) =
IdentityPallet::<T>::ensure_valid_origin(origin, permissions.is_some())?;
let signers_len: u64 = u64::try_from(signers.len()).unwrap_or_default();
Self::ensure_sigs_in_bounds(signers_len, sigs_required)?;
Self::base_create_multisig(
caller,
caller_did,
signers,
sigs_required,
permissions.unwrap_or(Permissions::empty()),
)?;
Ok(().into())
}
/// Creates a multisig proposal
///
/// # Arguments
/// * `multisig` - MultiSig address.
/// * `proposal` - Proposal to be voted on.
/// * `expiry` - Optional proposal expiry time.
///
/// If this is 1 out of `m` multisig, the proposal will be immediately executed.
#[pallet::call_index(1)]
#[pallet::weight({
<T as Config>::WeightInfo::create_proposal()
.saturating_add(<T as Config>::WeightInfo::execute_proposal())
.saturating_add(proposal.get_dispatch_info().call_weight)
})]
pub fn create_proposal(
origin: OriginFor<T>,
multisig: T::AccountId,
proposal: Box<<T as Config>::Proposal>,
expiry: Option<T::Moment>,
) -> DispatchResultWithPostInfo {
let signer = ensure_signed(origin)?;
with_base_weight(<T as Config>::WeightInfo::create_proposal(), || {
Self::base_create_proposal(&multisig, signer, &proposal, expiry)
})
}
/// Approves a multisig proposal using the caller's secondary key (`AccountId`).
///
/// # Arguments
/// * `multisig` - MultiSig address.
/// * `proposal_id` - Proposal id to approve.
/// * `max_weight` - The maximum weight to execute the proposal.
///
/// If quorum is reached, the proposal will be immediately executed.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::approve_and_execute(max_weight))]
pub fn approve(
origin: OriginFor<T>,
multisig: T::AccountId,
proposal_id: u64,
max_weight: Option<Weight>,
) -> DispatchResultWithPostInfo {
let max_weight = <T as Config>::WeightInfo::default_max_weight(&max_weight);
let signer = ensure_signed(origin)?;
with_base_weight(<T as Config>::WeightInfo::approve(), || {
Self::base_approve(&multisig, signer, proposal_id, max_weight)
})
}
/// Rejects a multisig proposal using the caller's secondary key (`AccountId`).
///
/// # Arguments
/// * `multisig` - MultiSig address.
/// * `proposal_id` - Proposal id to reject.
/// If quorum is reached, the proposal will be immediately executed.
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::reject())]
pub fn reject(
origin: OriginFor<T>,
multisig: T::AccountId,
proposal_id: u64,
) -> DispatchResultWithPostInfo {
let signer = ensure_signed(origin)?;
Self::base_reject(&multisig, signer, proposal_id)?;
Ok(().into())
}
/// Accepts a multisig signer authorization given to signer's key (AccountId).
///
/// # Arguments
/// * `auth_id` - Auth id of the authorization.
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::accept_multisig_signer())]
pub fn accept_multisig_signer(
origin: OriginFor<T>,
auth_id: u64,
) -> DispatchResultWithPostInfo {
let signer = ensure_signed(origin)?;
Self::base_accept_multisig_signer(signer, auth_id)?;
Ok(().into())
}
/// Adds signers to the multisig. This must be called by the multisig itself.
///
/// # Arguments
/// * `signers` - Signers to add.
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::add_multisig_signers(signers.len() as u32))]
pub fn add_multisig_signers(
origin: OriginFor<T>,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
Self::base_add_signers(None, multisig, signers)?;
Ok(().into())
}
/// Removes signers from the multisig. This must be called by the multisig itself.
///
/// # Arguments
/// * `signers` - Signers to remove.
#[pallet::weight(<T as Config>::WeightInfo::remove_multisig_signers(signers.len() as u32))]
#[pallet::call_index(6)]
pub fn remove_multisig_signers(
origin: OriginFor<T>,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
// Remove the signers from the multisig.
Self::base_remove_signers(None, multisig, signers)?;
Ok(().into())
}
/// Adds a signer to the multisig. This must be called by the admin identity of the
/// multisig.
///
/// # Arguments
/// * `multisig` - Address of the multi sig
/// * `signers` - Signers to add.
///
#[pallet::call_index(7)]
#[pallet::weight(<T as Config>::WeightInfo::add_multisig_signers_via_admin(signers.len() as u32))]
pub fn add_multisig_signers_via_admin(
origin: OriginFor<T>,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResultWithPostInfo {
let caller_did = Self::ensure_ms_admin(origin, &multisig)?;
Self::base_add_signers(Some(caller_did), multisig, signers)?;
Ok(().into())
}
/// Removes a signer from the multisig.
/// This must be called by the admin identity of the multisig.
///
/// # Arguments
/// * `multisig` - Address of the multisig.
/// * `signers` - Signers to remove.
///
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::remove_multisig_signers_via_admin(signers.len() as u32))]
pub fn remove_multisig_signers_via_admin(
origin: OriginFor<T>,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResultWithPostInfo {
// Ensure the caller is the admin and that they haven't lost permissions.
let caller_did = Self::ensure_ms_admin(origin, &multisig)?;
// Remove the signers from the multisig.
Self::base_remove_signers(Some(caller_did), multisig, signers)?;
Ok(().into())
}
/// Changes the number of signatures required by a multisig. This must be called by the
/// multisig itself.
///
/// # Arguments
/// * `sigs_required` - New number of required signatures.
#[pallet::call_index(9)]
#[pallet::weight(<T as Config>::WeightInfo::change_sigs_required())]
pub fn change_sigs_required(
origin: OriginFor<T>,
sigs_required: u64,
) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
Self::base_change_multisig_required_signatures(None, &multisig, sigs_required)?;
Ok(().into())
}
/// Changes the number of signatures required by a multisig. This must be called by the admin of the multisig.
///
/// # Arguments
/// * `multisig` - The account identifier ([`AccountId`]) for the multi signature account.
/// * `signatures_required` - The number of required signatures.
#[pallet::call_index(10)]
#[pallet::weight(<T as Config>::WeightInfo::change_sigs_required_via_admin())]
pub fn change_sigs_required_via_admin(
origin: OriginFor<T>,
multisig: T::AccountId,
signatures_required: u64,
) -> DispatchResultWithPostInfo {
let caller_did = Self::ensure_ms_admin(origin, &multisig)?;
Self::base_change_multisig_required_signatures(
Some(caller_did),
&multisig,
signatures_required,
)?;
Ok(().into())
}
/// Add an admin identity to the multisig. This must be called by the multisig itself.
#[pallet::call_index(11)]
#[pallet::weight(<T as Config>::WeightInfo::add_admin())]
pub fn add_admin(
origin: OriginFor<T>,
admin_did: IdentityId,
) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
let caller_did = Self::ensure_ms_has_did(&multisig)?;
AdminDid::<T>::insert(&multisig, admin_did);
Self::deposit_event(Event::MultiSigAddedAdmin {
caller_did,
multisig,
admin_did,
});
Ok(().into())
}
/// Removes the admin identity from the `multisig`. This must be called by the admin of the multisig.
#[pallet::call_index(12)]
#[pallet::weight(<T as Config>::WeightInfo::remove_admin_via_admin())]
pub fn remove_admin_via_admin(
origin: OriginFor<T>,
multisig: T::AccountId,
) -> DispatchResultWithPostInfo {
let admin_did = Self::ensure_ms_admin(origin, &multisig)?;
AdminDid::<T>::remove(&multisig);
Self::deposit_event(Event::MultiSigRemovedAdmin {
caller_did: admin_did,
multisig,
admin_did,
});
Ok(().into())
}
/// Removes the paying identity from the `multisig`. This must be called by the multisig itself.
#[pallet::call_index(13)]
#[pallet::weight(<T as Config>::WeightInfo::remove_payer())]
pub fn remove_payer(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
let caller_did = Self::ensure_ms_has_did(&multisig)?;
let paying_did = PayingDid::<T>::take(&multisig).ok_or(Error::<T>::NoPayingDid)?;
Self::deposit_event(Event::MultiSigRemovedPayingDid {
caller_did,
multisig,
paying_did,
});
Ok(().into())
}
/// Removes the paying identity from the `multisig`. This must be called by the paying identity of the multisig.
#[pallet::call_index(14)]
#[pallet::weight(<T as Config>::WeightInfo::remove_payer_via_payer())]
pub fn remove_payer_via_payer(
origin: OriginFor<T>,
multisig: T::AccountId,
) -> DispatchResultWithPostInfo {
let paying_did = Self::ensure_ms_payer(origin, &multisig)?;
PayingDid::<T>::remove(&multisig);
Self::deposit_event(Event::MultiSigRemovedPayingDid {
caller_did: paying_did,
multisig,
paying_did,
});
Ok(().into())
}
/// Approves a multisig join identity proposal.
///
/// # Arguments
/// * `multisig` - MultiSig address.
/// * `auth_id` - The join identity authorization to approve.
///
/// If quorum is reached, the join identity proposal will be immediately executed.
#[pallet::call_index(15)]
#[pallet::weight({
<T as Config>::WeightInfo::create_join_identity()
.saturating_add(<T as Config>::WeightInfo::approve_join_identity())
.saturating_add(<T as Config>::WeightInfo::execute_proposal())
.saturating_add(<T as Config>::WeightInfo::join_identity())
})]
pub fn approve_join_identity(
origin: OriginFor<T>,
multisig: T::AccountId,
auth_id: u64,
) -> DispatchResultWithPostInfo {
let signer = ensure_signed(origin)?;
if let Some(proposal_id) = AuthToProposalId::<T>::get(&multisig, auth_id) {
let max_weight = <T as Config>::WeightInfo::join_identity();
with_base_weight(<T as Config>::WeightInfo::approve_join_identity(), || {
Self::base_approve(&multisig, signer, proposal_id, max_weight)
})
} else {
let proposal = Call::<T>::join_identity { auth_id }.into();
let proposal_id = NextProposalId::<T>::get(&multisig);
AuthToProposalId::<T>::insert(&multisig, auth_id, proposal_id);
with_base_weight(<T as Config>::WeightInfo::create_join_identity(), || {
Self::base_create_proposal(&multisig, signer, &proposal, None)
})
}
}
/// Accept a JoinIdentity authorization for this multisig. This must be called by the multisig itself.
#[pallet::call_index(16)]
#[pallet::weight(<T as Config>::WeightInfo::join_identity())]
pub fn join_identity(origin: OriginFor<T>, auth_id: u64) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin.clone())?;
Self::ensure_ms(&multisig)?;
AuthToProposalId::<T>::remove(multisig, auth_id);
pallet_identity::Pallet::<T>::join_identity(origin, auth_id)?;
Ok(().into())
}
/// Removes the admin identity from the `multisig`. This must be called by the multisig itself.
#[pallet::call_index(17)]
#[pallet::weight(<T as Config>::WeightInfo::remove_admin())]
pub fn remove_admin(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
let multisig = ensure_signed(origin)?;
let caller_did = Self::ensure_ms_has_did(&multisig)?;
let admin_did = AdminDid::<T>::take(&multisig).ok_or(Error::<T>::AdminNotFound)?;
Self::deposit_event(Event::MultiSigRemovedAdmin {
caller_did,
multisig,
admin_did,
});
Ok(().into())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A Multisig has been created.
MultiSigCreated {
caller_did: IdentityId,
multisig: T::AccountId,
caller: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
sigs_required: u64,
},
/// A Multisig proposal has been created.
ProposalAdded {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
proposal_id: u64,
},
/// A Multisig proposal has been executed.
ProposalExecuted {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
proposal_id: u64,
result: DispatchResult,
},
/// A new signer has been added to a Multisig.
MultiSigSignerAdded {
caller_did: IdentityId,
multisig: T::AccountId,
signer: T::AccountId,
},
/// New keys have been authorized to be signers on a Multisig.
MultiSigSignersAuthorized {
caller_did: IdentityId,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
},
/// Signers have been removed from a Multisig.
MultiSigSignersRemoved {
caller_did: IdentityId,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
},
/// A Multisig has changed its required number of approvals.
MultiSigSignersRequiredChanged {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
sigs_required: u64,
},
/// A signer has voted to approve a Multisig proposal.
ProposalApprovalVote {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
signer: T::AccountId,
proposal_id: u64,
},
/// A signer has voted to reject a Multisig proposal.
ProposalRejectionVote {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
signer: T::AccountId,
proposal_id: u64,
},
/// A Multisig proposal has been approved.
ProposalApproved {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
proposal_id: u64,
},
/// A Multisig proposal has been rejected.
ProposalRejected {
caller_did: Option<IdentityId>,
multisig: T::AccountId,
proposal_id: u64,
},
/// A Multisig has added an admin DID.
MultiSigAddedAdmin {
caller_did: IdentityId,
multisig: T::AccountId,
admin_did: IdentityId,
},
/// A Multisig has removed it's admin DID.
MultiSigRemovedAdmin {
caller_did: IdentityId,
multisig: T::AccountId,
admin_did: IdentityId,
},
/// A Multisig has removed it's paying DID.
MultiSigRemovedPayingDid {
caller_did: IdentityId,
multisig: T::AccountId,
paying_did: IdentityId,
},
}
/// Multisig module errors.
#[pallet::error]
pub enum Error<T> {
/// The proposal does not exist.
ProposalMissing,
/// Multisig address.
DecodingError,
/// Required number of signers must be greater then zero.
RequiredSignersIsZero,
/// Not a signer.
NotASigner,
/// No such multisig.
NoSuchMultisig,
/// Not enough signers. The number of signers has to be greater then or equal to
/// the required number of signers to approve proposals.
NotEnoughSigners,
/// A nonce overflow.
NonceOverflow,
/// Already voted.
AlreadyVoted,
/// Already a signer.
AlreadyASigner,
/// Identity provided is not the multisig's admin.
IdentityNotAdmin,
/// Identity provided is not the multisig's payer.
IdentityNotPayer,
/// Changing multisig parameters not allowed since multisig is a primary key.
ChangeNotAllowed,
/// Signer is an account key that is already associated with a multisig.
SignerAlreadyLinkedToMultisig,
/// Signer is an account key that is already associated with an identity.
SignerAlreadyLinkedToIdentity,
/// A multisig can't be a signer of another multisig.
NestingNotAllowed,
/// Proposal was rejected earlier
ProposalAlreadyRejected,
/// Proposal has expired
ProposalExpired,
/// Proposal was executed earlier
ProposalAlreadyExecuted,
/// Max weight not enough to execute proposal.
MaxWeightTooLow,
/// Multisig is not attached to an identity
MultisigMissingIdentity,
/// Tried to add/remove too many signers.
TooManySigners,
/// Multisig doesn't have a paying DID.
NoPayingDid,
/// Expiry must be in the future.
InvalidExpiryDate,
/// The proposal has been invalidated after a multisg update.
InvalidatedProposal,
/// Multisig has no admin.
AdminNotFound,
/// The extrinsic expected a different `AuthorizationType` than what the `data.auth_type()` is.
BadAuthorizationType,
}
/// Nonce to ensure unique MultiSig addresses are generated; starts from 1.
#[pallet::storage]
pub type MultiSigNonce<T: Config> = StorageValue<_, u64, ValueQuery>;
/// Signers of a multisig. (multisig, signer) => bool.
#[pallet::storage]
pub type MultiSigSigners<T: Config> =
StorageDoubleMap<_, Identity, T::AccountId, Twox64Concat, T::AccountId, bool, ValueQuery>;
/// Number of approved/accepted signers of a multisig.
#[pallet::storage]
pub type NumberOfSigners<T: Config> = StorageMap<_, Identity, T::AccountId, u64, ValueQuery>;
/// Confirmations required before processing a multisig tx.
#[pallet::storage]
pub type MultiSigSignsRequired<T: Config> =
StorageMap<_, Identity, T::AccountId, u64, ValueQuery>;
/// Next proposal id for a multisig. Starts from 0.
///
/// multisig => next proposal id
#[pallet::storage]
pub type NextProposalId<T: Config> = StorageMap<_, Identity, T::AccountId, u64, ValueQuery>;
/// Proposals presented for voting to a multisig.
///
/// multisig -> proposal id => Option<Proposal>.
#[pallet::storage]
pub type Proposals<T: Config> =
StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, u64, <T as Config>::Proposal>;
/// Individual multisig signer votes.
///
/// (multisig, proposal_id) -> signer => vote.
#[pallet::storage]
pub type Votes<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
(T::AccountId, u64),
Twox64Concat,
T::AccountId,
bool,
ValueQuery,
>;
/// The multisig's paying identity. The primary key of this identity
/// pays the transaction/protocal fees of the multisig proposals.
///
/// multisig -> Option<IdentityId>.
#[pallet::storage]
pub type PayingDid<T: Config> = StorageMap<_, Identity, T::AccountId, IdentityId>;
/// The multisig's admin identity. The primary key of this identity
/// has admin control over the multisig.
///
/// multisig -> Option<IdentityId>.
#[pallet::storage]
pub type AdminDid<T: Config> = StorageMap<_, Identity, T::AccountId, IdentityId>;
/// The count of approvals/rejections of a multisig proposal.
///
/// multisig -> proposal id => Option<ProposalVoteCount>.
#[pallet::storage]
pub type ProposalVoteCounts<T: Config> =
StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, u64, ProposalVoteCount>;
/// The state of a multisig proposal
///
/// multisig -> proposal id => Option<ProposalState>.
#[pallet::storage]
pub type ProposalStates<T: Config> = StorageDoubleMap<
_,
Twox64Concat,
T::AccountId,
Twox64Concat,
u64,
ProposalState<T::Moment>,
>;
/// Proposal execution reentry guard.
#[pallet::storage]
pub(super) type ExecutionReentry<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Pending join identity authorization proposals.
///
/// multisig -> auth id => Option<proposal id>.
#[pallet::storage]
pub type AuthToProposalId<T: Config> =
StorageDoubleMap<_, Twox64Concat, T::AccountId, Twox64Concat, u64, u64>;
/// The last transaction version, used for `on_runtime_upgrade`.
#[pallet::storage]
pub(super) type TransactionVersion<T: Config> = StorageValue<_, u32, ValueQuery>;
/// The last proposal id before the multisig changed signers or signatures required.
///
/// multisig => Option<proposal id>
#[pallet::storage]
pub type LastInvalidProposal<T: Config> =
StorageMap<_, Identity, T::AccountId, u64, OptionQuery>;
/// Storage version.
#[pallet::storage]
pub(super) type StorageVersion<T: Config> = StorageValue<_, Version, ValueQuery>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T> {
#[serde(skip)]
pub _config: sp_std::marker::PhantomData<T>,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
MultiSigNonce::<T>::put(1);
TransactionVersion::<T>::put(0);
StorageVersion::<T>::put(Version::new(3));
}
}
}
impl<T: Config> Pallet<T> {
pub fn get_paying_did(multisig: &T::AccountId) -> Option<IdentityId> {
PayingDid::<T>::get(multisig)
}
pub fn ensure_ms_get_did(multisig: &T::AccountId) -> Result<Option<IdentityId>, DispatchError> {
Self::ensure_ms(multisig)?;
Ok(IdentityPallet::<T>::get_identity(multisig))
}
pub fn ensure_ms_has_did(multisig: &T::AccountId) -> Result<IdentityId, DispatchError> {
Self::ensure_ms_get_did(multisig)?.ok_or(Error::<T>::MultisigMissingIdentity.into())
}
fn ensure_max_signers(multisig: &T::AccountId, len: u64) -> Result<u64, DispatchError> {
let pending_num_of_signers = NumberOfSigners::<T>::get(&multisig)
.checked_add(len)
.ok_or(Error::<T>::TooManySigners)?;
ensure!(
pending_num_of_signers <= T::MaxSigners::get() as u64,
Error::<T>::TooManySigners
);
Ok(pending_num_of_signers)
}
fn ensure_ms_admin(
origin: T::RuntimeOrigin,
multisig: &T::AccountId,
) -> Result<IdentityId, DispatchError> {
let (_, caller_did) = IdentityPallet::<T>::ensure_primary_key(origin)?;
let admin_did = AdminDid::<T>::get(multisig);
ensure!(admin_did == Some(caller_did), Error::<T>::IdentityNotAdmin);
Ok(caller_did)
}
fn ensure_ms_payer(
origin: T::RuntimeOrigin,
multisig: &T::AccountId,
) -> Result<IdentityId, DispatchError> {
let (_, caller_did) = IdentityPallet::<T>::ensure_primary_key(origin)?;
let payer_did = PayingDid::<T>::get(multisig);
ensure!(payer_did == Some(caller_did), Error::<T>::IdentityNotPayer);
Ok(caller_did)
}
fn ensure_ms(multisig: &T::AccountId) -> DispatchResult {
ensure!(
MultiSigSignsRequired::<T>::contains_key(multisig),
Error::<T>::NoSuchMultisig
);
Ok(())
}
fn ensure_ms_signer(ms: &T::AccountId, signer: &T::AccountId) -> DispatchResult {
ensure!(
MultiSigSigners::<T>::get(ms, signer),
Error::<T>::NotASigner
);
Ok(())
}
fn ensure_sigs_in_bounds(num_signers: u64, required: u64) -> DispatchResult {
ensure!(required > 0, Error::<T>::RequiredSignersIsZero);
ensure!(num_signers >= required, Error::<T>::NotEnoughSigners);
Ok(())
}
fn ensure_proposal_is_active(multisig: &T::AccountId, proposal_id: u64) -> DispatchResult {
match ProposalStates::<T>::get(multisig, proposal_id) {
None => Err(Error::<T>::ProposalMissing.into()),
Some(ProposalState::Rejected) => Err(Error::<T>::ProposalAlreadyRejected.into()),
Some(ProposalState::ExecutionSuccessful | ProposalState::ExecutionFailed) => {
Err(Error::<T>::ProposalAlreadyExecuted.into())
}
Some(ProposalState::Active { until: None }) => {
Self::ensure_valid_proposal(multisig, proposal_id)?;
Ok(())
}
Some(ProposalState::Active { until: Some(until) }) => {
Self::ensure_valid_proposal(multisig, proposal_id)?;
// Ensure proposal is not expired
ensure!(
until > pallet_timestamp::Pallet::<T>::get(),
Error::<T>::ProposalExpired
);
Ok(())
}
}
}
fn base_authorize_signers(
caller_did: IdentityId,
multisig: &T::AccountId,
signers: &BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResult {
for signer in signers {
IdentityPallet::<T>::add_auth(
caller_did,
Signatory::Account(signer.clone()),
AuthorizationData::AddMultiSigSigner(multisig.clone()),
None,
)?;
}
Ok(())
}
fn base_add_signers(
caller_did: Option<IdentityId>,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResult {
// Ensure `multisig` is a MultiSig and get it's DID.
let ms_did = Self::ensure_ms_has_did(&multisig)?;
// Don't allow adding too many signers.
Self::ensure_max_signers(&multisig, signers.len() as u64)?;
Self::base_authorize_signers(ms_did, &multisig, &signers)?;
Self::deposit_event(Event::MultiSigSignersAuthorized {
caller_did: caller_did.unwrap_or(ms_did),
multisig,
signers,
});
Ok(())
}
fn base_remove_signers(
caller_did: Option<IdentityId>,
multisig: T::AccountId,
signers: BoundedVec<T::AccountId, T::MaxSigners>,
) -> DispatchResult {
// Ensure `multisig` is a MultiSig and get it's DID.
let ms_did = Self::ensure_ms_has_did(&multisig)?;
ensure!(
Self::is_changing_signers_allowed(&multisig),
Error::<T>::ChangeNotAllowed
);
let signers_len: u64 = u64::try_from(signers.len()).unwrap_or_default();
let pending_num_of_signers = NumberOfSigners::<T>::get(&multisig)
.checked_sub(signers_len)
.ok_or(Error::<T>::TooManySigners)?;
let sigs_required = MultiSigSignsRequired::<T>::get(&multisig);
Self::ensure_sigs_in_bounds(pending_num_of_signers, sigs_required)?;
for signer in &signers {
Self::ensure_ms_signer(&multisig, signer)?;
IdentityPallet::<T>::remove_key_record(signer, None);
MultiSigSigners::<T>::remove(&multisig, signer);
}
NumberOfSigners::<T>::insert(&multisig, pending_num_of_signers);
Self::set_invalid_proposals(&multisig);
Self::deposit_event(Event::MultiSigSignersRemoved {
caller_did: caller_did.unwrap_or(ms_did),
multisig: multisig.clone(),
signers,
});
Ok(())