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
//! Config program

use crate::ConfigKeys;
use bincode::deserialize;
use solana_sdk::{
    feature_set, ic_msg,
    instruction::InstructionError,
    keyed_account::{next_keyed_account, KeyedAccount},
    process_instruction::InvokeContext,
    program_utils::limited_deserialize,
    pubkey::Pubkey,
};

pub fn process_instruction(
    _program_id: &Pubkey,
    keyed_accounts: &[KeyedAccount],
    data: &[u8],
    invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
    let key_list: ConfigKeys = limited_deserialize(data)?;
    let keyed_accounts_iter = &mut keyed_accounts.iter();
    let config_keyed_account = &mut next_keyed_account(keyed_accounts_iter)?;

    let current_data: ConfigKeys = {
        let config_account = config_keyed_account.try_account_ref_mut()?;
        if invoke_context.is_feature_active(&feature_set::check_program_owner::id())
            && config_account.owner != crate::id()
        {
            return Err(InstructionError::InvalidAccountOwner);
        }

        deserialize(&config_account.data).map_err(|err| {
            ic_msg!(
                invoke_context,
                "Unable to deserialize config account: {}",
                err
            );
            InstructionError::InvalidAccountData
        })?
    };
    let current_signer_keys: Vec<Pubkey> = current_data
        .keys
        .iter()
        .filter(|(_, is_signer)| *is_signer)
        .map(|(pubkey, _)| *pubkey)
        .collect();

    if current_signer_keys.is_empty() {
        // Config account keypair must be a signer on account initialization,
        // or when no signers specified in Config data
        if config_keyed_account.signer_key().is_none() {
            return Err(InstructionError::MissingRequiredSignature);
        }
    }

    let mut counter = 0;
    for (signer, _) in key_list.keys.iter().filter(|(_, is_signer)| *is_signer) {
        counter += 1;
        if signer != config_keyed_account.unsigned_key() {
            let signer_account = keyed_accounts_iter.next();
            if signer_account.is_none() {
                ic_msg!(
                    invoke_context,
                    "account {:?} is not in account list",
                    signer
                );
                return Err(InstructionError::MissingRequiredSignature);
            }
            let signer_key = signer_account.unwrap().signer_key();
            if signer_key.is_none() {
                ic_msg!(
                    invoke_context,
                    "account {:?} signer_key().is_none()",
                    signer
                );
                return Err(InstructionError::MissingRequiredSignature);
            }
            if signer_key.unwrap() != signer {
                ic_msg!(
                    invoke_context,
                    "account[{:?}].signer_key() does not match Config data)",
                    counter + 1
                );
                return Err(InstructionError::MissingRequiredSignature);
            }
            // If Config account is already initialized, update signatures must match Config data
            if !current_data.keys.is_empty()
                && current_signer_keys
                    .iter()
                    .find(|&pubkey| pubkey == signer)
                    .is_none()
            {
                ic_msg!(
                    invoke_context,
                    "account {:?} is not in stored signer list",
                    signer
                );
                return Err(InstructionError::MissingRequiredSignature);
            }
        } else if config_keyed_account.signer_key().is_none() {
            ic_msg!(invoke_context, "account[0].signer_key().is_none()");
            return Err(InstructionError::MissingRequiredSignature);
        }
    }

    // Check for Config data signers not present in incoming account update
    if current_signer_keys.len() > counter {
        ic_msg!(
            invoke_context,
            "too few signers: {:?}; expected: {:?}",
            counter,
            current_signer_keys.len()
        );
        return Err(InstructionError::MissingRequiredSignature);
    }

    if config_keyed_account.data_len()? < data.len() {
        ic_msg!(invoke_context, "instruction data too large");
        return Err(InstructionError::InvalidInstructionData);
    }

    config_keyed_account.try_account_ref_mut()?.data[..data.len()].copy_from_slice(&data);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{config_instruction, get_config_data, id, ConfigKeys, ConfigState};
    use bincode::serialized_size;
    use serde_derive::{Deserialize, Serialize};
    use solana_sdk::{
        account::Account,
        keyed_account::create_keyed_is_signer_accounts,
        process_instruction::MockInvokeContext,
        signature::{Keypair, Signer},
        system_instruction::SystemInstruction,
    };
    use std::cell::RefCell;

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct MyConfig {
        pub item: u64,
    }
    impl Default for MyConfig {
        fn default() -> Self {
            Self { item: 123_456_789 }
        }
    }
    impl MyConfig {
        pub fn new(item: u64) -> Self {
            Self { item }
        }
        pub fn deserialize(input: &[u8]) -> Option<Self> {
            deserialize(input).ok()
        }
    }

    impl ConfigState for MyConfig {
        fn max_space() -> u64 {
            serialized_size(&Self::default()).unwrap()
        }
    }

    fn create_config_account(keys: Vec<(Pubkey, bool)>) -> (Keypair, RefCell<Account>) {
        let from_pubkey = solana_sdk::pubkey::new_rand();
        let config_keypair = Keypair::new();
        let config_pubkey = config_keypair.pubkey();

        let instructions =
            config_instruction::create_account::<MyConfig>(&from_pubkey, &config_pubkey, 1, keys);

        let system_instruction = limited_deserialize(&instructions[0].data).unwrap();
        let space = match system_instruction {
            SystemInstruction::CreateAccount {
                lamports: _,
                space,
                owner: _,
            } => space,
            _ => panic!("Not a CreateAccount system instruction"),
        };
        let config_account = RefCell::new(Account {
            data: vec![0; space as usize],
            owner: id(),
            ..Account::default()
        });
        let accounts = vec![(&config_pubkey, true, &config_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instructions[1].data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );

        (config_keypair, config_account)
    }

    #[test]
    fn test_process_create_ok() {
        solana_logger::setup();
        let keys = vec![];
        let (_, config_account) = create_config_account(keys);
        assert_eq!(
            Some(MyConfig::default()),
            deserialize(get_config_data(&config_account.borrow().data).unwrap()).ok()
        );
    }

    #[test]
    fn test_process_store_ok() {
        solana_logger::setup();
        let keys = vec![];
        let (config_keypair, config_account) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config);
        let accounts = vec![(&config_pubkey, true, &config_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );
        assert_eq!(
            Some(my_config),
            deserialize(get_config_data(&config_account.borrow().data).unwrap()).ok()
        );
    }

    #[test]
    fn test_process_store_fail_instruction_data_too_large() {
        solana_logger::setup();
        let keys = vec![];
        let (config_keypair, config_account) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let mut instruction = config_instruction::store(&config_pubkey, true, keys, &my_config);
        instruction.data = vec![0; 123]; // <-- Replace data with a vector that's too large
        let accounts = vec![(&config_pubkey, true, &config_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::InvalidInstructionData)
        );
    }

    #[test]
    fn test_process_store_fail_account0_not_signer() {
        solana_logger::setup();
        let keys = vec![];
        let (config_keypair, config_account) = create_config_account(keys);
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let mut instruction = config_instruction::store(&config_pubkey, true, vec![], &my_config);
        instruction.accounts[0].is_signer = false; // <----- not a signer
        let accounts = vec![(&config_pubkey, false, &config_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );
    }

    #[test]
    fn test_process_store_with_additional_signers() {
        solana_logger::setup();
        let pubkey = solana_sdk::pubkey::new_rand();
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let signer1_pubkey = solana_sdk::pubkey::new_rand();
        let keys = vec![
            (pubkey, false),
            (signer0_pubkey, true),
            (signer1_pubkey, true),
        ];
        let (config_keypair, config_account) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
        let signer0_account = RefCell::new(Account::default());
        let signer1_account = RefCell::new(Account::default());
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, true, &signer0_account),
            (&signer1_pubkey, true, &signer1_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );
        let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
        assert_eq!(meta_data.keys, keys);
        assert_eq!(
            Some(my_config),
            deserialize(get_config_data(&config_account.borrow().data).unwrap()).ok()
        );
    }

    #[test]
    fn test_process_store_without_config_signer() {
        solana_logger::setup();
        let pubkey = solana_sdk::pubkey::new_rand();
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let keys = vec![(pubkey, false), (signer0_pubkey, true)];
        let (config_keypair, _) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config);
        let signer0_account = RefCell::new(Account {
            owner: id(),
            ..Account::default()
        });
        let accounts = vec![(&signer0_pubkey, true, &signer0_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::InvalidAccountData)
        );
    }

    #[test]
    fn test_process_store_with_bad_additional_signer() {
        solana_logger::setup();
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let signer1_pubkey = solana_sdk::pubkey::new_rand();
        let signer0_account = RefCell::new(Account::default());
        let signer1_account = RefCell::new(Account::default());
        let keys = vec![(signer0_pubkey, true)];
        let (config_keypair, config_account) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config);

        // Config-data pubkey doesn't match signer
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer1_pubkey, true, &signer1_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );

        // Config-data pubkey not a signer
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, false, &signer0_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );
    }

    #[test]
    fn test_config_updates() {
        solana_logger::setup();
        let pubkey = solana_sdk::pubkey::new_rand();
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let signer1_pubkey = solana_sdk::pubkey::new_rand();
        let signer2_pubkey = solana_sdk::pubkey::new_rand();
        let signer0_account = RefCell::new(Account::default());
        let signer1_account = RefCell::new(Account::default());
        let signer2_account = RefCell::new(Account::default());
        let keys = vec![
            (pubkey, false),
            (signer0_pubkey, true),
            (signer1_pubkey, true),
        ];
        let (config_keypair, config_account) = create_config_account(keys.clone());
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, true, &signer0_account),
            (&signer1_pubkey, true, &signer1_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );

        // Update with expected signatures
        let new_config = MyConfig::new(84);
        let instruction =
            config_instruction::store(&config_pubkey, false, keys.clone(), &new_config);
        let accounts = vec![
            (&config_pubkey, false, &config_account),
            (&signer0_pubkey, true, &signer0_account),
            (&signer1_pubkey, true, &signer1_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );
        let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
        assert_eq!(meta_data.keys, keys);
        assert_eq!(
            new_config,
            MyConfig::deserialize(get_config_data(&config_account.borrow().data).unwrap()).unwrap()
        );

        // Attempt update with incomplete signatures
        let keys = vec![(pubkey, false), (signer0_pubkey, true)];
        let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config);
        let accounts = vec![
            (&config_pubkey, false, &config_account),
            (&signer0_pubkey, true, &signer0_account),
            (&signer1_pubkey, false, &signer1_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );

        // Attempt update with incorrect signatures
        let keys = vec![
            (pubkey, false),
            (signer0_pubkey, true),
            (signer2_pubkey, true),
        ];
        let instruction = config_instruction::store(&config_pubkey, false, keys, &my_config);
        let accounts = vec![
            (&config_pubkey, false, &config_account),
            (&signer0_pubkey, true, &signer0_account),
            (&signer2_pubkey, true, &signer2_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );
    }

    #[test]
    fn test_config_updates_requiring_config() {
        solana_logger::setup();
        let pubkey = solana_sdk::pubkey::new_rand();
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let signer0_account = RefCell::new(Account::default());
        let keys = vec![
            (pubkey, false),
            (signer0_pubkey, true),
            (signer0_pubkey, true),
        ]; // Dummy keys for account sizing
        let (config_keypair, config_account) = create_config_account(keys);
        let config_pubkey = config_keypair.pubkey();
        let my_config = MyConfig::new(42);

        let keys = vec![
            (pubkey, false),
            (signer0_pubkey, true),
            (config_keypair.pubkey(), true),
        ];

        let instruction = config_instruction::store(&config_pubkey, true, keys.clone(), &my_config);
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, true, &signer0_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );

        // Update with expected signatures
        let new_config = MyConfig::new(84);
        let instruction =
            config_instruction::store(&config_pubkey, true, keys.clone(), &new_config);
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, true, &signer0_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Ok(())
        );
        let meta_data: ConfigKeys = deserialize(&config_account.borrow().data).unwrap();
        assert_eq!(meta_data.keys, keys);
        assert_eq!(
            new_config,
            MyConfig::deserialize(get_config_data(&config_account.borrow().data).unwrap()).unwrap()
        );

        // Attempt update with incomplete signatures
        let keys = vec![(pubkey, false), (config_keypair.pubkey(), true)];
        let instruction = config_instruction::store(&config_pubkey, true, keys, &my_config);
        let accounts = vec![(&config_pubkey, true, &config_account)];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::MissingRequiredSignature)
        );
    }

    #[test]
    fn test_config_initialize_no_panic() {
        let from_pubkey = solana_sdk::pubkey::new_rand();
        let config_pubkey = solana_sdk::pubkey::new_rand();
        let instructions =
            config_instruction::create_account::<MyConfig>(&from_pubkey, &config_pubkey, 1, vec![]);
        let accounts = vec![];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instructions[1].data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::NotEnoughAccountKeys)
        );
    }

    #[test]
    fn test_config_bad_owner() {
        let from_pubkey = solana_sdk::pubkey::new_rand();
        let config_pubkey = solana_sdk::pubkey::new_rand();
        let new_config = MyConfig::new(84);
        let signer0_pubkey = solana_sdk::pubkey::new_rand();
        let signer0_account = RefCell::new(Account::default());
        let config_account = RefCell::new(Account::default());
        let keys = vec![
            (from_pubkey, false),
            (signer0_pubkey, true),
            (config_pubkey, true),
        ];

        let instruction = config_instruction::store(&config_pubkey, true, keys, &new_config);
        let accounts = vec![
            (&config_pubkey, true, &config_account),
            (&signer0_pubkey, true, &signer0_account),
        ];
        let keyed_accounts = create_keyed_is_signer_accounts(&accounts);
        assert_eq!(
            process_instruction(
                &id(),
                &keyed_accounts,
                &instruction.data,
                &mut MockInvokeContext::default()
            ),
            Err(InstructionError::InvalidAccountOwner)
        );
    }
}