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
//! Simple multi-signature wallet component. Generic over approvable actions.
//! Use with NativeTransactionAction for multisig over native transactions.

use std::marker::PhantomData;

use near_sdk::{
    borsh::{self, BorshDeserialize, BorshSerialize},
    env, AccountId,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::{ActionRequest, ApprovalConfiguration};

/// Check which accounts are eligible to submit approvals to an
/// [ApprovalManager](super::ApprovalManager)
pub trait AccountAuthorizer {
    /// Why can this account not be authorized?
    type AuthorizationError;

    /// Determines whether an account ID is allowed to submit an approval
    fn is_account_authorized(account_id: &AccountId) -> Result<(), Self::AuthorizationError>;
}

/// M (threshold) of N approval scheme
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Clone, Debug)]
pub struct Configuration<Au: AccountAuthorizer> {
    /// How many approvals are required?
    pub threshold: u8,
    /// A request cannot be executed, and can be deleted by any
    /// approval-eligible member after this period has elapsed.
    /// 0 = perpetual validity, no deletion
    pub validity_period_nanoseconds: u64,
    #[borsh_skip]
    #[serde(skip)]
    _authorizer: PhantomData<Au>,
}

impl<Au: AccountAuthorizer> Configuration<Au> {
    /// Create an approval scheme with the given threshold
    pub fn new(threshold: u8, validity_period_nanoseconds: u64) -> Self {
        Self {
            threshold,
            validity_period_nanoseconds,
            _authorizer: PhantomData,
        }
    }

    /// Is the given approval state still considered valid?
    pub fn is_within_validity_period(&self, approval_state: &ApprovalState) -> bool {
        if self.validity_period_nanoseconds == 0 {
            true
        } else {
            env::block_timestamp()
                .checked_sub(approval_state.created_at_nanoseconds)
                .unwrap() // inconsistent state if a request timestamp is in the future
                < self.validity_period_nanoseconds
        }
    }
}

/// Approval state for simple multisig
#[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize, Debug)]
pub struct ApprovalState {
    /// List of accounts that have approved an action thus far
    pub approved_by: Vec<AccountId>,
    /// Network timestamp when the request was created
    pub created_at_nanoseconds: u64,
}

impl Default for ApprovalState {
    fn default() -> Self {
        Self::new()
    }
}

impl ApprovalState {
    /// Creates an ApprovalState with the current network timestamp
    pub fn new() -> Self {
        Self {
            approved_by: Vec::new(),
            created_at_nanoseconds: env::block_timestamp(),
        }
    }
}

/// If a request has expired, some actions may not be performed
#[derive(Error, Clone, Debug)]
#[error("Validity period exceeded")]
pub struct RequestExpiredError;

/// Why might a simple multisig approval attempt fail?
#[derive(Error, Clone, Debug)]
pub enum ApprovalError {
    /// The account has already approved this action request
    #[error("Already approved by this account")]
    AlreadyApprovedByAccount,
    /// The request has expired and cannot be approved or executed
    #[error(transparent)]
    RequestExpired(#[from] RequestExpiredError),
}

/// Errors when evaluating a request for execution
#[derive(Error, Clone, Debug)]
pub enum ExecutionEligibilityError {
    /// The request does not have enough approvals
    #[error("Insufficient approvals on request: required {required} but only has {current}")]
    InsufficientApprovals {
        /// Current number of approvals
        current: usize,
        /// Required number of approvals
        required: usize,
    },
    /// The request has expired and cannot be approved or executed
    #[error(transparent)]
    RequestExpired(#[from] RequestExpiredError),
}

/// What errors may occur when removing a request?
#[derive(Error, Clone, Debug)]
pub enum RemovalError {
    /// Requests may not be removed while they are still valid
    #[error("Removal prohibited before expiration")]
    RequestStillValid,
}

impl<Au, Ac> ApprovalConfiguration<Ac, ApprovalState> for Configuration<Au>
where
    Au: AccountAuthorizer,
{
    type ApprovalError = ApprovalError;
    type RemovalError = RemovalError;
    type AuthorizationError = Au::AuthorizationError;
    type ExecutionEligibilityError = ExecutionEligibilityError;

    fn is_approved_for_execution(
        &self,
        action_request: &ActionRequest<Ac, ApprovalState>,
    ) -> Result<(), ExecutionEligibilityError> {
        if !self.is_within_validity_period(&action_request.approval_state) {
            return Err(RequestExpiredError.into());
        }

        let current = action_request.approval_state.approved_by.len();
        let required = self.threshold as usize;

        if current < required {
            return Err(ExecutionEligibilityError::InsufficientApprovals { current, required });
        }

        Ok(())
    }

    fn is_removable(
        &self,
        action_request: &ActionRequest<Ac, ApprovalState>,
    ) -> Result<(), Self::RemovalError> {
        if self.is_within_validity_period(&action_request.approval_state) {
            Err(RemovalError::RequestStillValid)
        } else {
            Ok(())
        }
    }

    fn is_account_authorized(
        &self,
        account_id: &AccountId,
        _action_request: &ActionRequest<Ac, ApprovalState>,
    ) -> Result<(), Self::AuthorizationError> {
        Au::is_account_authorized(account_id)
    }

    fn try_approve_with_authorized_account(
        &self,
        account_id: AccountId,
        action_request: &mut ActionRequest<Ac, ApprovalState>,
    ) -> Result<(), Self::ApprovalError> {
        if !self.is_within_validity_period(&action_request.approval_state) {
            return Err(RequestExpiredError.into());
        }

        if action_request
            .approval_state
            .approved_by
            .contains(&account_id)
        {
            return Err(ApprovalError::AlreadyApprovedByAccount);
        }

        action_request.approval_state.approved_by.push(account_id);

        Ok(())
    }
}

/// Types used by near-contract-tools-macros
pub mod macro_types {
    use thiserror::Error;

    /// Account that attempted an action is missing a role
    #[derive(Error, Clone, Debug)]
    #[error("Missing role '{0}' required for this action")]
    pub struct MissingRole<R>(pub R);
}

#[cfg(test)]
mod tests {
    use near_sdk::{
        borsh::{self, BorshDeserialize, BorshSerialize},
        env, near_bindgen,
        test_utils::VMContextBuilder,
        testing_env, AccountId, BorshStorageKey,
    };
    use thiserror::Error;

    use crate::{
        approval::{
            simple_multisig::{AccountAuthorizer, ApprovalState, Configuration},
            ApprovalManager,
        },
        rbac::Rbac,
        slot::Slot,
        Rbac,
    };

    #[derive(BorshSerialize, BorshDeserialize)]
    enum Action {
        SayHello,
        SayGoodbye,
    }

    impl crate::approval::Action<Contract> for Action {
        type Output = &'static str;

        fn execute(self, _contract: &mut Contract) -> Self::Output {
            match self {
                Self::SayHello => "hello",
                Self::SayGoodbye => "goodbye",
            }
        }
    }

    #[derive(BorshSerialize, BorshStorageKey)]
    enum Role {
        Multisig,
    }

    #[derive(Rbac, Debug, BorshSerialize, BorshDeserialize)]
    #[rbac(roles = "Role", crate = "crate")]
    #[near_bindgen]
    struct Contract {}

    impl ApprovalManager<Action, ApprovalState, Configuration<Self>> for Contract {
        fn root() -> Slot<()> {
            Slot::new(b"m")
        }
    }

    #[derive(Error, Clone, Debug)]
    #[error("Missing role: {0}")]
    struct MissingRole(&'static str);

    impl AccountAuthorizer for Contract {
        type AuthorizationError = MissingRole;

        fn is_account_authorized(account_id: &near_sdk::AccountId) -> Result<(), MissingRole> {
            if Self::has_role(account_id, &Role::Multisig) {
                Ok(())
            } else {
                Err(MissingRole("Multisig"))
            }
        }
    }

    #[near_bindgen]
    impl Contract {
        #[init]
        pub fn new() -> Self {
            <Self as ApprovalManager<_, _, _>>::init(Configuration::new(2, 10000));
            Self {}
        }

        pub fn obtain_multisig_permission(&mut self) {
            self.add_role(env::predecessor_account_id(), &Role::Multisig);
        }

        pub fn create(&mut self, say_hello: bool) -> u32 {
            let action = if say_hello {
                Action::SayHello
            } else {
                Action::SayGoodbye
            };

            self.create_request(action, ApprovalState::new()).unwrap()
        }

        pub fn approve(&mut self, request_id: u32) {
            self.approve_request(request_id).unwrap();
        }

        pub fn execute(&mut self, request_id: u32) -> &'static str {
            self.execute_request(request_id).unwrap()
        }

        pub fn remove(&mut self, request_id: u32) {
            self.remove_request(request_id).unwrap()
        }
    }

    fn predecessor(account_id: &AccountId) {
        let mut context = VMContextBuilder::new();
        context.predecessor_account_id(account_id.clone());
        testing_env!(context.build());
    }

    #[test]
    fn successful_approval() {
        let alice: AccountId = "alice".parse().unwrap();
        let bob: AccountId = "bob_acct".parse().unwrap();
        let charlie: AccountId = "charlie".parse().unwrap();

        let mut contract = Contract::new();

        predecessor(&alice);
        contract.obtain_multisig_permission();
        predecessor(&bob);
        contract.obtain_multisig_permission();
        predecessor(&charlie);
        contract.obtain_multisig_permission();

        let request_id = contract.create(true);

        assert_eq!(request_id, 0);
        assert!(Contract::is_approved_for_execution(request_id).is_err());

        predecessor(&alice);
        contract.approve(request_id);

        assert!(Contract::is_approved_for_execution(request_id).is_err());

        predecessor(&charlie);
        contract.approve(request_id);

        assert!(Contract::is_approved_for_execution(request_id).is_ok());

        predecessor(&bob);
        contract.approve(request_id);

        assert!(Contract::is_approved_for_execution(request_id).is_ok());

        assert_eq!(contract.execute(request_id), "hello");
    }

    #[test]
    fn successful_removal() {
        let alice: AccountId = "alice".parse().unwrap();

        let mut contract = Contract::new();

        predecessor(&alice);
        contract.obtain_multisig_permission();

        let request_id = contract.create(true);

        contract.approve(request_id);

        let created_at = Contract::get_request(request_id)
            .unwrap()
            .approval_state
            .created_at_nanoseconds;

        let mut context = VMContextBuilder::new();
        context
            .predecessor_account_id(alice)
            .block_timestamp(created_at + 10000);
        testing_env!(context.build());

        contract.remove(request_id);
    }

    #[test]
    #[should_panic = "RemovalNotAllowed"]
    fn unsuccessful_removal_not_expired() {
        let alice: AccountId = "alice".parse().unwrap();

        let mut contract = Contract::new();

        predecessor(&alice);
        contract.obtain_multisig_permission();

        let request_id = contract.create(true);

        contract.approve(request_id);

        let created_at = Contract::get_request(request_id)
            .unwrap()
            .approval_state
            .created_at_nanoseconds;

        let mut context = VMContextBuilder::new();
        context
            .predecessor_account_id(alice)
            .block_timestamp(created_at + 9999);
        testing_env!(context.build());

        contract.remove(request_id);
    }

    #[test]
    #[should_panic = "UnauthorizedAccount"]
    fn unsuccessful_removal_no_permission() {
        let alice: AccountId = "alice".parse().unwrap();
        let bob: AccountId = "bob_acct".parse().unwrap();

        let mut contract = Contract::new();

        predecessor(&alice);
        contract.obtain_multisig_permission();

        let request_id = contract.create(true);

        contract.approve(request_id);

        let created_at = Contract::get_request(request_id)
            .unwrap()
            .approval_state
            .created_at_nanoseconds;

        let mut context = VMContextBuilder::new();
        context
            .predecessor_account_id(bob)
            .block_timestamp(created_at + 10000);
        testing_env!(context.build());

        contract.remove(request_id);
    }
}