Skip to content

Commit 5f9e29f

Browse files
committed
refactor: unify env var handling
1 parent f3deb0f commit 5f9e29f

File tree

2 files changed

+68
-109
lines changed

2 files changed

+68
-109
lines changed

runtime/src/bank/pyth_accumulator.rs

Lines changed: 58 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,49 @@ use {
22
super::Bank,
33
crate::accounts_index::{ScanConfig, ScanError},
44
byteorder::LittleEndian,
5+
byteorder::ReadBytesExt,
56
itertools::Itertools,
67
log::*,
78
pyth_oracle::validator::AggregationError,
9+
pythnet_sdk::{
10+
accumulators::{merkle::MerkleAccumulator, Accumulator},
11+
hashers::keccak256_160::Keccak160,
12+
wormhole::{AccumulatorSequenceTracker, MessageData, PostedMessageUnreliableData},
13+
},
814
solana_sdk::{
915
account::{AccountSharedData, ReadableAccount},
10-
feature_set,
16+
borsh, feature_set,
1117
hash::hashv,
1218
pubkey::Pubkey,
1319
},
14-
std::{
15-
env::{self, VarError},
16-
str::FromStr,
17-
},
20+
std::env::{self, VarError},
1821
};
1922

2023
pub const ACCUMULATOR_RING_SIZE: u32 = 10_000;
2124

2225
lazy_static! {
23-
pub static ref ORACLE_PUBKEY: Pubkey = match env::var("PYTH_ORACLE_PUBKEY") {
24-
Ok(value) => value
26+
pub static ref MESSAGE_BUFFER_PID: Pubkey = env_pubkey_or(
27+
"MESSAGE_BUFFER_PID",
28+
Pubkey::new_from_array(pythnet_sdk::MESSAGE_BUFFER_PID),
29+
);
30+
pub static ref ACCUMULATOR_EMITTER_ADDR: Pubkey = env_pubkey_or(
31+
"ACCUMULATOR_EMITTER_ADDR",
32+
Pubkey::new_from_array(pythnet_sdk::ACCUMULATOR_EMITTER_ADDRESS),
33+
);
34+
pub static ref ACCUMULATOR_SEQUENCE_ADDR: Pubkey = env_pubkey_or(
35+
"ACCUMULATOR_SEQUENCE_ADDR",
36+
Pubkey::new_from_array(pythnet_sdk::pythnet::ACCUMULATOR_SEQUENCE_ADDR),
37+
);
38+
pub static ref WORMHOLE_PID: Pubkey = env_pubkey_or(
39+
"WORMHOLE_PID",
40+
Pubkey::new_from_array(pythnet_sdk::pythnet::WORMHOLE_PID),
41+
);
42+
pub static ref ORACLE_PID: Pubkey = env_pubkey_or(
43+
"ORACLE_PID",
44+
"FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH"
2545
.parse()
26-
.expect("invalid value of PYTH_ORACLE_PUBKEY env var"),
27-
Err(VarError::NotPresent) => {
28-
// Pythnet oracle program address
29-
"FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH".parse().unwrap()
30-
}
31-
Err(VarError::NotUnicode(err)) => {
32-
panic!("invalid value of PYTH_ORACLE_PUBKEY env var: {err:?}");
33-
}
34-
};
46+
.unwrap(),
47+
);
3548
}
3649

3750
/// Accumulator specific error type. It would be nice to use `transaction::Error` but it does
@@ -82,16 +95,19 @@ pub fn update_accumulator(bank: &Bank) {
8295

8396
/// Read the pubkey from the environment variable `var` or return `default`
8497
/// if the variable is not set.
85-
fn env_pubkey_or(
86-
var: &str,
87-
default: Pubkey,
88-
) -> std::result::Result<Pubkey, AccumulatorUpdateErrorV1> {
89-
Ok(std::env::var(var)
90-
.as_deref()
91-
.map(Pubkey::from_str)
92-
.ok()
93-
.transpose()?
94-
.unwrap_or(default))
98+
fn env_pubkey_or(var: &str, default: Pubkey) -> Pubkey {
99+
match env::var(var) {
100+
Ok(value) => value.parse().unwrap_or_else(|err| {
101+
panic!(
102+
"failed to parse env var {}={:?} as pubkey: {}",
103+
var, value, err
104+
)
105+
}),
106+
Err(VarError::NotPresent) => default,
107+
Err(VarError::NotUnicode(value)) => {
108+
panic!("invalid value of env var {}={:?}: not unicode", var, value);
109+
}
110+
}
95111
}
96112

97113
/// Get all accumulator related pubkeys from environment variables
@@ -100,64 +116,30 @@ pub fn get_accumulator_keys() -> Vec<(
100116
&'static str,
101117
std::result::Result<Pubkey, AccumulatorUpdateErrorV1>,
102118
)> {
103-
use pythnet_sdk::{pythnet, ACCUMULATOR_EMITTER_ADDRESS, MESSAGE_BUFFER_PID};
104-
let accumulator_keys = vec![
105-
(
106-
"MESSAGE_BUFFER_PID",
107-
Pubkey::new_from_array(MESSAGE_BUFFER_PID),
108-
),
109-
// accumulator emitter address should always be the same regardless
110-
// of environment but checking here for completeness
111-
(
112-
"ACCUMULATOR_EMITTER_ADDR",
113-
Pubkey::new_from_array(ACCUMULATOR_EMITTER_ADDRESS),
114-
),
115-
(
116-
"ACCUMULATOR_SEQUENCE_ADDR",
117-
Pubkey::new_from_array(pythnet::ACCUMULATOR_SEQUENCE_ADDR),
118-
),
119-
(
120-
"WORMHOLE_PID",
121-
Pubkey::new_from_array(pythnet::WORMHOLE_PID),
122-
),
123-
];
124-
let accumulator_pubkeys: Vec<(&str, std::result::Result<Pubkey, AccumulatorUpdateErrorV1>)> =
125-
accumulator_keys
126-
.iter()
127-
.map(|(k, d)| (*k, env_pubkey_or(k, *d)))
128-
.collect();
129-
accumulator_pubkeys
119+
vec![
120+
("MESSAGE_BUFFER_PID", Ok(*MESSAGE_BUFFER_PID)),
121+
("ACCUMULATOR_EMITTER_ADDR", Ok(*ACCUMULATOR_EMITTER_ADDR)),
122+
("ACCUMULATOR_SEQUENCE_ADDR", Ok(*ACCUMULATOR_SEQUENCE_ADDR)),
123+
("WORMHOLE_PID", Ok(*WORMHOLE_PID)),
124+
("ORACLE_PID", Ok(*ORACLE_PID)),
125+
]
130126
}
131127

132128
pub fn update_v1<'a>(
133129
bank: &Bank,
134130
v2_messages: &[Vec<u8>],
135131
use_message_buffers: bool,
136132
) -> std::result::Result<(), AccumulatorUpdateErrorV1> {
137-
use {
138-
byteorder::ReadBytesExt,
139-
pythnet_sdk::{
140-
accumulators::{merkle::MerkleAccumulator, Accumulator},
141-
hashers::keccak256_160::Keccak160,
142-
MESSAGE_BUFFER_PID,
143-
},
144-
solana_sdk::borsh,
145-
};
146-
147133
// Use the current Clock to determine the index into the accumulator ring buffer.
148134
let ring_index = (bank.slot() % 10_000) as u32;
149135

150136
// Find all accounts owned by the Message Buffer program using get_program_accounts, and
151137
// extract the account data.
152-
let message_buffer_pid = env_pubkey_or(
153-
"MESSAGE_BUFFER_PID",
154-
Pubkey::new_from_array(MESSAGE_BUFFER_PID),
155-
)?;
156138

157139
let message_buffer_accounts;
158140
let v1_messages = if use_message_buffers {
159141
message_buffer_accounts = bank
160-
.get_program_accounts(&message_buffer_pid, &ScanConfig::new(true))
142+
.get_program_accounts(&MESSAGE_BUFFER_PID, &ScanConfig::new(true))
161143
.map_err(AccumulatorUpdateErrorV1::GetProgramAccounts)?;
162144

163145
let preimage = b"account:MessageBuffer";
@@ -266,28 +248,12 @@ fn post_accumulator_attestation(
266248
>,
267249
ring_index: u32,
268250
) -> std::result::Result<(), AccumulatorUpdateErrorV1> {
269-
use pythnet_sdk::{
270-
pythnet,
271-
wormhole::{AccumulatorSequenceTracker, MessageData, PostedMessageUnreliableData},
272-
ACCUMULATOR_EMITTER_ADDRESS,
273-
};
274-
275-
let accumulator_sequence_addr = env_pubkey_or(
276-
"ACCUMULATOR_SEQUENCE_ADDR",
277-
Pubkey::new_from_array(pythnet::ACCUMULATOR_SEQUENCE_ADDR),
278-
)?;
279-
280-
let accumulator_emitter_addr = env_pubkey_or(
281-
"ACCUMULATOR_EMITTER_ADDR",
282-
Pubkey::new_from_array(ACCUMULATOR_EMITTER_ADDRESS),
283-
)?;
284-
285251
// Wormhole uses a Sequence account that is incremented each time a message is posted. As
286252
// we aren't calling Wormhole we need to bump this ourselves. If it doesn't exist, we just
287253
// create it instead.
288254
let mut sequence: AccumulatorSequenceTracker = {
289255
let data = bank
290-
.get_account_with_fixed_root(&accumulator_sequence_addr)
256+
.get_account_with_fixed_root(&ACCUMULATOR_SEQUENCE_ADDR)
291257
.unwrap_or_default();
292258
let data = data.data();
293259
solana_sdk::borsh::try_from_slice_unchecked(data)
@@ -311,7 +277,7 @@ fn post_accumulator_attestation(
311277
nonce: 0,
312278
sequence: sequence.sequence,
313279
emitter_chain: 26,
314-
emitter_address: accumulator_emitter_addr.to_bytes(),
280+
emitter_address: ACCUMULATOR_EMITTER_ADDR.to_bytes(),
315281
payload: acc.serialize(bank.slot(), ACCUMULATOR_RING_SIZE),
316282
}
317283
} else {
@@ -322,26 +288,21 @@ fn post_accumulator_attestation(
322288
submission_time: bank.clock().unix_timestamp as u32,
323289
sequence: sequence.sequence,
324290
emitter_chain: 26,
325-
emitter_address: accumulator_emitter_addr.to_bytes(),
291+
emitter_address: ACCUMULATOR_EMITTER_ADDR.to_bytes(),
326292
payload: acc.serialize(bank.slot(), ACCUMULATOR_RING_SIZE),
327293
..Default::default()
328294
}
329295
},
330296
};
331297

332298
debug!("Accumulator: Wormhole message data: {:?}", message.message);
333-
let wormhole_pid = env_pubkey_or(
334-
"WORMHOLE_PID",
335-
Pubkey::new_from_array(pythnet::WORMHOLE_PID),
336-
)?;
337-
338299
// Now we can bump and write the Sequence account.
339300
sequence.sequence += 1;
340301
let sequence = solana_sdk::borsh::BorshSerialize::try_to_vec(&sequence)
341302
.map_err(|_| AccumulatorUpdateErrorV1::FailedSequenceSerialization)?;
342303
let sequence_balance = bank.get_minimum_balance_for_rent_exemption(sequence.len());
343304
let sequence_account = {
344-
let owner = &wormhole_pid;
305+
let owner = &WORMHOLE_PID;
345306
let mut account = AccountSharedData::new(sequence_balance, sequence.len(), owner);
346307
account.set_data(sequence);
347308
account
@@ -352,7 +313,7 @@ fn post_accumulator_attestation(
352313
.map_err(|_| AccumulatorUpdateErrorV1::FailedMessageSerialization)?;
353314
let message_balance = bank.get_minimum_balance_for_rent_exemption(message.len());
354315
let message_account = {
355-
let owner = &wormhole_pid;
316+
let owner = &WORMHOLE_PID;
356317
let mut account = AccountSharedData::new(message_balance, message.len(), owner);
357318
account.set_data(message);
358319
account
@@ -362,10 +323,10 @@ fn post_accumulator_attestation(
362323
// for RPC users to select the message for an associated VAA.
363324
let (message_pda, _) = Pubkey::find_program_address(
364325
&[b"AccumulatorMessage", &ring_index.to_be_bytes()],
365-
&wormhole_pid,
326+
&WORMHOLE_PID,
366327
);
367328

368-
bank.store_account_and_update_capitalization(&accumulator_sequence_addr, &sequence_account);
329+
bank.store_account_and_update_capitalization(&ACCUMULATOR_SEQUENCE_ADDR, &sequence_account);
369330

370331
info!("Accumulator: Writing wormhole message to {:?}", message_pda);
371332
bank.store_account_and_update_capitalization(&message_pda, &message_account);
@@ -375,7 +336,7 @@ fn post_accumulator_attestation(
375336

376337
pub fn update_v2(bank: &Bank) -> std::result::Result<(), AccumulatorUpdateErrorV1> {
377338
let accounts = bank
378-
.get_program_accounts(&ORACLE_PUBKEY, &ScanConfig::new(true))
339+
.get_program_accounts(&ORACLE_PID, &ScanConfig::new(true))
379340
.map_err(AccumulatorUpdateErrorV1::GetProgramAccounts)?;
380341

381342
let mut any_v1_aggregations = false;

runtime/src/bank/pyth_accumulator_tests.rs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::{
22
bank::{
3-
pyth_accumulator::{get_accumulator_keys, ACCUMULATOR_RING_SIZE, ORACLE_PUBKEY},
3+
pyth_accumulator::{get_accumulator_keys, ACCUMULATOR_RING_SIZE, ORACLE_PID},
44
Bank,
55
},
66
genesis_utils::{create_genesis_config_with_leader, GenesisConfigInfo},
@@ -129,17 +129,16 @@ fn test_update_accumulator_sysvar() {
129129
// Store Message account so the accumulator sysvar updater can find it.
130130
bank.store_account(&price_message_key.pubkey(), &price_message_account);
131131

132-
let (price_feed_key, _bump) = Pubkey::find_program_address(&[b"123"], &ORACLE_PUBKEY);
133-
let mut price_feed_account =
134-
AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PUBKEY);
132+
let (price_feed_key, _bump) = Pubkey::find_program_address(&[b"123"], &ORACLE_PID);
133+
let mut price_feed_account = AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PID);
135134
let _ = PriceAccount::initialize(
136135
&AccountInfo::new(
137136
&price_feed_key.to_bytes().into(),
138137
false,
139138
true,
140139
&mut 0,
141140
&mut price_feed_account.data_mut(),
142-
&ORACLE_PUBKEY.to_bytes().into(),
141+
&ORACLE_PID.to_bytes().into(),
143142
false,
144143
Epoch::default(),
145144
),
@@ -419,17 +418,16 @@ fn test_update_accumulator_end_of_block() {
419418
// Store Message account so the accumulator sysvar updater can find it.
420419
bank.store_account(&price_message_key.pubkey(), &price_message_account);
421420

422-
let (price_feed_key, _bump) = Pubkey::find_program_address(&[b"123"], &ORACLE_PUBKEY);
423-
let mut price_feed_account =
424-
AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PUBKEY);
421+
let (price_feed_key, _bump) = Pubkey::find_program_address(&[b"123"], &ORACLE_PID);
422+
let mut price_feed_account = AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PID);
425423
PriceAccount::initialize(
426424
&AccountInfo::new(
427425
&price_feed_key.to_bytes().into(),
428426
false,
429427
true,
430428
&mut 0,
431429
&mut price_feed_account.data_mut(),
432-
&ORACLE_PUBKEY.to_bytes().into(),
430+
&ORACLE_PID.to_bytes().into(),
433431
false,
434432
Epoch::default(),
435433
),
@@ -688,14 +686,14 @@ fn test_accumulator_v2() {
688686
bank = new_from_parent(&Arc::new(bank)); // Advance slot 2.
689687

690688
let generate_price = |seeds, generate_buffers: bool| {
691-
let (price_feed_key, _bump) = Pubkey::find_program_address(&[seeds], &ORACLE_PUBKEY);
689+
let (price_feed_key, _bump) = Pubkey::find_program_address(&[seeds], &ORACLE_PID);
692690
let mut price_feed_account =
693-
AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PUBKEY);
691+
AccountSharedData::new(42, size_of::<PriceAccount>(), &ORACLE_PID);
694692

695693
let messages = {
696694
let price_feed_info_key = &price_feed_key.to_bytes().into();
697695
let price_feed_info_lamports = &mut 0;
698-
let price_feed_info_owner = &ORACLE_PUBKEY.to_bytes().into();
696+
let price_feed_info_owner = &ORACLE_PID.to_bytes().into();
699697
let price_feed_info_data = price_feed_account.data_mut();
700698
let price_feed_info = AccountInfo::new(
701699
price_feed_info_key,

0 commit comments

Comments
 (0)