lib.rs 38.4 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
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
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Plain 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
//!
37
//! With the exception of `execute_transaction` no error conditions are signalled
38
39
40
41
42
//! through return types. Any error or invariant violation triggers a panic and therefore
//! rolls back the transaction.
//!
//! ## Interface
//!
43
//! The interface is modelled after the popular Gnosis multisig wallet. However, there
44
//! are subtle variations from the interface. For example the `confirm_transaction`
45
//! will never trigger the execution of a `Transaction` even if the threshold is reached.
46
47
48
49
//! 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
50
//! called by the wallet. For example, to add an owner you would submit a transaction
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! 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)]

72
73
74
75
76
pub use self::multisig_plain::{
    ConfirmationStatus,
    MultisigPlain,
    Transaction,
};
77
78
use ink_lang as ink;

79
#[ink::contract]
80
mod multisig_plain {
81
82
83
84
85
86
87
88
89
90
91
    use ink_env::call::{
        build_call,
        utils::ReturnType,
        ExecutionInput,
    };
    use ink_prelude::vec::Vec;
    use ink_storage::{
        collections::{
            HashMap as StorageHashMap,
            Stash as StorageStash,
            Vec as StorageVec,
92
        },
93
94
95
        traits::{
            PackedLayout,
            SpreadLayout,
96
        },
97
        Lazy,
98
99
100
101
102
103
104
105
106
107
108
109
    };
    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.
    ///
110
    /// We use this to pass the set of untyped (bytes) parameters to the `CallBuilder`.
111
112
113
    struct CallInput<'a>(&'a [u8]);

    impl<'a> scale::Encode for CallInput<'a> {
114
        fn encode_to<T: Output + ?Sized>(&self, dest: &mut T) {
115
116
117
118
119
            dest.write(self.0);
        }
    }

    /// Indicates whether a transaction is already confirmed or needs further confirmations.
120
121
122
    #[derive(scale::Encode, scale::Decode, Clone, Copy, SpreadLayout, PackedLayout)]
    #[cfg_attr(
        feature = "std",
123
        derive(scale_info::TypeInfo, ink_storage::traits::StorageLayout)
124
    )]
125
126
127
128
129
130
131
132
133
    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.
134
135
136
137
138
139
140
    #[derive(scale::Encode, scale::Decode, SpreadLayout, PackedLayout)]
    #[cfg_attr(
        feature = "std",
        derive(
            Debug,
            PartialEq,
            Eq,
141
            scale_info::TypeInfo,
142
            ink_storage::traits::StorageLayout
143
144
        )
    )]
145
    pub struct Transaction {
146
        /// The `AccountId` of the contract that is called in this transaction.
147
        pub callee: AccountId,
148
        /// The selector bytes that identifies the function of the callee that should be called.
149
        pub selector: [u8; 4],
150
        /// The SCALE encoded parameters that are passed to the called function.
151
        pub input: Vec<u8>,
152
        /// The amount of chain balance that is transferred to the callee.
153
        pub transferred_value: Balance,
154
        /// Gas limit for the execution of the call.
155
        pub gas_limit: u64,
156
157
    }

158
159
160
161
162
163
164
165
    /// 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,
    }

166
    #[ink(storage)]
167
    pub struct MultisigPlain {
168
        /// Every entry in this map represents the confirmation of an owner for a
169
        /// transaction. This is effectively a set rather than a map.
170
        confirmations: StorageHashMap<(TransactionId, AccountId), ()>,
171
172
173
        /// 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.
174
        confirmation_count: StorageHashMap<TransactionId, u32>,
175
176
        /// Just the list of transactions. It is a stash as stable ids are necessary
        /// for referencing them in confirmation calls.
177
        transactions: StorageStash<Transaction>,
178
179
        /// The list is a vector because iterating over it is necessary when cleaning
        /// up the confirmation set.
180
        owners: StorageVec<AccountId>,
181
        /// Redundant information to speed up the check whether a caller is an owner.
182
        is_owner: StorageHashMap<AccountId, ()>,
183
        /// Minimum number of owners that have to confirm a transaction to be executed.
184
        requirement: Lazy<u32>,
185
186
187
188
    }

    /// Emitted when an owner confirms a transaction.
    #[ink(event)]
189
    pub struct Confirmation {
190
191
192
193
194
195
196
197
198
199
200
201
202
        /// 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)]
203
    pub struct Revokation {
204
205
206
        /// The transaction that was revoked.
        #[ink(topic)]
        transaction: TransactionId,
207
        /// The owner that sent the revocation.
208
209
210
211
212
213
        #[ink(topic)]
        from: AccountId,
    }

    /// Emitted when an owner submits a transaction.
    #[ink(event)]
214
    pub struct Submission {
215
216
217
218
219
220
221
        /// The transaction that was submitted.
        #[ink(topic)]
        transaction: TransactionId,
    }

    /// Emitted when a transaction was canceled.
    #[ink(event)]
222
    pub struct Cancelation {
223
224
225
226
227
228
229
        /// The transaction that was canceled.
        #[ink(topic)]
        transaction: TransactionId,
    }

    /// Emitted when a transaction was executed.
    #[ink(event)]
230
    pub struct Execution {
231
232
233
234
235
236
237
        /// 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)]
238
        result: Result<Option<Vec<u8>>, Error>,
239
240
241
242
    }

    /// Emitted when an owner is added to the wallet.
    #[ink(event)]
243
    pub struct OwnerAddition {
244
245
246
247
248
249
250
        /// The owner that was added.
        #[ink(topic)]
        owner: AccountId,
    }

    /// Emitted when an owner is removed from the wallet.
    #[ink(event)]
251
    pub struct OwnerRemoval {
252
253
254
255
256
257
258
        /// The owner that was removed.
        #[ink(topic)]
        owner: AccountId,
    }

    /// Emitted when the requirement changed.
    #[ink(event)]
259
    pub struct RequirementChange {
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        /// The new requirement value.
        new_requirement: u32,
    }

    impl MultisigPlain {
        /// 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)]
274
        pub fn new(requirement: u32, owners: Vec<AccountId>) -> Self {
275
276
277
278
279
280
281
282
283
284
285
286
            let is_owner: StorageHashMap<_, _, _> =
                owners.iter().copied().map(|owner| (owner, ())).collect();
            let owners: StorageVec<_> = owners.iter().copied().collect();
            ensure_requirement_is_valid(owners.len(), requirement);
            assert!(is_owner.len() == owners.len());
            Self {
                confirmations: StorageHashMap::default(),
                confirmation_count: StorageHashMap::default(),
                transactions: StorageStash::default(),
                owners,
                is_owner,
                requirement: Lazy::new(requirement),
287
288
289
290
291
292
293
294
295
296
297
298
299
300
            }
        }

        /// 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
301
        /// `Transaction` and dispatched through `submit_transaction` and `invoke_transaction`:
302
        /// ```no_run
303
        /// use ink_env::{DefaultEnvironment as Env, AccountId, call::{CallParams, Selector}, test::CallData};
304
        /// use multisig_plain::{Transaction, ConfirmationStatus};
305
306
307
308
309
310
        ///
        /// // address of an existing MultiSigPlain contract
        /// let wallet_id: AccountId = [7u8; 32].into();
        ///
        /// // first create the transaction that adds `alice` through `add_owner`
        /// let alice: AccountId = [1u8; 32].into();
311
        /// let mut call = CallData::new(Selector::new([166, 229, 27, 154])); // add_owner
312
313
314
315
316
317
318
319
320
321
        /// call.push_arg(&alice);
        /// let transaction = Transaction {
        ///     callee: wallet_id,
        ///     selector: call.selector().to_bytes(),
        ///     input: call.params().to_owned(),
        ///     transferred_value: 0,
        ///     gas_limit: 0
        /// };
        ///
        /// // submit the transaction for confirmation
322
323
324
325
326
        /// let mut submit = CallParams::<Env, _, _>::eval(
        ///     wallet_id,
        ///     Selector::new([86, 244, 13, 223]) // submit_transaction
        /// );
        /// let (id, _): (u32, ConfirmationStatus)  = submit.push_arg(&transaction)
327
328
329
330
        ///     .fire()
        ///     .expect("submit_transaction won't panic.");
        ///
        /// // wait until all required owners have confirmed and then execute the transaction
331
332
333
334
        /// let mut invoke = CallParams::<Env, _, ()>::invoke(
        ///     wallet_id,
        ///     Selector::new([185, 50, 225, 236]) // invoke_transaction
        /// );
335
336
337
        /// invoke.push_arg(&id).fire();
        /// ```
        #[ink(message)]
338
        pub fn add_owner(&mut self, new_owner: AccountId) {
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
            self.ensure_from_wallet();
            self.ensure_no_owner(&new_owner);
            ensure_requirement_is_valid(self.owners.len() + 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)]
357
        pub fn remove_owner(&mut self, owner: AccountId) {
358
359
360
361
362
363
            self.ensure_from_wallet();
            self.ensure_owner(&owner);
            let len = self.owners.len() - 1;
            let requirement = u32::min(len, *self.requirement);
            ensure_requirement_is_valid(len, requirement);
            self.owners.swap_remove(self.owner_index(&owner));
364
            self.is_owner.take(&owner);
365
            Lazy::set(&mut self.requirement, requirement);
366
367
368
369
370
371
372
373
374
375
376
377
            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)]
378
        pub fn replace_owner(&mut self, old_owner: AccountId, new_owner: AccountId) {
379
380
381
            self.ensure_from_wallet();
            self.ensure_owner(&old_owner);
            self.ensure_no_owner(&new_owner);
382
383
384
            let owner_index = self.owner_index(&old_owner);
            self.owners[owner_index] = new_owner;
            self.is_owner.take(&old_owner);
385
386
387
388
389
390
391
392
393
394
395
396
397
398
            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)]
399
        pub fn change_requirement(&mut self, new_requirement: u32) {
400
401
            self.ensure_from_wallet();
            ensure_requirement_is_valid(self.owners.len(), new_requirement);
402
            Lazy::set(&mut self.requirement, new_requirement);
403
404
405
            self.env().emit_event(RequirementChange { new_requirement });
        }

406
        /// Add a new transaction candidate to the contract.
407
408
409
        ///
        /// This also confirms the transaction for the caller. This can be called by any owner.
        #[ink(message)]
410
        pub fn submit_transaction(
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
            &mut self,
            transaction: Transaction,
        ) -> (TransactionId, ConfirmationStatus) {
            self.ensure_caller_is_owner();
            let trans_id = self.transactions.put(transaction);
            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)]
432
        pub fn cancel_transaction(&mut self, trans_id: TransactionId) {
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
            self.ensure_from_wallet();
            if self.take_transaction(trans_id).is_some() {
                self.env().emit_event(Cancelation {
                    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)]
449
450
451
452
        pub fn confirm_transaction(
            &mut self,
            trans_id: TransactionId,
        ) -> ConfirmationStatus {
453
454
455
456
457
458
459
460
461
462
463
464
465
            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)]
466
        pub fn revoke_confirmation(&mut self, trans_id: TransactionId) {
467
468
            self.ensure_caller_is_owner();
            let caller = self.env().caller();
469
            if self.confirmations.take(&(trans_id, caller)).is_some() {
470
471
472
473
474
475
476
477
                self.confirmation_count
                    .entry(trans_id)
                    .and_modify(|v| {
                        if *v > 0 {
                            *v -= 1;
                        }
                    })
                    .or_insert(1);
478
479
480
481
482
483
484
485
486
                self.env().emit_event(Revokation {
                    transaction: trans_id,
                    from: caller,
                });
            }
        }

        /// Invoke a confirmed execution without getting its output.
        ///
487
488
489
490
        /// 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.
        ///
491
492
        /// Its return value indicates whether the called transaction was successful.
        /// This can be called by anyone.
493
        #[ink(message, payable)]
494
495
496
497
        pub fn invoke_transaction(
            &mut self,
            trans_id: TransactionId,
        ) -> Result<(), Error> {
498
499
            self.ensure_confirmed(trans_id);
            let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID);
500
            assert!(self.env().transferred_balance() == t.transferred_value);
501
502
503
504
505
506
507
508
509
            let result = build_call::<<Self as ::ink_lang::ContractEnv>::Env>()
                .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()
510
                .map_err(|_| Error::TransactionFailed);
511
512
513
514
515
516
517
518
519
520
            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
521
        /// its output when successful.
522
523
        /// This can be called by anyone.
        #[ink(message)]
524
525
526
        pub fn eval_transaction(
            &mut self,
            trans_id: TransactionId,
527
        ) -> Result<Vec<u8>, Error> {
528
529
            self.ensure_confirmed(trans_id);
            let t = self.take_transaction(trans_id).expect(WRONG_TRANSACTION_ID);
530
531
532
533
534
535
536
537
538
            let result = build_call::<<Self as ::ink_lang::ContractEnv>::Env>()
                .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::<ReturnType<Vec<u8>>>()
                .fire()
539
                .map_err(|_| Error::TransactionFailed);
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
            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 {
555
            let count = self.confirmation_count.entry(transaction).or_insert(0);
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
            let new_confirmation = self
                .confirmations
                .insert((transaction, confirmer), ())
                .is_none();
            if new_confirmation {
                *count += 1;
            }
            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.take(trans_id);
            if transaction.is_some() {
                self.clean_transaction_confirmations(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) {
602
            use ::ink_storage::collections::stash::Entry as StashEntry;
603
604
605
606
607
608
609
610
611
612
613
614
            for (trans_id, _) in
                self.transactions
                    .entries()
                    .enumerate()
                    .filter_map(|(n, entry)| {
                        match entry {
                            StashEntry::Vacant(_) => None,
                            StashEntry::Occupied(value) => Some((n as u32, value)),
                        }
                    })
            {
                if self.confirmations.take(&(trans_id, *owner)).is_some() {
615
                    *self.confirmation_count.entry(trans_id).or_insert(0) += 1;
616
617
618
619
620
621
622
                }
            }
        }

        /// This removes all confirmation state associated with `transaction`.
        fn clean_transaction_confirmations(&mut self, transaction: TransactionId) {
            for owner in self.owners.iter() {
623
                self.confirmations.take(&(transaction, *owner));
624
            }
625
            self.confirmation_count.take(&transaction);
626
627
628
629
630
631
632
633
634
        }

        /// 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)
635
                    >= &self.requirement
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
            );
        }

        /// 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.contains_key(owner));
        }

        /// Panic if `owner` is an owner.
        fn ensure_no_owner(&self, owner: &AccountId) {
            assert!(!self.is_owner.contains_key(owner));
        }
    }

    /// 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::*;
674
        use ink_env::{
675
676
677
            call,
            test,
        };
678
        use ink_lang as ink;
679
        type Accounts = test::DefaultAccounts<Environment>;
680
681
682
683
        const WALLET: [u8; 32] = [7; 32];

        impl Transaction {
            fn change_requirement(requirement: u32) -> Self {
684
                let mut call = test::CallData::new(call::Selector::new([0x00; 4])); // change_requirement
685
686
687
688
689
690
691
692
693
694
695
696
                call.push_arg(&requirement);
                Self {
                    callee: WALLET.into(),
                    selector: call.selector().to_bytes(),
                    input: call.params().to_owned(),
                    transferred_value: 0,
                    gas_limit: 1000000,
                }
            }
        }

        fn set_sender(sender: AccountId) {
697
            test::push_execution_context::<Environment>(
698
699
700
701
                sender,
                WALLET.into(),
                1000000,
                1000000,
702
                test::CallData::new(call::Selector::new([0x00; 4])), // dummy
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
            );
        }

        fn set_from_wallet() {
            set_sender(WALLET.into());
        }

        fn set_from_owner() {
            let accounts = default_accounts();
            set_sender(accounts.alice);
        }

        fn set_from_noowner() {
            let accounts = default_accounts();
            set_sender(accounts.django);
        }

        fn default_accounts() -> Accounts {
            test::default_accounts()
                .expect("Test environment is expected to be initialized.")
        }

        fn build_contract() -> MultisigPlain {
            let accounts = default_accounts();
            let owners = ink_prelude::vec![accounts.alice, accounts.bob, accounts.eve];
            MultisigPlain::new(2, owners)
        }

        fn submit_transaction() -> MultisigPlain {
            let mut contract = build_contract();
            let accounts = default_accounts();
            set_from_owner();
            contract.submit_transaction(Transaction::change_requirement(1));
            assert_eq!(contract.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.confirmations.len(), 1);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1);
            contract
        }

746
        #[ink::test]
747
748
749
750
751
752
        fn construction_works() {
            let accounts = default_accounts();
            let owners = ink_prelude::vec![accounts.alice, accounts.bob, accounts.eve];
            let contract = build_contract();

            assert_eq!(contract.owners.len(), 3);
753
            assert_eq!(*contract.requirement, 2);
754
755
756
757
758
759
760
761
762
763
764
765
            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.confirmations.len(), 0);
            assert_eq!(contract.confirmation_count.len(), 0);
            assert_eq!(contract.transactions.len(), 0);
        }

766
        #[ink::test]
767
768
769
770
771
        #[should_panic]
        fn empty_owner_construction_fails() {
            MultisigPlain::new(0, vec![]);
        }

772
        #[ink::test]
773
774
775
776
777
778
        #[should_panic]
        fn zero_requirement_construction_fails() {
            let accounts = default_accounts();
            MultisigPlain::new(0, vec![accounts.alice, accounts.bob]);
        }

779
        #[ink::test]
780
781
782
783
784
785
        #[should_panic]
        fn too_large_requirement_construction_fails() {
            let accounts = default_accounts();
            MultisigPlain::new(3, vec![accounts.alice, accounts.bob]);
        }

786
        #[ink::test]
787
788
789
790
791
792
793
794
795
796
797
        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);
        }

798
        #[ink::test]
799
800
801
802
803
804
805
806
        #[should_panic]
        fn add_existing_owner_fails() {
            let accounts = default_accounts();
            let mut contract = build_contract();
            set_from_wallet();
            contract.add_owner(accounts.bob);
        }

807
        #[ink::test]
808
809
810
811
812
813
814
815
        #[should_panic]
        fn add_owner_permission_denied() {
            let accounts = default_accounts();
            let mut contract = build_contract();
            set_from_owner();
            contract.add_owner(accounts.frank);
        }

816
        #[ink::test]
817
818
819
820
821
822
823
824
825
826
827
        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);
        }

828
        #[ink::test]
829
830
831
832
833
834
835
836
        #[should_panic]
        fn remove_owner_nonexisting_fails() {
            let accounts = default_accounts();
            let mut contract = build_contract();
            set_from_wallet();
            contract.remove_owner(accounts.django);
        }

837
        #[ink::test]
838
839
840
841
842
843
844
845
        #[should_panic]
        fn remove_owner_permission_denied() {
            let accounts = default_accounts();
            let mut contract = build_contract();
            set_from_owner();
            contract.remove_owner(accounts.alice);
        }

846
        #[ink::test]
847
848
849
850
851
852
853
854
855
856
857
858
        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);
        }

859
        #[ink::test]
860
861
862
863
864
865
866
867
        #[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);
        }

868
        #[ink::test]
869
870
871
872
873
874
875
876
        #[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);
        }

877
        #[ink::test]
878
879
880
881
882
883
884
885
        #[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);
        }

886
        #[ink::test]
887
888
        fn change_requirement_works() {
            let mut contract = build_contract();
889
            assert_eq!(*contract.requirement, 2);
890
891
            set_from_wallet();
            contract.change_requirement(3);
892
            assert_eq!(*contract.requirement, 3);
893
894
895
            assert_eq!(test::recorded_events().count(), 1);
        }

896
        #[ink::test]
897
898
899
900
901
902
903
        #[should_panic]
        fn change_requirement_too_high() {
            let mut contract = build_contract();
            set_from_wallet();
            contract.change_requirement(4);
        }

904
        #[ink::test]
905
906
907
908
909
910
911
        #[should_panic]
        fn change_requirement_zero_fails() {
            let mut contract = build_contract();
            set_from_wallet();
            contract.change_requirement(0);
        }

912
        #[ink::test]
913
914
915
916
        fn submit_transaction_works() {
            submit_transaction();
        }

917
        #[ink::test]
918
919
920
921
922
923
924
        #[should_panic]
        fn submit_transaction_noowner_fails() {
            let mut contract = build_contract();
            set_from_noowner();
            contract.submit_transaction(Transaction::change_requirement(1));
        }

925
        #[ink::test]
926
927
928
929
930
931
932
        #[should_panic]
        fn submit_transaction_wallet_fails() {
            let mut contract = build_contract();
            set_from_wallet();
            contract.submit_transaction(Transaction::change_requirement(1));
        }

933
        #[ink::test]
934
935
936
937
938
939
940
941
        fn cancel_transaction_works() {
            let mut contract = submit_transaction();
            set_from_wallet();
            contract.cancel_transaction(0);
            assert_eq!(contract.transactions.len(), 0);
            assert_eq!(test::recorded_events().count(), 3);
        }

942
        #[ink::test]
943
944
945
946
947
948
949
950
        fn cancel_transaction_nonexisting() {
            let mut contract = submit_transaction();
            set_from_wallet();
            contract.cancel_transaction(1);
            assert_eq!(contract.transactions.len(), 1);
            assert_eq!(test::recorded_events().count(), 2);
        }

951
        #[ink::test]
952
953
954
955
956
957
        #[should_panic]
        fn cancel_transaction_no_permission() {
            let mut contract = submit_transaction();
            contract.cancel_transaction(0);
        }

958
        #[ink::test]
959
960
961
962
963
964
965
966
967
968
969
        fn confirm_transaction_works() {
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            set_sender(accounts.bob);
            contract.confirm_transaction(0);
            assert_eq!(test::recorded_events().count(), 3);
            contract.confirmations.get(&(0, accounts.bob)).unwrap();
            assert_eq!(contract.confirmations.len(), 2);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 2);
        }

970
        #[ink::test]
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
        fn revoke_confirmations() {
            // given
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            // Confirm by Bob
            set_sender(accounts.bob);
            contract.confirm_transaction(0);
            // Confirm by Eve
            set_sender(accounts.eve);
            contract.confirm_transaction(0);
            assert_eq!(contract.confirmations.len(), 3);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 3);
            // Revoke from Eve
            contract.revoke_confirmation(0);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 2);
            // Revoke from Bob
            set_sender(accounts.bob);
            contract.revoke_confirmation(0);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1);
        }

992
        #[ink::test]
993
994
995
996
997
998
999
1000
1001
1002
1003
        fn confirm_transaction_already_confirmed() {
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            set_sender(accounts.alice);
            contract.confirm_transaction(0);
            assert_eq!(test::recorded_events().count(), 2);
            contract.confirmations.get(&(0, accounts.alice)).unwrap();
            assert_eq!(contract.confirmations.len(), 1);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1);
        }

1004
        #[ink::test]
1005
1006
1007
1008
1009
1010
1011
        #[should_panic]
        fn confirm_transaction_noowner_fail() {
            let mut contract = submit_transaction();
            set_from_noowner();
            contract.confirm_transaction(0);
        }

1012
        #[ink::test]
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
        fn revoke_transaction_works() {
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            set_sender(accounts.alice);
            contract.revoke_confirmation(0);
            assert_eq!(test::recorded_events().count(), 3);
            assert!(contract.confirmations.get(&(0, accounts.alice)).is_none());
            assert_eq!(contract.confirmations.len(), 0);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 0);
        }

1024
        #[ink::test]
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
        fn revoke_transaction_no_confirmer() {
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            set_sender(accounts.bob);
            contract.revoke_confirmation(0);
            assert_eq!(test::recorded_events().count(), 2);
            assert!(contract.confirmations.get(&(0, accounts.alice)).is_some());
            assert_eq!(contract.confirmations.len(), 1);
            assert_eq!(*contract.confirmation_count.get(&0).unwrap(), 1);
        }

1036
        #[ink::test]
1037
1038
1039
1040
1041
1042
1043
1044
        #[should_panic]
        fn revoke_transaction_noowner_fail() {
            let mut contract = submit_transaction();
            let accounts = default_accounts();
            set_sender(accounts.django);
            contract.revoke_confirmation(0);
        }

1045
        #[ink::test]
1046
1047
1048
1049
1050
1051
        fn execute_transaction_works() {
            // Execution of calls is currently unsupported in off-chain test.
            // Calling execute_transaction panics in any case.
        }
    }
}