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
use std::collections::HashMap;
use crate::{
error::RuleSetError,
instruction::RuleSetInstruction,
pda::PREFIX,
state::RuleSet,
utils::{assert_derivation, create_or_allocate_account_raw},
};
use borsh::BorshDeserialize;
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint::ProgramResult,
msg,
program_memory::sol_memcpy,
pubkey::Pubkey,
};
pub struct Processor;
impl Processor {
pub fn process_instruction(
program_id: &Pubkey,
accounts: &[AccountInfo],
instruction_data: &[u8],
) -> ProgramResult {
let instruction = RuleSetInstruction::try_from_slice(instruction_data)?;
match instruction {
RuleSetInstruction::Create(args) => {
let account_info_iter = &mut accounts.iter();
let payer_info = next_account_info(account_info_iter)?;
let ruleset_pda_info = next_account_info(account_info_iter)?;
let system_program_info = next_account_info(account_info_iter)?;
if !payer_info.is_signer {
return Err(RuleSetError::PayerIsNotSigner.into());
}
let bump = assert_derivation(
program_id,
ruleset_pda_info,
&[
PREFIX.as_bytes(),
payer_info.key.as_ref(),
args.name.as_bytes(),
],
)?;
let ruleset_seeds = &[
PREFIX.as_ref(),
payer_info.key.as_ref(),
args.name.as_ref(),
&[bump],
];
create_or_allocate_account_raw(
*program_id,
ruleset_pda_info,
system_program_info,
payer_info,
args.serialized_rule_set.len(),
ruleset_seeds,
)?;
sol_memcpy(
&mut ruleset_pda_info.try_borrow_mut_data().unwrap(),
&args.serialized_rule_set,
args.serialized_rule_set.len(),
);
Ok(())
}
RuleSetInstruction::Validate(args) => {
let account_info_iter = &mut accounts.iter();
let payer_info = next_account_info(account_info_iter)?;
let ruleset_pda_info = next_account_info(account_info_iter)?;
let _system_program_info = next_account_info(account_info_iter)?;
if !payer_info.is_signer {
return Err(RuleSetError::PayerIsNotSigner.into());
}
let _bump = assert_derivation(
program_id,
ruleset_pda_info,
&[
PREFIX.as_bytes(),
payer_info.key.as_ref(),
args.name.as_bytes(),
],
)?;
let accounts_map = accounts
.iter()
.map(|account| (*account.key, account))
.collect::<HashMap<Pubkey, &AccountInfo>>();
let data = ruleset_pda_info
.data
.try_borrow()
.map_err(|_| RuleSetError::DataTypeMismatch)?;
let rule_set: RuleSet =
rmp_serde::from_slice(&data).map_err(|_| RuleSetError::DataTypeMismatch)?;
msg!("{:#?}", rule_set);
let rule = rule_set
.get(args.operation)
.ok_or(RuleSetError::DataTypeMismatch)?;
if let Err(err) = rule.validate(&accounts_map, &args.payload) {
msg!("Failed to validate: {}", err);
return Err(err);
}
Ok(())
}
}
}
}