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
use eosio::*;
use eosio_cdt::*;
use std::marker::PhantomData;

#[eosio::table("proposal")]
pub struct Proposal {
    #[eosio(primary_key)]
    pub proposal_name: Name,
    pub packed_transaction: Vec<u8>,
}

#[eosio::table("approvals")]
pub struct OldApprovalsInfo {
    #[eosio(primary_key)]
    pub proposal_name: Name,
    pub requested_approvals: Vec<PermissionLevel>,
    pub provided_approvals: Vec<PermissionLevel>,
}

#[eosio::table("approvals2")]
pub struct ApprovalsInfo {
    pub version: u8,
    #[eosio(primary_key)]
    pub proposal_name: Name,
    /// requested approval doesn't need to cointain time, but we want requested
    /// approval to be of exact the same size ad provided approval, in this
    /// case approve/unapprove doesn't change serialized data size. So, we
    /// use the same type.
    pub requested_approvals: Vec<Approval>,
    pub provided_approvals: Vec<Approval>,
}

#[derive(
    Read, Write, NumBytes, Default, Clone, PartialEq, PartialOrd, Debug,
)]
pub struct Approval {
    pub level: PermissionLevel,
    pub time: TimePoint,
}

#[eosio::table("invals")]
pub struct Invalidation {
    #[eosio(primary_key)]
    pub account: AccountName,
    pub last_invalidation_time: TimePoint,
}

/// Create proposal
///
/// Creates a proposal containing one transaction.
/// Allows an account `proposer` to make a proposal `proposal_name` which has
/// `requested` permission levels expected to approve the proposal, and if
/// approved by all expected permission levels then `trx` transaction can we
/// executed by this proposal. The `proposer` account is authorized and the
/// `trx` transaction is verified if it was authorized by the provided keys and
/// permissions, and if the proposal name doesn’t already exist; if all
/// validations pass the `proposal_name` and `trx` trasanction are saved in the
/// proposals table and the `requested` permission levels to the approvals table
/// (for the `proposer` context). Storage changes are billed to `proposer`.
///
/// - `proposer` - The account proposing a transaction
/// - `proposal_name` - The name of the proposal (should be unique for proposer)
/// - `requested` - Permission levels expected to approve the proposal
/// - `trx` - Proposed transaction
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L9-L57)
#[eosio::action]
pub fn propose(
    _proposer: PhantomData<AccountName>,
    _proposal_name: PhantomData<Name>,
    _requested: PhantomData<Vec<PermissionLevel>>,
    _trx: PhantomData<Transaction>,
) {
    let mut ds = current_data_stream();
    let proposer: AccountName = ds.read().expect("read");
    let proposal_name: Name = ds.read().expect("read");
    let requested: Vec<PermissionLevel> = ds.read().expect("read");
    let packed_transaction = ds.as_remaining_bytes().expect("read");
    let trx_header =
        TransactionHeader::unpack(&packed_transaction).expect("read");

    require_auth(proposer);
    assert!(
        trx_header.expiration >= current_time_point_sec(),
        "transaction expired"
    );

    let this = current_receiver();
    let proposals = Proposal::table(this, proposer);
    assert!(
        proposals.find(proposal_name).is_none(),
        "proposal with the same name exists"
    );

    let has_trx_auth =
        has_transaction_authority_bytes(&packed_transaction, &[], &requested)
            .expect("write");
    assert!(has_trx_auth, "transaction authorization failed");

    let proposal = Proposal {
        proposal_name,
        packed_transaction: packed_transaction.to_vec(),
    };
    proposals.emplace(proposer, proposal).expect("write");

    let approvals = ApprovalsInfo::table(this, proposer);
    let approval = ApprovalsInfo {
        version: 1,
        proposal_name,
        requested_approvals: requested
            .into_iter()
            .map(|level| Approval {
                level,
                time: TimePoint::default(),
            })
            .collect(),
        provided_approvals: Vec::new(),
    };
    approvals.emplace(proposer, approval).expect("write");
}

/// Approve proposal
///
/// Approves an existing proposal
/// Allows an account, the owner of `level` permission, to approve a proposal
/// `proposal_name` proposed by `proposer`. If the proposal's requested approval
/// list contains the `level` permission then the `level` permission is moved
/// from internal `requested_approvals` list to internal `provided_approvals`
/// list of the proposal, thus persisting the approval for the `proposal_name`
/// proposal. Storage changes are billed to `proposer`.
///
/// - `proposer` - The account proposing a transaction
/// - `proposal_name` - The name of the proposal (should be unique for proposer)
/// - `level` - Permission level approving the transaction
/// - `proposal_hash` - Transaction's checksum
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L59-L92)
#[eosio::action]
pub fn approve(
    proposer: AccountName,
    proposal_name: Name,
    level: PermissionLevel,
    proposal_hash: BinaryExtension<Checksum256>,
) {
    require_level(level);
    let this = current_receiver();

    if let Some(proposal_hash) = proposal_hash.as_value() {
        let proposals = Proposal::table(this, proposer);
        let proposal = proposals
            .find(proposal_name)
            .expect("proposal not found")
            .get()
            .expect("read");
        assert_sha256(proposal_hash, proposal.packed_transaction);
    }

    let approvals = ApprovalsInfo::table(this, proposer);

    if let Some(cursor) = approvals.find(proposal_name) {
        let mut approval = cursor.get().expect("read");
        let (mut provided, requested): (Vec<_>, Vec<_>) = approval
            .requested_approvals
            .into_iter()
            .partition(|a| a.level == level);
        let mut provided = provided
            .pop()
            .expect("approval is not on the list of requested approvals");
        provided.time = current_time_point();
        approval.provided_approvals.push(provided);
        approval.requested_approvals = requested;
        cursor.modify(Payer::Same, approval).expect("write");
    } else {
        let old_approvals = OldApprovalsInfo::table(this, proposer);
        let cursor = old_approvals
            .find(proposal_name)
            .expect("proposal not found");
        let mut old_approval = cursor.get().expect("read");
        let (mut provided, requested): (Vec<_>, Vec<_>) = old_approval
            .requested_approvals
            .into_iter()
            .partition(|a| a == &level);
        let provided = provided
            .pop()
            .expect("approval is not on the list of requested approvals");
        old_approval.provided_approvals.push(provided);
        old_approval.requested_approvals = requested;
        cursor.modify(Payer::Same, old_approval).expect("write");
    }
}

/// Revoke proposal
///
/// Revokes an existing proposal
/// This action is the reverse of the `approve` action: if all validations pass
/// the `level` permission is erased from internal `provided_approvals` and
/// added to the internal `requested_approvals` list, and thus un-approve or
/// revoke the proposal.
///
/// - `proposer` - The account proposing a transaction
/// - `proposal_name` - The name of the proposal (should be an existing
///   proposal)
/// - `level` - Permission level revoking approval for proposal
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L94-L116)
#[eosio::action]
pub fn unapprove(
    proposer: AccountName,
    proposal_name: Name,
    level: PermissionLevel,
) {
    require_level(level);
    let this = current_receiver();

    let approvals = ApprovalsInfo::table(this, proposer);
    if let Some(cursor) = approvals.find(proposal_name) {
        let mut approval = cursor.get().expect("read");
        let (mut requested, provided): (Vec<_>, Vec<_>) = approval
            .provided_approvals
            .into_iter()
            .partition(|a| a.level == level);
        let requested =
            requested.pop().expect("no approval previously granted");
        approval.requested_approvals.push(requested);
        approval.provided_approvals = provided;
        cursor.modify(Payer::Same, approval).expect("write");
    } else {
        let old_approvals = OldApprovalsInfo::table(this, proposer);
        let cursor = old_approvals
            .find(proposal_name)
            .expect("proposal not found");
        let mut old_approval = cursor.get().expect("read");
        let (mut requested, provided): (Vec<_>, Vec<_>) = old_approval
            .provided_approvals
            .into_iter()
            .partition(|a| a == &level);
        let requested =
            requested.pop().expect("no approval previously granted");
        old_approval.requested_approvals.push(requested);
        old_approval.provided_approvals = provided;
        cursor.modify(Payer::Same, old_approval).expect("write");
    }
}

/// Cancel proposal
///
/// Cancels an existing proposal
///
/// - `proposer` - The account proposing a transaction
/// - `proposal_name` - The name of the proposal (should be an existing
///   proposal)
/// - `canceler` - The account cancelling the proposal (only the proposer can
///   cancel an unexpired transaction, and the canceler has to be different than
///   the proposer)
///
/// Allows the `canceler` account to cancel the `proposal_name` proposal,
/// created by a `proposer`, only after time has expired on the proposed
/// transaction. It removes corresponding entries from internal proptable and
/// from approval (or old approvals) tables as well.
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L118-L140)
#[eosio::action]
pub fn cancel(
    proposer: AccountName,
    proposal_name: Name,
    canceler: AccountName,
) {
    require_auth(canceler);

    let this = current_receiver();

    let proposals = Proposal::table(this, proposer);
    let cursor = proposals.find(proposal_name).expect("proposal not found");
    let proposal = cursor.get().expect("read");

    if canceler != proposer {
        let trx_header = TransactionHeader::unpack(proposal.packed_transaction)
            .expect("read");
        assert!(
            trx_header.expiration < current_time_point_sec(),
            "cannot cancel until expiration"
        );
    }

    cursor.erase().expect("read");

    let approvals = ApprovalsInfo::table(this, proposer);
    if let Some(cursor) = approvals.find(proposal_name) {
        cursor.erase().expect("read");
    } else {
        let old_approvals = OldApprovalsInfo::table(this, proposer);
        let cursor = old_approvals
            .find(proposal_name)
            .expect("proposal not found");
        cursor.erase().expect("read");
    }
}

/// Execute proposal
///
/// Allows an `executer` account to execute a proposal.
///
/// Preconditions:
/// - `executer` has authorization,
/// - `proposal_name` is found in the proposals table,
/// - all requested approvals are received,
/// - proposed transaction is not expired,
/// - and approval accounts are not found in invalidations table.
///
/// If all preconditions are met the transaction is executed as a deferred
/// transaction, and the proposal is erased from the proposals table.
///
/// - `proposer` - The account proposing a transaction
/// - `proposal_name` - The name of the proposal (should be an existing
///   proposal)
/// - `executer` - The account executing the transaction
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L142-L189)
#[eosio::action]
pub fn exec(proposer: AccountName, proposal_name: Name, executer: AccountName) {
    require_auth(executer);

    let this = current_receiver();
    let proposals = Proposal::table(this, proposer);
    let proposal_cursor =
        proposals.find(proposal_name).expect("proposal not found");
    let proposal = proposal_cursor.get().expect("read");
    let trx_header =
        TransactionHeader::unpack(&proposal.packed_transaction).expect("read");
    assert!(
        trx_header.expiration >= current_time_point_sec(),
        "transaction expired"
    );

    let mut approval_levels: Vec<PermissionLevel> = Vec::new();
    let approvals = ApprovalsInfo::table(this, proposer);
    let invalidations = Invalidation::table(this, this);
    if let Some(cursor) = approvals.find(proposal_name) {
        let approval = cursor.get().expect("read");
        for p in approval.provided_approvals.into_iter() {
            let is_invalidated = invalidations
                .find(p.level.actor)
                .map(|cursor| {
                    let inv = cursor.get().expect("read");
                    inv.last_invalidation_time > p.time
                })
                .unwrap_or(false);
            if !is_invalidated {
                approval_levels.push(p.level);
            }
        }
        cursor.erase().expect("read");
    } else {
        let old_approvals = OldApprovalsInfo::table(this, proposer);
        let cursor = old_approvals
            .find(proposal_name)
            .expect("proposal not found");
        let approval = cursor.get().expect("read");
        for level in approval.provided_approvals.into_iter() {
            let is_invalidated = invalidations.find(level.actor).is_some();
            if !is_invalidated {
                approval_levels.push(level);
            }
        }
        cursor.erase().expect("read");
    }

    let has_trx_auth = has_transaction_authority_bytes(
        &proposal.packed_transaction,
        &[],
        approval_levels,
    )
    .expect("write");
    assert!(has_trx_auth, "transaction authorization failed");

    let trx_id = TransactionId::from(
        (u128::from(proposer.as_u64()) << 64)
            | u128::from(proposal_name.as_u64()),
    );
    send_deferred_bytes(trx_id, executer, proposal.packed_transaction, true);
    proposal_cursor.erase().expect("read");
}

/// Invalidate proposal
///
/// Allows an `account` to invalidate itself, that is, its name is added to
/// the invalidations table and this table will be cross referenced when exec is
/// performed.
///
/// - `account` - The account invalidating the transaction
///
/// [Reference implementation](https://github.com/EOSIO/eosio.contracts/blob/8f05770098794c040faf7b98cd966105b6c1ccf1/contracts/eosio.msig/src/eosio.msig.cpp#L191-L205)
#[eosio::action]
pub fn invalidate(account: AccountName) {
    require_auth(account);
    let this = current_receiver();
    let invalidations = Invalidation::table(this, this);
    if let Some(cursor) = invalidations.find(account) {
        let mut invalidation = cursor.get().expect("read");
        invalidation.last_invalidation_time = current_time_point();
        cursor.modify(Payer::Same, invalidation).expect("write");
    } else {
        let invalidation = Invalidation {
            account,
            last_invalidation_time: current_time_point(),
        };
        invalidations.emplace(account, invalidation).expect("write");
    }
}

eosio::abi!(propose, approve, unapprove, cancel, exec, invalidate);