-
Notifications
You must be signed in to change notification settings - Fork 2
/
processor.rs
634 lines (542 loc) · 22.5 KB
/
processor.rs
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
634
//! Program state processor
//! A multisig wallet program for the Solana blockchain Designed by Mohammadreza Ashouri / [email protected]
use crate::{
error::WalletError,
instruction::WalletInstruction,
state::{Account, AccountState, InstructionBuffer, PartialInstruction, MAX_OWNERS, MIN_WEIGHT},
};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
info,
instruction::Instruction,
program::invoke_signed,
program_error::ProgramError,
program_pack::{IsInitialized, Pack},
pubkey::Pubkey,
};
use std::{collections::BTreeMap, mem};
/// Program state handler.
pub struct Processor {}
impl Processor {
/// Process a Hello instruction
fn process_hello() -> ProgramResult {
info!("Hello!");
Ok(())
}
/// Process an AddOwner instruction and initialize the wallet
fn process_initialize_wallet(
wallet_account: &mut Account,
owners: BTreeMap<Pubkey, u16>,
) -> ProgramResult {
// check key weight
Self::is_key_weight_enough(&owners)?;
wallet_account.state = AccountState::Initialized;
for (pubkey, weight) in owners {
wallet_account.owners.insert(pubkey, weight);
}
Ok(())
}
/// Process an AddOwner instruction
fn process_add_owner(
wallet_account: &mut Account,
owners: BTreeMap<Pubkey, u16>,
) -> ProgramResult {
if wallet_account.owners.len() + owners.len() > MAX_OWNERS {
info!("WalletError: too many owners");
return Err(WalletError::InvalidInstruction.into());
}
for (pubkey, weight) in owners {
if weight == 0 {
info!("WalletError: Key weight cannot be 0");
return Err(WalletError::InvalidInstruction.into());
}
if wallet_account.owners.contains_key(&pubkey) {
info!("WalletError: Owner already exists");
return Err(WalletError::InvalidInstruction.into());
}
wallet_account.owners.insert(pubkey, weight);
}
Ok(())
}
/// Process a RemoveOwner instruction
fn process_remove_owner(wallet_account: &mut Account, pubkey: Pubkey) -> ProgramResult {
// check target exist
if !wallet_account.owners.contains_key(&pubkey) {
info!("WalletError: Cannot find the target owner to remove");
return Err(WalletError::InvalidInstruction.into());
}
// remove
wallet_account.owners.remove(&pubkey);
// check key weight
Self::is_key_weight_enough(&wallet_account.owners)?;
Ok(())
}
/// Process an Recovery instruction
fn process_recovery(
wallet_account: &mut Account,
owners: BTreeMap<Pubkey, u16>,
) -> ProgramResult {
if owners.len() > MAX_OWNERS {
info!("WalletError: too many owners");
return Err(WalletError::InvalidInstruction.into());
}
// check key weight
Self::is_key_weight_enough(&wallet_account.owners)?;
wallet_account.owners.clear();
for (pubkey, weight) in owners {
if weight == 0 {
info!("WalletError: Key weight cannot be 0");
return Err(WalletError::InvalidInstruction.into());
}
if wallet_account.owners.contains_key(&pubkey) {
info!("WalletError: Owner already exists");
return Err(WalletError::InvalidInstruction.into());
}
wallet_account.owners.insert(pubkey, weight);
}
Ok(())
}
/// Process an Revoke insturction
fn process_revoke(wallet_account: &mut Account) -> ProgramResult {
wallet_account.owners.clear();
Ok(())
}
/// Process an Invoke instruction and call another program
fn process_invoke(accounts: &[AccountInfo], instruction: Instruction) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let wallet_account = next_account_info(accounts_iter)?;
let auth_account = next_account_info(accounts_iter)?;
let payer_account = next_account_info(accounts_iter)?;
let mut pass_accounts = Vec::new();
// Pass all accounts to invoke call
// info!(bs58::encode(wallet_account.key.to_bytes()).into_string().as_str());
pass_accounts.push(wallet_account.clone());
// info!(bs58::encode(auth_account.key.to_bytes()).into_string().as_str());
pass_accounts.push(auth_account.clone());
pass_accounts.push(payer_account.clone());
for account in accounts_iter {
// info!(bs58::encode(account.key.to_bytes()).into_string().as_str());
pass_accounts.push(account.clone());
}
// limit payer auth
let mut instruction = instruction.clone();
for account in &mut instruction.accounts {
if &account.pubkey == payer_account.key {
account.is_signer = false;
}
}
invoke_signed(
&instruction,
pass_accounts.as_slice(),
&[&[&wallet_account.key.to_bytes()]],
)?;
Ok(())
}
fn is_key_weight_enough(owners: &BTreeMap<Pubkey, u16>) -> ProgramResult {
let mut sum_of_key_weight = 0;
for (_, weight) in owners {
sum_of_key_weight += weight;
}
if sum_of_key_weight < MIN_WEIGHT {
return Err(WalletError::InsufficientWeight.into());
}
Ok(())
}
/// Check if signatures have enought weight
fn check_signatures(accounts: &[AccountInfo], wallet_account: &Account) -> ProgramResult {
let mut total_key_weight = 0;
let mut counted = BTreeMap::new();
for account in accounts.iter() {
if account.is_signer
&& wallet_account.owners.contains_key(account.key)
&& !counted.contains_key(account.key)
{
counted.insert(account.key, true);
total_key_weight += wallet_account.owners[account.key];
}
}
if total_key_weight < MIN_WEIGHT {
info!("WalletError: Signature weight too low");
return Err(WalletError::InsufficientWeight.into());
}
Ok(())
}
/// Load wallet account data
fn load_wallet_account(
program_id: &Pubkey,
accounts: &[AccountInfo],
) -> Result<Account, ProgramError> {
// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();
// The account containing wallet information
let walllet_account = next_account_info(accounts_iter)?;
// The account must be owned by the program in order to modify its data
if walllet_account.owner != program_id {
info!("Wallet account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}
// The data must be large enough to hold a u64 count
if walllet_account.try_data_len()? < mem::size_of::<Account>() {
info!("Wallet account data length too small for Account");
return Err(ProgramError::InvalidAccountData);
}
Account::unpack_unchecked(&walllet_account.data.borrow())
}
/// Store wallet account data
fn store_wallet_account(
program_id: &Pubkey,
accounts: &[AccountInfo],
wallet_account: Account,
) -> Result<(), ProgramError> {
// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();
// Get the account to say hello to
let account = next_account_info(accounts_iter)?;
// The account must be owned by the program in order to modify its data
if account.owner != program_id {
info!("Wallet account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}
// The account must be declaired writable
if !account.is_writable {
info!("Wallet account was not declaired writable");
return Err(ProgramError::InvalidAccountData);
}
Account::pack(wallet_account, &mut account.data.borrow_mut())?;
Ok(())
}
fn process_init_instruction_buffer(
_program_id: &Pubkey,
accounts: &[AccountInfo],
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let instruction_account_info = next_account_info(accounts_iter)?;
let owner_account_info = next_account_info(accounts_iter)?;
let mut sequence_instructions =
InstructionBuffer::unpack(&instruction_account_info.data.borrow())?;
if sequence_instructions.owner != Pubkey::default() {
return Err(ProgramError::AccountAlreadyInitialized);
}
sequence_instructions.owner = *owner_account_info.key;
InstructionBuffer::pack(
sequence_instructions,
&mut instruction_account_info.data.borrow_mut(),
)?;
Ok(())
}
fn process_append_partial_instruction(
_program_id: &Pubkey,
accounts: &[AccountInfo],
idx: u16,
instruction: Instruction,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let _wallet_account_info = next_account_info(accounts_iter)?;
let instruction_account_info = next_account_info(accounts_iter)?;
let owner_account_info = next_account_info(accounts_iter)?;
if !owner_account_info.is_signer {
info!(&format!("{} should be a signer", owner_account_info.key));
return Err(ProgramError::MissingRequiredSignature);
}
let mut sequence_instructions =
InstructionBuffer::unpack(&instruction_account_info.data.borrow())?;
if sequence_instructions.owner != *owner_account_info.key {
info!(&format!("{} owner mismatch", instruction_account_info.key));
return Err(ProgramError::InvalidAccountData);
}
sequence_instructions.owner = *owner_account_info.key;
sequence_instructions
.instructions
.push(PartialInstruction { idx, instruction });
InstructionBuffer::pack(
sequence_instructions,
&mut instruction_account_info.data.borrow_mut(),
)?;
Ok(())
}
fn process_run_insturction_buffer(
_program_id: &Pubkey,
accounts: &[AccountInfo],
num: u16,
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let wallet_account = next_account_info(accounts_iter)?;
let instruction_account_info = next_account_info(accounts_iter)?;
let owner_account_info = next_account_info(accounts_iter)?;
if !owner_account_info.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
let sequence_instructions =
InstructionBuffer::unpack(&instruction_account_info.data.borrow())?;
if sequence_instructions.instructions.len() != usize::from(num) {
return Err(ProgramError::InvalidAccountData);
}
if sequence_instructions.owner != *owner_account_info.key {
return Err(ProgramError::InvalidAccountData);
}
let mut pass_accounts = Vec::new();
let instruction_num = sequence_instructions.instructions.len();
let mut inner_instructions = BTreeMap::<u16, &Instruction>::new();
for ins in sequence_instructions.instructions.iter() {
inner_instructions.insert(ins.idx, &ins.instruction);
}
for account in accounts_iter {
let mut pass_account = account.clone();
if pass_account.key == owner_account_info.key {
pass_account.is_signer = false;
}
pass_accounts.push(account.clone());
}
for n in 0..instruction_num {
invoke_signed(
inner_instructions.get(&(n as u16)).unwrap(),
pass_accounts.as_slice(),
&[&[&wallet_account.key.to_bytes()]],
)?;
}
let dest_starting_lamports = owner_account_info.lamports();
**owner_account_info.lamports.borrow_mut() = dest_starting_lamports
.checked_add(instruction_account_info.lamports())
.ok_or(ProgramError::InvalidAccountData)?;
**instruction_account_info.lamports.borrow_mut() = 0;
Ok(())
}
fn process_close_instruction_buffer(
_program_id: &Pubkey,
accounts: &[AccountInfo],
) -> ProgramResult {
let accounts_iter = &mut accounts.iter();
let instruction_account_info = next_account_info(accounts_iter)?;
let owner_account_info = next_account_info(accounts_iter)?;
if !owner_account_info.is_signer {
info!(&format!("{} should be a signer", owner_account_info.key));
return Err(ProgramError::MissingRequiredSignature);
}
let sequence_instructions =
InstructionBuffer::unpack(&instruction_account_info.data.borrow())?;
if sequence_instructions.owner != *owner_account_info.key {
return Err(ProgramError::InvalidAccountData);
}
let dest_starting_lamports = owner_account_info.lamports();
**owner_account_info.lamports.borrow_mut() = dest_starting_lamports
.checked_add(instruction_account_info.lamports())
.ok_or(ProgramError::InvalidAccountData)?;
**instruction_account_info.lamports.borrow_mut() = 0;
Ok(())
}
/// Process a WalletInstruction
pub fn process(program_id: &Pubkey, accounts: &[AccountInfo], input: &[u8]) -> ProgramResult {
let instruction = WalletInstruction::unpack(input, &accounts)?;
match instruction {
WalletInstruction::AddOwner { owners } => {
let mut wallet_account = Self::load_wallet_account(program_id, accounts)?;
let is_wallet_initialized = wallet_account.is_initialized();
// TODO add init instruction to handle it
if !is_wallet_initialized {
info!("Instruction: AddOwner (Initialize Wallet)");
Self::process_initialize_wallet(&mut wallet_account, owners)?;
} else {
info!("Instruction: AddOwner");
Self::check_signatures(accounts, &wallet_account)?;
Self::process_add_owner(&mut wallet_account, owners)?;
}
Self::store_wallet_account(program_id, accounts, wallet_account)
}
WalletInstruction::RemoveOwner { pubkey } => {
info!("Instruction: RemoveOwner");
let mut wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_remove_owner(&mut wallet_account, pubkey)?;
Self::store_wallet_account(program_id, accounts, wallet_account)
}
WalletInstruction::Recovery { owners } => {
info!("Instruction: Recovery");
let mut wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_recovery(&mut wallet_account, owners)?;
Self::store_wallet_account(program_id, accounts, wallet_account)
}
WalletInstruction::Revoke => {
info!("Instruction: Revoke");
let mut wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_revoke(&mut wallet_account)?;
Self::store_wallet_account(program_id, accounts, wallet_account)
}
WalletInstruction::Invoke {
instruction: internal_instruction,
} => {
info!("Instruction: Invoke");
let wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_invoke(accounts, internal_instruction)
}
WalletInstruction::Hello => {
info!("Instruction: Hello");
let wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_hello()
}
WalletInstruction::InitInstructionBuffer => {
info!("Instruction: InitInstructionBuffer");
Self::process_init_instruction_buffer(program_id, accounts)
}
WalletInstruction::AppendPartialInsturciton { idx, instruction } => {
info!("Instruction: AppendPartialInsturciton");
let wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::check_signatures(accounts, &wallet_account)?;
Self::process_append_partial_instruction(program_id, accounts, idx, instruction)
}
WalletInstruction::RunInstructionBuffer { num } => {
info!("Instruction: RunInstructionBuffer");
let wallet_account = Self::load_wallet_account(program_id, accounts)?;
if !wallet_account.is_initialized() {
return Err(ProgramError::UninitializedAccount);
}
Self::process_run_insturction_buffer(program_id, accounts, num)
}
WalletInstruction::CloseInstructionBuffer => {
info!("Instruction: CloseInstructionBuffer");
Self::process_close_instruction_buffer(program_id, accounts)
}
_ => {
info!("Invalid instruction");
Err(WalletError::InvalidInstruction.into())
}
}?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use maplit::btreemap;
use std::str::FromStr;
#[test]
fn should_fail_when_init_with_key_weight_is_not_enough() {
let mut init_account = Account {
state: AccountState::Uninitialized,
owners: BTreeMap::new(),
};
let init_keys = btreemap! {
Pubkey::from_str("KEY").unwrap() => 1,
Pubkey::from_str("KEY").unwrap() => 1,
};
let expected_account = Account {
state: AccountState::Uninitialized,
owners: BTreeMap::new(),
};
assert_eq!(
Processor::process_initialize_wallet(&mut init_account, init_keys.clone()),
Err(WalletError::InsufficientWeight.into()),
);
assert_eq!(init_account, expected_account);
}
#[test]
fn process_initialize_wallet_should_success() {
let mut init_account = Account {
state: AccountState::Uninitialized,
owners: BTreeMap::new(),
};
let init_keys = btreemap! {
Pubkey::from_str("KEY").unwrap() => 999,
Pubkey::from_str("KEY").unwrap() => 1,
};
assert_eq!(
Processor::process_initialize_wallet(&mut init_account, init_keys.clone()),
Ok(()),
);
assert_eq!(
init_account,
Account {
state: AccountState::Initialized,
owners: init_keys.clone(),
},
);
}
#[test]
fn process_add_owner_should_success() {
let mut init_account = Account {
state: AccountState::Initialized,
owners: btreemap! {
Pubkey::from_str("KEY").unwrap() => 1000,
},
};
let add_keys = btreemap! {Pubkey::from_str("KEY").unwrap() => 1};
assert_eq!(
Processor::process_add_owner(&mut init_account, add_keys),
Ok(())
);
let expected_account = Account {
state: AccountState::Initialized,
owners: btreemap! {
Pubkey::from_str("KEY").unwrap() => 1000,
Pubkey::from_str("KEY").unwrap() => 1
},
};
assert_eq!(init_account, expected_account);
}
#[test]
fn should_fail_when_recovery_with_key_weight_is_not_enough() {
let mut wallet_account = Account {
state: AccountState::Initialized,
owners: btreemap! {Pubkey::from_str("KEY").unwrap() => 1000},
};
let recovery_keys = btreemap! {
Pubkey::from_str("KEY").unwrap() => 1,
};
assert_eq!(
Processor::process_initialize_wallet(&mut wallet_account, recovery_keys),
Err(WalletError::InsufficientWeight.into()),
);
}
#[test]
fn process_recovery_should_success() {
let mut wallet_account = Account {
state: AccountState::Initialized,
owners: btreemap! {Pubkey::from_str("KEY").unwrap() => 1000},
};
let recovery_keys = btreemap! {Pubkey::from_str("KEY").unwrap() => 1000};
assert_eq!(
Processor::process_recovery(&mut wallet_account, recovery_keys.clone()),
Ok(())
);
let expected_account = Account {
state: AccountState::Initialized,
owners: recovery_keys.clone(),
};
assert_eq!(wallet_account, expected_account);
}
#[test]
fn process_revoke_should_success() {
let mut wallet_account = Account {
state: AccountState::Initialized,
owners: btreemap! {Pubkey::from_str("KEY").unwrap() => 1000},
};
assert_eq!(Processor::process_revoke(&mut wallet_account), Ok(()));
let expected_account = Account {
state: AccountState::Initialized,
owners: btreemap! {},
};
assert_eq!(wallet_account, expected_account);
}
}