eclipse_bridge_multisig 0.0.1

Created with Anchor
Documentation
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
//! An example of a multisig to execute arbitrary Solana transactions.
//!
//! This program can be used to allow a multisig to govern anything a regular
//! Pubkey can govern. One can use the multisig as a BPF program upgrade
//! authority, a mint authority, etc.
//!
//! To use, one must first create a `Multisig` account, specifying two important
//! parameters:
//!
//! 1. Owners - the set of addresses that sign transactions for the multisig.
//! 2. Threshold - the number of signers required to execute a transaction.
//!
//! Once the `Multisig` account is created, one can create a `Transaction`
//! account, specifying the parameters for a normal solana transaction.
//!
//! To sign, owners should invoke the `approve` instruction, and finally,
//! the `execute_transaction`, once enough (i.e. `threshold`) of the owners have
//! signed.

use anchor_lang::prelude::*;
use anchor_lang::solana_program;
use anchor_lang::solana_program::instruction::Instruction;
use std::convert::Into;


const ANCHOR_ACCT_DESCRIM_SIZE: usize = 8;
const VEC_SIZE: usize = 4;
const PUBKEY_SIZE: usize = 32;

#[cfg(not(feature = "no-entrypoint"))]
use solana_security_txt::security_txt;

#[cfg(not(feature = "no-entrypoint"))]
security_txt! {
    name: "LMAX Multisig",
    project_url: "https://www.lmax.com",
    contacts: "email:infosec@lmax.com",
    policy: "https://lmax.com/.well-known/security.txt",

    preferred_languages: "en",
    auditors: "https://www.certik.com"
}

#[macro_export]
macro_rules! vec_len {
    ( $elem_size:expr, $elem_count:expr ) => {
        {
            ($elem_size * $elem_count + VEC_SIZE)
        }
    };
}

#[macro_export]
macro_rules! instructions_len {
    ( $instructions: expr) => {
        {
            ($instructions.iter().map(|ix| {
                PUBKEY_SIZE + vec_len!(PUBKEY_SIZE + 1 + 1, ix.accounts.len()) + vec_len!(1, ix.data.len())
            })
            .sum::<usize>() + VEC_SIZE)
        }
    };
}

#[macro_export]
macro_rules! multisig_data_len {
    ( $owner_count:expr ) => {
        {
            (ANCHOR_ACCT_DESCRIM_SIZE + vec_len!(PUBKEY_SIZE, $owner_count) + 8 + 1 + 4)
        }
    };
}

#[macro_export]
macro_rules! transaction_data_len {
    ( $instructions:expr, $owner_count:expr ) => {
        {
            (ANCHOR_ACCT_DESCRIM_SIZE + PUBKEY_SIZE + instructions_len!($instructions) + vec_len!(1, $owner_count) + 4)
        }
    };
}



declare_id!("LMAXm1DhfBg1YMvi79gXdPfsJpYuJb9urGkGNa12hvJ");

#[program]
pub mod lmax_multisig {
    use super::*;

    // Initializes a new multisig account with a set of owners and a threshold.
    pub fn create_multisig(
        ctx: Context<CreateMultisig>,
        owners: Vec<Pubkey>,
        threshold: u64,
        nonce: u8,
    ) -> Result<()> {
        assert_unique_owners(&owners)?;
        require!(
            threshold > 0 && threshold <= owners.len() as u64,
            ErrorCode::InvalidThreshold
        );
        require!(!owners.is_empty(), ErrorCode::NotEnoughOwners);

        let multisig = &mut ctx.accounts.multisig;
        multisig.owners = owners;
        multisig.threshold = threshold;
        multisig.nonce = nonce;
        multisig.owner_set_seqno = 0;
        Ok(())
    }

    // Creates a new transaction account, automatically signed by the creator,
    // which must be one of the owners of the multisig.
    pub fn create_transaction(
        ctx: Context<CreateTransaction>,
        instructions: Vec<TransactionInstruction>,
        transaction_nonce: u64,
    ) -> Result<()> {
        require!(!instructions.is_empty(), ErrorCode::MissingInstructions);

        let owner_index = ctx
            .accounts
            .multisig
            .owners
            .iter()
            .position(|a| a == ctx.accounts.proposer.key)
            .ok_or(ErrorCode::InvalidOwner)?;

        let mut signers = Vec::new();
        signers.resize(ctx.accounts.multisig.owners.len(), false);
        signers[owner_index] = true;

        let tx = &mut ctx.accounts.transaction;
        tx.instructions = instructions;
        tx.signers = signers;
        tx.multisig = ctx.accounts.multisig.key();
        tx.owner_set_seqno = ctx.accounts.multisig.owner_set_seqno;
        tx.transaction_nonce = transaction_nonce;

        Ok(())
    }

    // Approves a transaction on behalf of an owner of the multisig.
    pub fn approve(ctx: Context<Approve>) -> Result<()> {
        let owner_index = ctx
            .accounts
            .multisig
            .owners
            .iter()
            .position(|a| a == ctx.accounts.owner.key)
            .ok_or(ErrorCode::InvalidOwner)?;

        ctx.accounts.transaction.signers[owner_index] = true;

        Ok(())
    }

    // Set owners and threshold at once.
    pub fn set_owners_and_change_threshold<'info>(
        ctx: Context<'_, '_, '_, 'info, Auth<'info>>,
        owners: Vec<Pubkey>,
        threshold: u64,
    ) -> Result<()> {
        let multisig = &mut ctx.accounts.multisig;
        execute_set_owners(multisig, owners)?;
        execute_change_threshold(multisig, threshold)
    }

    // Sets the owners field on the multisig. The only way this can be invoked
    // is via a recursive call from execute_transaction -> set_owners.
    pub fn set_owners(ctx: Context<Auth>, owners: Vec<Pubkey>) -> Result<()> {
        execute_set_owners(&mut ctx.accounts.multisig, owners)
    }

    // Changes the execution threshold of the multisig. The only way this can be
    // invoked is via a recursive call from execute_transaction ->
    // change_threshold.
    pub fn change_threshold(ctx: Context<Auth>, threshold: u64) -> Result<()> {
        let multisig = &mut ctx.accounts.multisig;
        execute_change_threshold(multisig, threshold)
    }

    // Executes the given transaction if threshold owners have signed it.
    pub fn execute_transaction(ctx: Context<ExecuteTransaction>) -> Result<()> {
        require!(ctx.accounts.multisig.owners.contains(ctx.accounts.executor.key), ErrorCode::InvalidExecutor);

        // Do we have enough signers?
        let sig_count = ctx.accounts.transaction.signers.iter()
            .filter(|&did_sign| *did_sign)
            .count() as u64;
        require!(sig_count >= ctx.accounts.multisig.threshold, ErrorCode::NotEnoughSigners);

        let multisig_key = ctx.accounts.multisig.key();
        let seeds = &[multisig_key.as_ref(), &[ctx.accounts.multisig.nonce]];
        let signer = &[&seeds[..]];
        let accounts = ctx.remaining_accounts;

        // Execute the transaction signed by the multisig.
        ctx.accounts.transaction.instructions.iter()
            .map(|ix| {
                let mut ix: Instruction = ix.into();
                ix.accounts = ix.accounts.iter()
                    .map(|acc| {
                        let mut acc = acc.clone();
                        if &acc.pubkey == ctx.accounts.multisig_signer.key {
                            acc.is_signer = true;
                        }
                        acc
                    })
                    .collect();
                solana_program::program::invoke_signed(&ix, accounts, signer)
            })
            // Collect will process Result objects from the invoke_signed until it finds an error, when it will return that error
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(())
    }

    // Cancel the given transaction regardless of signatures.
    pub fn cancel_transaction(ctx: Context<CancelTransaction>) -> Result<()> {
        require!(ctx.accounts.multisig.owners.contains(ctx.accounts.executor.key), ErrorCode::InvalidExecutor);
        Ok(())
    }
}

#[derive(Accounts)]
#[instruction(owners: Vec<Pubkey>, threshold: u64, nonce: u8)]
pub struct CreateMultisig<'info> {
    // see https://book.anchor-lang.com/anchor_references/space.html
    #[account(
        init,
        space = multisig_data_len!(owners.len()),
        payer = payer,
        signer
    )]
    multisig: Box<Account<'info, Multisig>>,
    /// CHECK: multisig_signer is a PDA program signer. Data is never read or written to
    #[account(
        seeds = [multisig.key().as_ref()],
        bump = nonce,
    )]
    multisig_signer: UncheckedAccount<'info>,
    #[account(mut)]
    payer: Signer<'info>,
    system_program: Program<'info, System>,
}

#[derive(Accounts)]
#[instruction(instructions: Vec<TransactionInstruction>, transaction_nonce: u64)]
pub struct CreateTransaction<'info> {
    multisig: Box<Account<'info, Multisig>>,
    // see https://book.anchor-lang.com/anchor_references/space.html
    #[account(
        init,
        space = transaction_data_len!(instructions, multisig.owners.len()) + 8,
        payer = payer,
        seeds = [b"transaction_nonce", transaction_nonce.to_le_bytes().as_ref()],
        bump,
    )]
    transaction: Box<Account<'info, Transaction>>,
    // One of the owners. Checked in the handler.
    proposer: Signer<'info>,
    #[account(mut)]
    payer: Signer<'info>,
    system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Approve<'info> {
    #[account(constraint = multisig.owner_set_seqno == transaction.owner_set_seqno)]
    multisig: Box<Account<'info, Multisig>>,
    #[account(mut, has_one = multisig)]
    transaction: Box<Account<'info, Transaction>>,
    // One of the multisig owners. Checked in the handler.
    owner: Signer<'info>,
}

#[derive(Accounts)]
pub struct Auth<'info> {
    #[account(mut)]
    multisig: Box<Account<'info, Multisig>>,
    #[account(
        seeds = [multisig.key().as_ref()],
        bump = multisig.nonce,
    )]
    multisig_signer: Signer<'info>,
}

#[derive(Accounts)]
pub struct ExecuteTransaction<'info> {
    #[account(constraint = multisig.owner_set_seqno == transaction.owner_set_seqno)]
    multisig: Box<Account<'info, Multisig>>,
    /// CHECK: multisig_signer is a PDA program signer. Data is never read or written to
    #[account(
        seeds = [multisig.key().as_ref()],
        bump = multisig.nonce,
    )]
    multisig_signer: UncheckedAccount<'info>,
    #[account(mut, has_one = multisig, close = refundee)]
    transaction: Box<Account<'info, Transaction>>,
    /// CHECK: success can be any address where rent exempt funds are sent
    #[account(mut)]
    refundee:  AccountInfo<'info>,
    executor: Signer<'info>,
}

#[derive(Accounts)]
pub struct CancelTransaction<'info> {
    #[account(constraint = multisig.owner_set_seqno >= transaction.owner_set_seqno)]
    multisig: Box<Account<'info, Multisig>>,
    #[account(mut, has_one = multisig, close = refundee)]
    transaction: Box<Account<'info, Transaction>>,
    /// CHECK: success can be any address where rent exempt funds are sent
    #[account(mut)]
    refundee:  AccountInfo<'info>,
    executor: Signer<'info>,
}

#[account]
pub struct Multisig {
    pub owners: Vec<Pubkey>,
    pub threshold: u64,
    pub nonce: u8,
    pub owner_set_seqno: u32,
}

#[account]
pub struct Transaction {
    // The multisig account this transaction belongs to.
    pub multisig: Pubkey,
    // The instructions to be executed by this transaction
    pub instructions: Vec<TransactionInstruction>,
    // signers[index] is true iff multisig.owners[index] signed the transaction.
    pub signers: Vec<bool>,
    // Owner set sequence number.
    pub owner_set_seqno: u32,
    // transaction nonce for tracking and uniqueness.
    pub transaction_nonce: u64,
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TransactionInstruction {
    /// Pubkey of the program that executes this instruction.
    pub program_id: Pubkey,
    /// Metadata describing accounts that should be passed to the program.
    pub accounts: Vec<TransactionAccount>,
    /// Opaque data passed to the program for its own interpretation.
    pub data: Vec<u8>,
}

impl From<&TransactionInstruction> for Instruction {
    fn from(ix: &TransactionInstruction) -> Instruction {
        Instruction {
            program_id: ix.program_id,
            accounts: ix.accounts.iter().map(Into::into).collect(),
            data: ix.data.clone(),
        }
    }
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct TransactionAccount {
    pub pubkey: Pubkey,
    pub is_signer: bool,
    pub is_writable: bool,
}

impl From<&TransactionAccount> for AccountMeta {
    fn from(account: &TransactionAccount) -> AccountMeta {
        match account.is_writable {
            false => AccountMeta::new_readonly(account.pubkey, account.is_signer),
            true => AccountMeta::new(account.pubkey, account.is_signer),
        }
    }
}

fn assert_unique_owners(owners: &[Pubkey]) -> Result<()> {
    for (i, owner) in owners.iter().enumerate() {
        require!(
            !owners.iter().skip(i + 1).any(|item| item == owner),
            ErrorCode::UniqueOwners
        )
    }
    Ok(())
}

fn execute_set_owners(multisig: &mut Account<Multisig>, owners: Vec<Pubkey>) -> Result<()> {
    assert_unique_owners(&owners)?;
    require!(!owners.is_empty(), ErrorCode::NotEnoughOwners);
    // Increasing the number of owners requires reallocation of space in the data account.
    // This requires a signer to pay the fees for more space, but the instruction will be executed by the multisig.
    require!(multisig_data_len!(owners.len()) <= multisig.to_account_info().data.borrow().len(), ErrorCode::TooManyOwners);

    if (owners.len() as u64) < multisig.threshold {
        multisig.threshold = owners.len() as u64;
    }

    multisig.owners = owners;
    multisig.owner_set_seqno += 1;

    Ok(())
}

fn execute_change_threshold(multisig: &mut Multisig, threshold: u64) -> Result<()> {
    require!(threshold > 0 && threshold <= multisig.owners.len() as u64, ErrorCode::InvalidThreshold);
    multisig.threshold = threshold;
    Ok(())
}

#[error_code]
pub enum ErrorCode {
    #[msg("The given owner is not part of this multisig.")]
    InvalidOwner,
    #[msg("Owners length must be non zero.")]
    NotEnoughOwners,
    #[msg("The number of owners cannot be increased.")]
    TooManyOwners,
    #[msg("Not enough owners signed this transaction.")]
    NotEnoughSigners,
    #[msg("Cannot delete a transaction that has been signed by an owner.")]
    TransactionAlreadySigned,
    #[msg("Overflow when adding.")]
    Overflow,
    #[msg("Cannot delete a transaction the owner did not create.")]
    UnableToDelete,
    #[msg("The given transaction has already been executed.")]
    AlreadyExecuted,
    #[msg("Threshold must be less than or equal to the number of owners and greater than zero.")]
    InvalidThreshold,
    #[msg("Owners must be unique.")]
    UniqueOwners,
    #[msg("Executor is not a multisig owner.")]
    InvalidExecutor,
    #[msg("Failed to close transaction account and refund rent-exemption SOL.")]
    AccountCloseFailed,
    #[msg("The number of instructions must be greater than zero.")]
    MissingInstructions,
}