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
use core::panic;
use borsh::maybestd::io::Write;
use crate::{
error::GovernanceError,
state::{
enums::{GovernanceAccountType, TransactionExecutionStatus},
legacy::ProposalInstructionV1,
},
PROGRAM_AUTHORITY_SEED,
};
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use solana_program::{
account_info::AccountInfo,
borsh::try_from_slice_unchecked,
clock::UnixTimestamp,
instruction::{AccountMeta, Instruction},
program_error::ProgramError,
program_pack::IsInitialized,
pubkey::Pubkey,
};
use spl_governance_tools::account::{get_account_data, AccountMaxSize};
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
#[repr(C)]
pub struct InstructionData {
pub program_id: Pubkey,
pub accounts: Vec<AccountMetaData>,
pub data: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
#[repr(C)]
pub struct AccountMetaData {
pub pubkey: Pubkey,
pub is_signer: bool,
pub is_writable: bool,
}
impl From<Instruction> for InstructionData {
fn from(instruction: Instruction) -> Self {
InstructionData {
program_id: instruction.program_id,
accounts: instruction
.accounts
.iter()
.map(|a| AccountMetaData {
pubkey: a.pubkey,
is_signer: a.is_signer,
is_writable: a.is_writable,
})
.collect(),
data: instruction.data,
}
}
}
impl From<&InstructionData> for Instruction {
fn from(instruction: &InstructionData) -> Self {
Instruction {
program_id: instruction.program_id,
accounts: instruction
.accounts
.iter()
.map(|a| AccountMeta {
pubkey: a.pubkey,
is_signer: a.is_signer,
is_writable: a.is_writable,
})
.collect(),
data: instruction.data.clone(),
}
}
}
#[repr(C)]
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProposalTransactionV2 {
pub account_type: GovernanceAccountType,
pub proposal: Pubkey,
pub option_index: u8,
pub transaction_index: u16,
pub hold_up_time: u32,
pub instructions: Vec<InstructionData>,
pub executed_at: Option<UnixTimestamp>,
pub execution_status: TransactionExecutionStatus,
pub reserved_v2: [u8; 8],
}
impl AccountMaxSize for ProposalTransactionV2 {
fn get_max_size(&self) -> Option<usize> {
let instructions_size = self
.instructions
.iter()
.map(|i| i.accounts.len() * 34 + i.data.len())
.sum::<usize>()
+ 4;
Some(instructions_size + 98)
}
}
impl IsInitialized for ProposalTransactionV2 {
fn is_initialized(&self) -> bool {
self.account_type == GovernanceAccountType::ProposalTransactionV2
}
}
impl ProposalTransactionV2 {
pub fn serialize<W: Write>(self, writer: &mut W) -> Result<(), ProgramError> {
if self.account_type == GovernanceAccountType::ProposalTransactionV2 {
BorshSerialize::serialize(&self, writer)?
} else if self.account_type == GovernanceAccountType::ProposalInstructionV1 {
if self.instructions.len() != 1 {
panic!("Multiple instructions are not supported by ProposalInstructionV1")
};
if self.reserved_v2 != [0; 8] {
panic!("Extended data not supported by ProposalInstructionV1")
}
let proposal_transaction_data_v1 = ProposalInstructionV1 {
account_type: self.account_type,
proposal: self.proposal,
instruction_index: self.transaction_index,
hold_up_time: self.hold_up_time,
instruction: self.instructions[0].clone(),
executed_at: self.executed_at,
execution_status: self.execution_status,
};
BorshSerialize::serialize(&proposal_transaction_data_v1, writer)?;
}
Ok(())
}
}
pub fn get_proposal_transaction_address_seeds<'a>(
proposal: &'a Pubkey,
option_index: &'a [u8; 1],
instruction_index_le_bytes: &'a [u8; 2],
) -> [&'a [u8]; 4] {
[
PROGRAM_AUTHORITY_SEED,
proposal.as_ref(),
option_index,
instruction_index_le_bytes,
]
}
pub fn get_proposal_transaction_address<'a>(
program_id: &Pubkey,
proposal: &'a Pubkey,
option_index_le_bytes: &'a [u8; 1],
instruction_index_le_bytes: &'a [u8; 2],
) -> Pubkey {
Pubkey::find_program_address(
&get_proposal_transaction_address_seeds(
proposal,
option_index_le_bytes,
instruction_index_le_bytes,
),
program_id,
)
.0
}
pub fn get_proposal_transaction_data(
program_id: &Pubkey,
proposal_transaction_info: &AccountInfo,
) -> Result<ProposalTransactionV2, ProgramError> {
let account_type: GovernanceAccountType =
try_from_slice_unchecked(&proposal_transaction_info.data.borrow())?;
if account_type == GovernanceAccountType::ProposalInstructionV1 {
let proposal_transaction_data_v1 =
get_account_data::<ProposalInstructionV1>(program_id, proposal_transaction_info)?;
return Ok(ProposalTransactionV2 {
account_type,
proposal: proposal_transaction_data_v1.proposal,
option_index: 0,
transaction_index: proposal_transaction_data_v1.instruction_index,
hold_up_time: proposal_transaction_data_v1.hold_up_time,
instructions: vec![proposal_transaction_data_v1.instruction],
executed_at: proposal_transaction_data_v1.executed_at,
execution_status: proposal_transaction_data_v1.execution_status,
reserved_v2: [0; 8],
});
}
get_account_data::<ProposalTransactionV2>(program_id, proposal_transaction_info)
}
pub fn get_proposal_transaction_data_for_proposal(
program_id: &Pubkey,
proposal_transaction_info: &AccountInfo,
proposal: &Pubkey,
) -> Result<ProposalTransactionV2, ProgramError> {
let proposal_transaction_data =
get_proposal_transaction_data(program_id, proposal_transaction_info)?;
if proposal_transaction_data.proposal != *proposal {
return Err(GovernanceError::InvalidProposalForProposalTransaction.into());
}
Ok(proposal_transaction_data)
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use solana_program::{bpf_loader_upgradeable, clock::Epoch};
use super::*;
fn create_test_account_meta_data() -> AccountMetaData {
AccountMetaData {
pubkey: Pubkey::new_unique(),
is_signer: true,
is_writable: false,
}
}
fn create_test_instruction_data() -> Vec<InstructionData> {
vec![InstructionData {
program_id: Pubkey::new_unique(),
accounts: vec![
create_test_account_meta_data(),
create_test_account_meta_data(),
],
data: vec![1, 2, 3],
}]
}
fn create_test_proposal_transaction() -> ProposalTransactionV2 {
ProposalTransactionV2 {
account_type: GovernanceAccountType::ProposalTransactionV2,
proposal: Pubkey::new_unique(),
option_index: 0,
transaction_index: 1,
hold_up_time: 10,
instructions: create_test_instruction_data(),
executed_at: Some(100),
execution_status: TransactionExecutionStatus::Success,
reserved_v2: [0; 8],
}
}
#[test]
fn test_account_meta_data_size() {
let account_meta_data = create_test_account_meta_data();
let size = account_meta_data.try_to_vec().unwrap().len();
assert_eq!(34, size);
}
#[test]
fn test_proposal_transaction_max_size() {
let proposal_transaction = create_test_proposal_transaction();
let size = proposal_transaction.try_to_vec().unwrap().len();
assert_eq!(proposal_transaction.get_max_size(), Some(size));
}
#[test]
fn test_empty_proposal_transaction_max_size() {
let mut proposal_transaction = create_test_proposal_transaction();
proposal_transaction.instructions[0].data = vec![];
proposal_transaction.instructions[0].accounts = vec![];
let size = proposal_transaction.try_to_vec().unwrap().len();
assert_eq!(proposal_transaction.get_max_size(), Some(size));
}
#[test]
fn test_upgrade_instruction_serialization() {
let program_address =
Pubkey::from_str("Hita5Lun87S4MADAF4vGoWEgFm5DyuVqxoWzzqYxS3AD").unwrap();
let buffer_address =
Pubkey::from_str("5XqXkgJGAUwrUHBkxbKpYMGqsRoQLfyqRbYUEkjNY6hL").unwrap();
let governance = Pubkey::from_str("FqSReK9R8QxvFZgdrAwGT3gsYp1ZGfiFjS8xrzyyadn3").unwrap();
let upgrade_instruction = bpf_loader_upgradeable::upgrade(
&program_address,
&buffer_address,
&governance,
&governance,
);
let instruction_data: InstructionData = upgrade_instruction.clone().into();
let mut instruction_bytes = vec![];
instruction_data.serialize(&mut instruction_bytes).unwrap();
let base64 = base64::encode(instruction_bytes.clone());
let instruction =
Instruction::from(&InstructionData::deserialize(&mut &instruction_bytes[..]).unwrap());
assert_eq!(upgrade_instruction, instruction);
assert_eq!(base64,"Aqj2kU6IobDiEBU+92OuKwDCuT0WwSTSwFN6EASAAAAHAAAAchkHXTU9jF+rKpILT6dzsVyNI9NsQy9cab+GGvdwNn0AAfh2HVruy2YibpgcQUmJf5att5YdPXSv1k2pRAKAfpSWAAFDVQuXWos2urmegSPblI813GlTm7CJ/8rv+9yzNE3yfwAB3Gw+apCyfrRNqJ6f1160Htkx+uYZT6FIILQ3WzNA4KwAAQan1RcZLFxRIYzJTD1K8X9Y2u4Im6H9ROPb2YoAAAAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAAAA3Gw+apCyfrRNqJ6f1160Htkx+uYZT6FIILQ3WzNA4KwBAAQAAAADAAAA");
}
#[test]
fn test_proposal_transaction_v1_to_v2_serialization_roundtrip() {
let proposal_transaction_v1_source = ProposalInstructionV1 {
account_type: GovernanceAccountType::ProposalInstructionV1,
proposal: Pubkey::new_unique(),
instruction_index: 1,
hold_up_time: 120,
instruction: create_test_instruction_data()[0].clone(),
executed_at: Some(155),
execution_status: TransactionExecutionStatus::Success,
};
let mut account_data = vec![];
proposal_transaction_v1_source
.serialize(&mut account_data)
.unwrap();
let program_id = Pubkey::new_unique();
let info_key = Pubkey::new_unique();
let mut lamports = 10u64;
let account_info = AccountInfo::new(
&info_key,
false,
false,
&mut lamports,
&mut account_data[..],
&program_id,
false,
Epoch::default(),
);
let proposal_transaction_v2 =
get_proposal_transaction_data(&program_id, &account_info).unwrap();
proposal_transaction_v2
.serialize(&mut &mut **account_info.data.borrow_mut())
.unwrap();
let proposal_transaction_v1_target =
get_account_data::<ProposalInstructionV1>(&program_id, &account_info).unwrap();
assert_eq!(
proposal_transaction_v1_source,
proposal_transaction_v1_target
)
}
}