-
Notifications
You must be signed in to change notification settings - Fork 415
/
lib.rs
executable file
·1086 lines (998 loc) · 39.7 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
//! # Multisig Wallet
//!
//! This implements a plain multi owner wallet.
//!
//! ## Warning
//!
//! This contract is an *example*. It is neither audited nor endorsed for production use.
//! Do **not** rely on it to keep anything of value secure.
//!
//! ## Overview
//!
//! Each instantiation of this contract has a set of `owners` and a `requirement` of
//! how many of them need to agree on a `Transaction` for it to be able to be executed.
//! Every owner can submit a transaction and when enough of the other owners confirm
//! it will be able to be executed. The following invariant is enforced by the contract:
//!
//! ```ignore
//! 0 < requirement && requirement <= owners && owners <= MAX_OWNERS
//! ```
//!
//! ## Error Handling
//!
//! With the exception of `execute_transaction` no error conditions are signalled
//! through return types. Any error or invariant violation triggers a panic and therefore
//! rolls back the transaction.
//!
//! ## Interface
//!
//! The interface is modelled after the popular Gnosis multisig wallet. However, there
//! are subtle variations from the interface. For example the `confirm_transaction`
//! will never trigger the execution of a `Transaction` even if the threshold is reached.
//! A call of `execute_transaction` is always required. This can be called by anyone.
//!
//! All the messages that are declared as only callable by the wallet must go through
//! the usual submit, confirm, execute cycle as any other transaction that should be
//! called by the wallet. For example, to add an owner you would submit a transaction
//! that calls the wallets own `add_owner` message through `submit_transaction`.
//!
//! ### Owner Management
//!
//! The messages `add_owner`, `remove_owner`, and `replace_owner` can be used to manage
//! the owner set after instantiation.
//!
//! ### Changing the Requirement
//!
//! `change_requirement` can be used to tighten or relax the `requirement` of how many
//! owner signatures are needed to execute a `Transaction`.
//!
//! ### Transaction Management
//!
//! `submit_transaction`, `cancel_transaction`, `confirm_transaction`,
//! `revoke_confirmation` and `execute_transaction` are the bread and butter messages
//! of this contract. Use them to dispatch arbitrary messages to other contracts
//! with the wallet as a sender.
#![cfg_attr(not(feature = "std"), no_std)]
pub use self::multisig::{
ConfirmationStatus,
Multisig,
Transaction,
};
use ink_lang as ink;
#[ink::contract]
mod multisig {
use ink_env::call::{
build_call,
Call,
ExecutionInput,
};
use ink_prelude::vec::Vec;
use ink_storage::{
traits::{
PackedLayout,
SpreadAllocate,
SpreadLayout,
},
Mapping,
};
use scale::Output;
/// Tune this to your liking but be wary that allowing too many owners will not perform well.
const MAX_OWNERS: u32 = 50;
type TransactionId = u32;
const WRONG_TRANSACTION_ID: &str =
"The user specified an invalid transaction id. Abort.";
/// A wrapper that allows us to encode a blob of bytes.
///
/// We use this to pass the set of untyped (bytes) parameters to the `CallBuilder`.
struct CallInput<'a>(&'a [u8]);
impl<'a> scale::Encode for CallInput<'a> {
fn encode_to<T: Output + ?Sized>(&self, dest: &mut T) {
dest.write(self.0);
}
}
/// Indicates whether a transaction is already confirmed or needs further confirmations.
#[derive(scale::Encode, scale::Decode, Clone, Copy, SpreadLayout, PackedLayout)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)
)]
pub enum ConfirmationStatus {
/// The transaction is already confirmed.
Confirmed,
/// Indicates how many confirmations are remaining.
ConfirmationsNeeded(u32),
}
/// A Transaction is what every `owner` can submit for confirmation by other owners.
/// If enough owners agree it will be executed by the contract.
#[derive(scale::Encode, scale::Decode, SpreadLayout, PackedLayout)]
#[cfg_attr(
feature = "std",
derive(
Debug,
PartialEq,
Eq,
scale_info::TypeInfo,
ink_storage::traits::StorageLayout
)
)]
pub struct Transaction {
/// The `AccountId` of the contract that is called in this transaction.
pub callee: AccountId,
/// The selector bytes that identifies the function of the callee that should be called.
pub selector: [u8; 4],
/// The SCALE encoded parameters that are passed to the called function.
pub input: Vec<u8>,
/// The amount of chain balance that is transferred to the callee.
pub transferred_value: Balance,
/// Gas limit for the execution of the call.
pub gas_limit: u64,
}
/// Errors that can occur upon calling this contract.
#[derive(Copy, Clone, Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(::scale_info::TypeInfo))]
pub enum Error {
/// Returned if the call failed.
TransactionFailed,
}
/// This is a book keeping struct that stores a list of all transaction ids and
/// also the next id to use. We need it for cleaning up the storage.
#[derive(
scale::Encode, scale::Decode, SpreadLayout, PackedLayout, SpreadAllocate, Default,
)]
#[cfg_attr(
feature = "std",
derive(
Debug,
PartialEq,
Eq,
scale_info::TypeInfo,
ink_storage::traits::StorageLayout
)
)]
pub struct Transactions {
/// Just store all transaction ids packed.
transactions: Vec<TransactionId>,
/// We just increment this whenever a new transaction is created.
/// We never decrement or defragment. For now, the contract becomes defunct
/// when the ids are exhausted.
next_id: TransactionId,
}
/// Emitted when an owner confirms a transaction.
#[ink(event)]
pub struct Confirmation {
/// The transaction that was confirmed.
#[ink(topic)]
transaction: TransactionId,
/// The owner that sent the confirmation.
#[ink(topic)]
from: AccountId,
/// The confirmation status after this confirmation was applied.
#[ink(topic)]
status: ConfirmationStatus,
}
/// Emitted when an owner revoked a confirmation.
#[ink(event)]
pub struct Revocation {
/// The transaction that was revoked.
#[ink(topic)]
transaction: TransactionId,
/// The owner that sent the revocation.
#[ink(topic)]
from: AccountId,
}
/// Emitted when an owner submits a transaction.
#[ink(event)]
pub struct Submission {
/// The transaction that was submitted.
#[ink(topic)]
transaction: TransactionId,
}
/// Emitted when a transaction was canceled.
#[ink(event)]
pub struct Cancellation {
/// The transaction that was canceled.
#[ink(topic)]
transaction: TransactionId,
}
/// Emitted when a transaction was executed.
#[ink(event)]
pub struct Execution {
/// The transaction that was executed.
#[ink(topic)]
transaction: TransactionId,
/// Indicates whether the transaction executed successfully. If so the `Ok` value holds
/// the output in bytes. The Option is `None` when the transaction was executed through
/// `invoke_transaction` rather than `evaluate_transaction`.
#[ink(topic)]
result: Result<Option<Vec<u8>>, Error>,
}
/// Emitted when an owner is added to the wallet.
#[ink(event)]
pub struct OwnerAddition {
/// The owner that was added.
#[ink(topic)]
owner: AccountId,
}
/// Emitted when an owner is removed from the wallet.
#[ink(event)]
pub struct OwnerRemoval {
/// The owner that was removed.
#[ink(topic)]
owner: AccountId,
}
/// Emitted when the requirement changed.
#[ink(event)]
pub struct RequirementChange {
/// The new requirement value.
new_requirement: u32,
}
#[ink(storage)]
#[derive(SpreadAllocate)]
pub struct Multisig {
/// Every entry in this map represents the confirmation of an owner for a
/// transaction. This is effectively a set rather than a map.
confirmations: Mapping<(TransactionId, AccountId), ()>,
/// The amount of confirmations for every transaction. This is a redundant
/// information and is kept in order to prevent iterating through the
/// confirmation set to check if a transaction is confirmed.
confirmation_count: Mapping<TransactionId, u32>,
/// Map the transaction id to its unexecuted transaction.
transactions: Mapping<TransactionId, Transaction>,
/// We need to hold a list of all transactions so that we can clean up storage
/// when an owner is removed.
transaction_list: Transactions,
/// The list is a vector because iterating over it is necessary when cleaning
/// up the confirmation set.
owners: Vec<AccountId>,
/// Redundant information to speed up the check whether a caller is an owner.
is_owner: Mapping<AccountId, ()>,
/// Minimum number of owners that have to confirm a transaction to be executed.
requirement: u32,
}
impl Multisig {
/// The only constructor of the contract.
///
/// A list of owners must be supplied and a number of how many of them must
/// confirm a transaction. Duplicate owners are silently dropped.
///
/// # Panics
///
/// If `requirement` violates our invariant.
#[ink(constructor)]
pub fn new(requirement: u32, mut owners: Vec<AccountId>) -> Self {
ink_lang::utils::initialize_contract(|contract: &mut Self| {
owners.sort_unstable();
owners.dedup();
ensure_requirement_is_valid(owners.len() as u32, requirement);
for owner in &owners {
contract.is_owner.insert(owner, &());
}
contract.owners = owners;
contract.transaction_list = Default::default();
contract.requirement = requirement;
})
}
/// Add a new owner to the contract.
///
/// Only callable by the wallet itself.
///
/// # Panics
///
/// If the owner already exists.
///
/// # Examples
///
/// Since this message must be send by the wallet itself it has to be build as a
/// `Transaction` and dispatched through `submit_transaction` and `invoke_transaction`:
/// ```should_panic
/// use ink_env::{
/// call::{
/// utils::ArgumentList,
/// Call,
/// CallParams,
/// ExecutionInput,
/// Selector,
/// },
/// AccountId,
/// DefaultEnvironment as Env,
/// };
/// use ink_lang::selector_bytes;
/// use scale::Encode;
/// use multisig::{Transaction, ConfirmationStatus};
///
/// // address of an existing `Multisig` contract
/// let wallet_id: AccountId = [7u8; 32].into();
///
/// // first create the transaction that adds `alice` through `add_owner`
/// let alice: AccountId = [1u8; 32].into();
/// let add_owner_args = ArgumentList::empty().push_arg(&alice);
///
/// let transaction_candidate = Transaction {
/// callee: wallet_id,
/// selector: selector_bytes!("add_owner"),
/// input: add_owner_args.encode(),
/// transferred_value: 0,
/// gas_limit: 0
/// };
///
/// // Submit the transaction for confirmation
/// //
/// // Note that the selector bytes of the `submit_transaction` method
/// // are `[86, 244, 13, 223]`.
/// let (id, _status) = ink_env::call::build_call::<ink_env::DefaultEnvironment>()
/// .call_type(Call::new().callee(wallet_id))
/// .gas_limit(0)
/// .exec_input(ExecutionInput::new(Selector::new([86, 244, 13, 223]))
/// .push_arg(&transaction_candidate)
/// )
/// .returns::<(u32, ConfirmationStatus)>()
/// .fire()
/// .expect("submit_transaction won't panic");
///
/// // Wait until all required owners have confirmed and then execute the transaction
/// //
/// // Note that the selector bytes of the `invoke_transaction` method
/// // are `[185, 50, 225, 236]`.
/// ink_env::call::build_call::<ink_env::DefaultEnvironment>()
/// .call_type(Call::new().callee(wallet_id))
/// .gas_limit(0)
/// .exec_input(ExecutionInput::new(Selector::new([185, 50, 225, 236]))
/// .push_arg(&id)
/// )
/// .returns::<()>()
/// .fire()
/// .expect("invoke_transaction won't panic");
/// ```
#[ink(message)]
pub fn add_owner(&mut self, new_owner: AccountId) {
self.ensure_from_wallet();
self.ensure_no_owner(&new_owner);
ensure_requirement_is_valid(self.owners.len() as u32 + 1, self.requirement);
self.is_owner.insert(new_owner, &());
self.owners.push(new_owner);
self.env().emit_event(OwnerAddition { owner: new_owner });
}
/// Remove an owner from the contract.
///
/// Only callable by the wallet itself. If by doing this the amount of owners
/// would be smaller than the requirement it is adjusted to be exactly the
/// number of owners.
///
/// # Panics
///
/// If `owner` is no owner of the wallet.
#[ink(message)]
pub fn remove_owner(&mut self, owner: AccountId) {
self.ensure_from_wallet();
self.ensure_owner(&owner);
let len = self.owners.len() as u32 - 1;
let requirement = u32::min(len, self.requirement);
ensure_requirement_is_valid(len, requirement);
let owner_index = self.owner_index(&owner) as usize;
self.owners.swap_remove(owner_index);
self.is_owner.remove(&owner);
self.requirement = requirement;
self.clean_owner_confirmations(&owner);
self.env().emit_event(OwnerRemoval { owner });
}
/// Replace an owner from the contract with a new one.
///
/// Only callable by the wallet itself.
///
/// # Panics
///
/// If `old_owner` is no owner or if `new_owner` already is one.
#[ink(message)]
pub fn replace_owner(&mut self, old_owner: AccountId, new_owner: AccountId) {
self.ensure_from_wallet();
self.ensure_owner(&old_owner);
self.ensure_no_owner(&new_owner);
let owner_index = self.owner_index(&old_owner);
self.owners[owner_index as usize] = new_owner;
self.is_owner.remove(&old_owner);
self.is_owner.insert(new_owner, &());
self.clean_owner_confirmations(&old_owner);
self.env().emit_event(OwnerRemoval { owner: old_owner });
self.env().emit_event(OwnerAddition { owner: new_owner });
}
/// Change the requirement to a new value.
///
/// Only callable by the wallet itself.
///
/// # Panics
///
/// If the `new_requirement` violates our invariant.
#[ink(message)]
pub fn change_requirement(&mut self, new_requirement: u32) {
self.ensure_from_wallet();
ensure_requirement_is_valid(self.owners.len() as u32, new_requirement);
self.requirement = new_requirement;
self.env().emit_event(RequirementChange { new_requirement });
}
/// Add a new transaction candidate to the contract.
///
/// This also confirms the transaction for the caller. This can be called by any owner.
#[ink(message)]
pub fn submit_transaction(
&mut self,
transaction: Transaction,
) -> (TransactionId, ConfirmationStatus) {
self.ensure_caller_is_owner();
let trans_id = self.transaction_list.next_id;
self.transaction_list.next_id =
trans_id.checked_add(1).expect("Transaction ids exhausted.");
self.transactions.insert(trans_id, &transaction);
self.transaction_list.transactions.push(trans_id);
self.env().emit_event(Submission {
transaction: trans_id,
});
(
trans_id,
self.confirm_by_caller(self.env().caller(), trans_id),
)
}
/// Remove a transaction from the contract.
/// Only callable by the wallet itself.
///
/// # Panics
///
/// If `trans_id` is no valid transaction id.
#[ink(message)]
pub fn cancel_transaction(&mut self, trans_id: TransactionId) {
self.ensure_from_wallet();
if self.take_transaction(trans_id).is_some() {
self.env().emit_event(Cancellation {
transaction: trans_id,
});
}
}
/// Confirm a transaction for the sender that was submitted by any owner.
///
/// This can be called by any owner.
///
/// # Panics
///
/// If `trans_id` is no valid transaction id.
#[ink(message)]
pub fn confirm_transaction(
&mut self,
trans_id: TransactionId,
) -> ConfirmationStatus {
self.ensure_caller_is_owner();
self.ensure_transaction_exists(trans_id);
self.confirm_by_caller(self.env().caller(), trans_id)
}
/// Revoke the senders confirmation.
///
/// This can be called by any owner.
///
/// # Panics
///
/// If `trans_id` is no valid transaction id.
#[ink(message)]
pub fn revoke_confirmation(&mut self, trans_id: TransactionId) {
self.ensure_caller_is_owner();
let caller = self.env().caller();
if self.confirmations.get(&(trans_id, caller)).is_some() {
self.confirmations.remove(&(trans_id, caller));
let mut confirmation_count = self
.confirmation_count
.get(&trans_id)
.expect(
"There is a entry in `self.confirmations`. Hence a count must exit.",
);
// Will not underflow as there is at least one confirmation
confirmation_count -= 1;
self.confirmation_count
.insert(&trans_id, &confirmation_count);
self.env().emit_event(Revocation {
transaction: trans_id,
from: caller,
});
}
}
/// Invoke a confirmed execution without getting its output.
///
/// If the transaction which is invoked transfers value, this value has
/// to be sent as payment with this call. The method will fail otherwise,
/// and the transaction would then be reverted.
///
/// Its return value indicates whether the called transaction was successful.
/// This can be called by anyone.
#[ink(message, payable)]
pub fn invoke_transaction(
&mut self,
trans_id: TransactionId,
) -> Result<(), Error> {
self.ensure_confirmed(trans_id);
let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID);
assert!(self.env().transferred_value() == t.transferred_value);
let result = build_call::<<Self as ::ink_lang::reflect::ContractEnv>::Env>()
.call_type(
Call::new()
.callee(t.callee)
.gas_limit(t.gas_limit)
.transferred_value(t.transferred_value),
)
.exec_input(
ExecutionInput::new(t.selector.into()).push_arg(CallInput(&t.input)),
)
.returns::<()>()
.fire()
.map_err(|_| Error::TransactionFailed);
self.env().emit_event(Execution {
transaction: trans_id,
result: result.map(|_| None),
});
result
}
/// Evaluate a confirmed execution and return its output as bytes.
///
/// Its return value indicates whether the called transaction was successful and contains
/// its output when successful.
/// This can be called by anyone.
#[ink(message, payable)]
pub fn eval_transaction(
&mut self,
trans_id: TransactionId,
) -> Result<Vec<u8>, Error> {
self.ensure_confirmed(trans_id);
let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID);
let result = build_call::<<Self as ::ink_lang::reflect::ContractEnv>::Env>()
.call_type(
Call::new()
.callee(t.callee)
.gas_limit(t.gas_limit)
.transferred_value(t.transferred_value),
)
.exec_input(
ExecutionInput::new(t.selector.into()).push_arg(CallInput(&t.input)),
)
.returns::<Vec<u8>>()
.fire()
.map_err(|_| Error::TransactionFailed);
self.env().emit_event(Execution {
transaction: trans_id,
result: result.clone().map(Some),
});
result
}
/// Set the `transaction` as confirmed by `confirmer`.
/// Idempotent operation regarding an already confirmed `transaction`
/// by `confirmer`.
fn confirm_by_caller(
&mut self,
confirmer: AccountId,
transaction: TransactionId,
) -> ConfirmationStatus {
let mut count = self.confirmation_count.get(&transaction).unwrap_or(0);
let key = (transaction, confirmer);
let new_confirmation = self.confirmations.get(&key).is_none();
if new_confirmation {
count += 1;
self.confirmations.insert(&key, &());
self.confirmation_count.insert(&transaction, &count);
}
let status = {
if count >= self.requirement {
ConfirmationStatus::Confirmed
} else {
ConfirmationStatus::ConfirmationsNeeded(self.requirement - count)
}
};
if new_confirmation {
self.env().emit_event(Confirmation {
transaction,
from: confirmer,
status,
});
}
status
}
/// Get the index of `owner` in `self.owners`.
/// Panics if `owner` is not found in `self.owners`.
fn owner_index(&self, owner: &AccountId) -> u32 {
self.owners.iter().position(|x| *x == *owner).expect(
"This is only called after it was already verified that the id is
actually an owner.",
) as u32
}
/// Remove the transaction identified by `trans_id` from `self.transactions`.
/// Also removes all confirmation state associated with it.
fn take_transaction(&mut self, trans_id: TransactionId) -> Option<Transaction> {
let transaction = self.transactions.get(&trans_id);
if transaction.is_some() {
self.transactions.remove(&trans_id);
let pos = self
.transaction_list
.transactions
.iter()
.position(|t| t == &trans_id)
.expect("The transaction exists hence it must also be in the list.");
self.transaction_list.transactions.swap_remove(pos);
for owner in self.owners.iter() {
self.confirmations.remove(&(trans_id, *owner));
}
self.confirmation_count.remove(&trans_id);
}
transaction
}
/// Remove all confirmation state associated with `owner`.
/// Also adjusts the `self.confirmation_count` variable.
fn clean_owner_confirmations(&mut self, owner: &AccountId) {
for trans_id in &self.transaction_list.transactions {
let key = (*trans_id, *owner);
if self.confirmations.get(&key).is_some() {
self.confirmations.remove(&key);
let mut count = self.confirmation_count.get(&trans_id).unwrap_or(0);
count -= 1;
self.confirmation_count.insert(&trans_id, &count);
}
}
}
/// Panic if transaction `trans_id` is not confirmed by at least
/// `self.requirement` owners.
fn ensure_confirmed(&self, trans_id: TransactionId) {
assert!(
self.confirmation_count
.get(&trans_id)
.expect(WRONG_TRANSACTION_ID)
>= self.requirement
);
}
/// Panic if the transaction `trans_id` does not exit.
fn ensure_transaction_exists(&self, trans_id: TransactionId) {
self.transactions.get(trans_id).expect(WRONG_TRANSACTION_ID);
}
/// Panic if the sender is no owner of the wallet.
fn ensure_caller_is_owner(&self) {
self.ensure_owner(&self.env().caller());
}
/// Panic if the sender is not this wallet.
fn ensure_from_wallet(&self) {
assert_eq!(self.env().caller(), self.env().account_id());
}
/// Panic if `owner` is not an owner,
fn ensure_owner(&self, owner: &AccountId) {
assert!(self.is_owner.get(owner).is_some());
}
/// Panic if `owner` is an owner.
fn ensure_no_owner(&self, owner: &AccountId) {
assert!(self.is_owner.get(owner).is_none());
}
}
/// Panic if the number of `owners` under a `requirement` violates our
/// requirement invariant.
fn ensure_requirement_is_valid(owners: u32, requirement: u32) {
assert!(0 < requirement && requirement <= owners && owners <= MAX_OWNERS);
}
#[cfg(test)]
mod tests {
use super::*;
use ink_env::{
call::utils::ArgumentList,
test,
};
use ink_lang as ink;
const WALLET: [u8; 32] = [7; 32];
impl Transaction {
fn change_requirement(requirement: u32) -> Self {
use scale::Encode;
let call_args = ArgumentList::empty().push_arg(&requirement);
// Multisig::change_requirement()
Self {
callee: AccountId::from(WALLET),
selector: ink::selector_bytes!("change_requirement"),
input: call_args.encode(),
transferred_value: 0,
gas_limit: 1000000,
}
}
}
fn set_caller(sender: AccountId) {
ink_env::test::set_caller::<Environment>(sender);
}
fn set_from_wallet() {
let callee = AccountId::from(WALLET);
set_caller(callee);
}
fn set_from_owner() {
let accounts = default_accounts();
set_caller(accounts.alice);
}
fn set_from_no_owner() {
let accounts = default_accounts();
set_caller(accounts.django);
}
fn default_accounts() -> test::DefaultAccounts<Environment> {
ink_env::test::default_accounts::<Environment>()
}
fn build_contract() -> Multisig {
// Set the contract's address as `WALLET`.
let callee: AccountId = AccountId::from(WALLET);
ink_env::test::set_callee::<ink_env::DefaultEnvironment>(callee);
let accounts = default_accounts();
let owners = vec![accounts.alice, accounts.bob, accounts.eve];
Multisig::new(2, owners)
}
fn submit_transaction() -> Multisig {
let mut contract = build_contract();
let accounts = default_accounts();
set_from_owner();
contract.submit_transaction(Transaction::change_requirement(1));
assert_eq!(contract.transaction_list.transactions.len(), 1);
assert_eq!(test::recorded_events().count(), 2);
let transaction = contract.transactions.get(0).unwrap();
assert_eq!(transaction, Transaction::change_requirement(1));
contract.confirmations.get(&(0, accounts.alice)).unwrap();
assert_eq!(contract.confirmation_count.get(&0).unwrap(), 1);
contract
}
#[ink::test]
fn construction_works() {
let accounts = default_accounts();
let owners = vec![accounts.alice, accounts.bob, accounts.eve];
let contract = build_contract();
assert_eq!(contract.owners.len(), 3);
assert_eq!(contract.requirement, 2);
assert!(contract.owners.iter().eq(owners.iter()));
assert!(contract.is_owner.get(&accounts.alice).is_some());
assert!(contract.is_owner.get(&accounts.bob).is_some());
assert!(contract.is_owner.get(&accounts.eve).is_some());
assert!(contract.is_owner.get(&accounts.charlie).is_none());
assert!(contract.is_owner.get(&accounts.django).is_none());
assert!(contract.is_owner.get(&accounts.frank).is_none());
assert_eq!(contract.transaction_list.transactions.len(), 0);
}
#[ink::test]
#[should_panic]
fn empty_owner_construction_fails() {
Multisig::new(0, vec![]);
}
#[ink::test]
#[should_panic]
fn zero_requirement_construction_fails() {
let accounts = default_accounts();
Multisig::new(0, vec![accounts.alice, accounts.bob]);
}
#[ink::test]
#[should_panic]
fn too_large_requirement_construction_fails() {
let accounts = default_accounts();
Multisig::new(3, vec![accounts.alice, accounts.bob]);
}
#[ink::test]
fn add_owner_works() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
let owners = contract.owners.len();
contract.add_owner(accounts.frank);
assert_eq!(contract.owners.len(), owners + 1);
assert!(contract.is_owner.get(&accounts.frank).is_some());
assert_eq!(test::recorded_events().count(), 1);
}
#[ink::test]
#[should_panic]
fn add_existing_owner_fails() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
contract.add_owner(accounts.bob);
}
#[ink::test]
#[should_panic]
fn add_owner_permission_denied() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_owner();
contract.add_owner(accounts.frank);
}
#[ink::test]
fn remove_owner_works() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
let owners = contract.owners.len();
contract.remove_owner(accounts.alice);
assert_eq!(contract.owners.len(), owners - 1);
assert!(contract.is_owner.get(&accounts.alice).is_none());
assert_eq!(test::recorded_events().count(), 1);
}
#[ink::test]
#[should_panic]
fn remove_owner_nonexisting_fails() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
contract.remove_owner(accounts.django);
}
#[ink::test]
#[should_panic]
fn remove_owner_permission_denied() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_owner();
contract.remove_owner(accounts.alice);
}
#[ink::test]
fn replace_owner_works() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
let owners = contract.owners.len();
contract.replace_owner(accounts.alice, accounts.django);
assert_eq!(contract.owners.len(), owners);
assert!(contract.is_owner.get(&accounts.alice).is_none());
assert!(contract.is_owner.get(&accounts.django).is_some());
assert_eq!(test::recorded_events().count(), 2);
}
#[ink::test]
#[should_panic]
fn replace_owner_existing_fails() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
contract.replace_owner(accounts.alice, accounts.bob);
}
#[ink::test]
#[should_panic]
fn replace_owner_nonexisting_fails() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_wallet();
contract.replace_owner(accounts.django, accounts.frank);
}
#[ink::test]
#[should_panic]
fn replace_owner_permission_denied() {
let accounts = default_accounts();
let mut contract = build_contract();
set_from_owner();
contract.replace_owner(accounts.alice, accounts.django);
}
#[ink::test]
fn change_requirement_works() {
let mut contract = build_contract();
assert_eq!(contract.requirement, 2);
set_from_wallet();
contract.change_requirement(3);
assert_eq!(contract.requirement, 3);
assert_eq!(test::recorded_events().count(), 1);
}
#[ink::test]
#[should_panic]
fn change_requirement_too_high() {
let mut contract = build_contract();
set_from_wallet();
contract.change_requirement(4);
}
#[ink::test]
#[should_panic]
fn change_requirement_zero_fails() {
let mut contract = build_contract();
set_from_wallet();
contract.change_requirement(0);
}
#[ink::test]
fn submit_transaction_works() {
submit_transaction();
}
#[ink::test]
#[should_panic]
fn submit_transaction_no_owner_fails() {
let mut contract = build_contract();
set_from_no_owner();
contract.submit_transaction(Transaction::change_requirement(1));
}
#[ink::test]
#[should_panic]
fn submit_transaction_wallet_fails() {
let mut contract = build_contract();
set_from_wallet();
contract.submit_transaction(Transaction::change_requirement(1));
}
#[ink::test]
fn cancel_transaction_works() {
let mut contract = submit_transaction();
set_from_wallet();
contract.cancel_transaction(0);
assert_eq!(contract.transaction_list.transactions.len(), 0);
assert_eq!(test::recorded_events().count(), 3);
}
#[ink::test]
fn cancel_transaction_nonexisting() {
let mut contract = submit_transaction();
set_from_wallet();
contract.cancel_transaction(1);
assert_eq!(contract.transaction_list.transactions.len(), 1);
assert_eq!(test::recorded_events().count(), 2);
}
#[ink::test]
#[should_panic]
fn cancel_transaction_no_permission() {
let mut contract = submit_transaction();
contract.cancel_transaction(0);
}
#[ink::test]
fn confirm_transaction_works() {
let mut contract = submit_transaction();