Skip to content

Commit

Permalink
refactor: use ordered publisher list
Browse files Browse the repository at this point in the history
This change brings down the average cost of a price update without
aggregation from 5k to 2k because binary search requires much less
lookups. There are mechanims implemented in the code to make sure
that upon the upgrade we sort the array without adding overhead to
the happy path (working binary search). Also add_publisher now does
an insertion sort to keep the list sorted and del_publisher won't
change the order of the list.
  • Loading branch information
ali-bahjati committed May 7, 2024
1 parent ceb4a32 commit 58afc9d
Show file tree
Hide file tree
Showing 3 changed files with 223 additions and 14 deletions.
24 changes: 21 additions & 3 deletions program/rust/src/processor/add_publisher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ pub fn add_publisher(
let cmd_args = load::<AddPublisherArgs>(instruction_data)?;

pyth_assert(
instruction_data.len() == size_of::<AddPublisherArgs>()
&& cmd_args.publisher != Pubkey::default(),
instruction_data.len() == size_of::<AddPublisherArgs>(),
ProgramError::InvalidArgument,
)?;

Expand All @@ -67,19 +66,38 @@ pub fn add_publisher(
return Err(ProgramError::InvalidArgument);
}

// Use the call with the default pubkey (000..) as a trigger to sort the publishers as a
// migration step from unsorted list to sorted list.
if cmd_args.publisher == Pubkey::default() {
// Using sort_by_cached_key because it sorts the keys first
// and performs swaps on the values in the end which results
// in linear swaps of comp_ values.
price_data.comp_.sort_by_cached_key(|x| x.pub_);
return Ok(());
}

for i in 0..(try_convert::<u32, usize>(price_data.num_)?) {
if cmd_args.publisher == price_data.comp_[i].pub_ {
return Err(ProgramError::InvalidArgument);
}
}

let current_index: usize = try_convert(price_data.num_)?;
let mut current_index: usize = try_convert(price_data.num_)?;
sol_memset(
bytes_of_mut(&mut price_data.comp_[current_index]),
0,
size_of::<PriceComponent>(),
);
price_data.comp_[current_index].pub_ = cmd_args.publisher;

// Shift the element back to keep the publishers components sorted.
while current_index > 0
&& price_data.comp_[current_index].pub_ < price_data.comp_[current_index - 1].pub_
{
price_data.comp_.swap(current_index, current_index - 1);
current_index -= 1;
}

price_data.num_ += 1;
price_data.header.size = try_convert::<_, u32>(PriceAccount::INITIAL_SIZE)?;
Ok(())
Expand Down
132 changes: 121 additions & 11 deletions program/rust/src/processor/upd_price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use {
crate::{
accounts::{
PriceAccount,
PriceComponent,
PriceInfo,
PythOracleSerialize,
UPD_PRICE_WRITE_SEED,
Expand Down Expand Up @@ -127,7 +128,7 @@ pub fn upd_price(
// Check clock
let clock = Clock::from_account_info(clock_account)?;

let mut publisher_index: usize = 0;
let publisher_index: usize;
let latest_aggregate_price: PriceInfo;

// The price_data borrow happens in a scope because it must be
Expand All @@ -137,17 +138,15 @@ pub fn upd_price(
// Verify that symbol account is initialized
let price_data = load_checked::<PriceAccount>(price_account, cmd_args.header.version)?;

// Verify that publisher is authorized
while publisher_index < try_convert::<u32, usize>(price_data.num_)? {
if price_data.comp_[publisher_index].pub_ == *funding_account.key {
break;
publisher_index = match find_publisher_index(
&price_data.comp_[..try_convert::<u32, usize>(price_data.num_)?],
funding_account.key,
) {
Some(index) => index,
None => {
return Err(OracleError::PermissionViolation.into());
}
publisher_index += 1;
}
pyth_assert(
publisher_index < try_convert::<u32, usize>(price_data.num_)?,
OracleError::PermissionViolation.into(),
)?;
};

latest_aggregate_price = price_data.agg_;
let latest_publisher_price = price_data.comp_[publisher_index].latest_;
Expand Down Expand Up @@ -281,6 +280,62 @@ pub fn upd_price(
Ok(())
}

/// Find the index of the publisher in the list of components.
///
/// This method first tries to binary search for the publisher's key in the list of components
/// to get the result faster if the list is sorted. If the list is not sorted, it falls back to
/// a linear search.
#[inline]
fn find_publisher_index(comps: &[PriceComponent], key: &Pubkey) -> Option<usize> {
// Verify that publisher is authorized by initially binary searching
// for the publisher's component in the price account. The binary
// search might not work if the publisher list is not sorted; therefore
// we fall back to a linear search.
let mut binary_search_result = None;

{
// Binary search to find the publisher key. Rust std binary search is not used because
// they guarantee valid outcome only if the array is sorted whereas we want to rely on
// a Equal match if it is a result on an unsorted array. Currently the rust
// implementation behaves the same but we do not want to rely on api internals.
let mut left = 0;
let mut right = comps.len();
while left < right {
let mid = left + (right - left) / 2;
match comps[mid].pub_.cmp(key) {
std::cmp::Ordering::Less => {
left = mid + 1;
}
std::cmp::Ordering::Greater => {
right = mid;
}
std::cmp::Ordering::Equal => {
binary_search_result = Some(mid);
break;
}
}
}
}

match binary_search_result {
Some(index) => Some(index),
None => {
let mut index = 0;
while index < comps.len() {
if comps[index].pub_ == *key {
break;
}
index += 1;
}
if index == comps.len() {
None
} else {
Some(index)
}
}
}
}

#[allow(dead_code)]
// Wrapper struct for the accounts required to add data to the accumulator program.
struct MessageBufferAccounts<'a, 'b: 'a> {
Expand All @@ -289,3 +344,58 @@ struct MessageBufferAccounts<'a, 'b: 'a> {
oracle_auth_pda: &'a AccountInfo<'b>,
message_buffer_data: &'a AccountInfo<'b>,
}

#[cfg(test)]
mod test {
use {
super::*,
crate::accounts::PriceComponent,
solana_program::pubkey::Pubkey,
};

fn dummy_price_component(pub_: Pubkey) -> PriceComponent {
let dummy_price_info = PriceInfo {
price_: 0,
conf_: 0,
status_: 0,
pub_slot_: 0,
corp_act_status_: 0,
};

PriceComponent {
latest_: dummy_price_info,
agg_: dummy_price_info,
pub_,
}
}

/// Test the find_publisher_index method works with an unordered list of components.
#[test]
pub fn test_find_publisher_index_unordered_comp() {
let comps = (0..64)
.map(|_| dummy_price_component(Pubkey::new_unique()))
.collect::<Vec<_>>();

comps.iter().enumerate().for_each(|(idx, comp)| {
assert_eq!(find_publisher_index(&comps, &comp.pub_), Some(idx));
});

assert_eq!(find_publisher_index(&comps, &Pubkey::new_unique()), None);
}

/// Test the find_publisher_index method works with a sorted list of components.
#[test]
pub fn test_find_publisher_index_ordered_comp() {
let mut comps = (0..64)
.map(|_| dummy_price_component(Pubkey::new_unique()))
.collect::<Vec<_>>();

comps.sort_by_key(|comp| comp.pub_);

comps.iter().enumerate().for_each(|(idx, comp)| {
assert_eq!(find_publisher_index(&comps, &comp.pub_), Some(idx));
});

assert_eq!(find_publisher_index(&comps, &Pubkey::new_unique()), None);
}
}
81 changes: 81 additions & 0 deletions program/rust/src/tests/test_upd_price_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,87 @@ fn test_upd_price_v2() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

#[test]
fn test_upd_works_with_unordered_publisher_set() -> Result<(), Box<dyn std::error::Error>> {
let mut instruction_data = [0u8; size_of::<UpdPriceArgs>()];

let program_id = Pubkey::new_unique();

let mut price_setup = AccountSetup::new::<PriceAccount>(&program_id);
let mut price_account = price_setup.as_account_info();
price_account.is_signer = false;
PriceAccount::initialize(&price_account, PC_VERSION).unwrap();

let mut publishers_setup: Vec<_> = (0..20).map(|_| AccountSetup::new_funding()).collect();
let mut publishers: Vec<_> = publishers_setup
.iter_mut()
.map(|s| s.as_account_info())
.collect();

publishers.sort_by_key(|x| x.key);

{
let mut price_data = load_checked::<PriceAccount>(&price_account, PC_VERSION).unwrap();
price_data.num_ = 20;
// Store the publishers in reverse order
publishers
.iter()
.rev()
.enumerate()
.for_each(|(i, account)| {
price_data.comp_[i].pub_ = *account.key;
});
}

let mut clock_setup = AccountSetup::new_clock();
let mut clock_account = clock_setup.as_account_info();
clock_account.is_signer = false;
clock_account.is_writable = false;

update_clock_slot(&mut clock_account, 1);

for (i, publisher) in publishers.iter().enumerate() {
populate_instruction(&mut instruction_data, (i + 100) as i64, 10, 1);
process_instruction(
&program_id,
&[
publisher.clone(),
price_account.clone(),
clock_account.clone(),
],
&instruction_data,
)?;
}

update_clock_slot(&mut clock_account, 2);

// Trigger the aggregate calculation by sending another price
// update
populate_instruction(&mut instruction_data, 100, 10, 2);
process_instruction(
&program_id,
&[
publishers[0].clone(),
price_account.clone(),
clock_account.clone(),
],
&instruction_data,
)?;


let price_data = load_checked::<PriceAccount>(&price_account, PC_VERSION).unwrap();

// The result will be the following only if all the
// publishers prices are included in the aggregate.
assert_eq!(price_data.valid_slot_, 1);
assert_eq!(price_data.agg_.pub_slot_, 2);
assert_eq!(price_data.agg_.price_, 109);
assert_eq!(price_data.agg_.conf_, 8);
assert_eq!(price_data.agg_.status_, PC_STATUS_TRADING);

Ok(())
}

// Create an upd_price instruction with the provided parameters
fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) {
let mut cmd = load_mut::<UpdPriceArgs>(instruction_data).unwrap();
Expand Down

0 comments on commit 58afc9d

Please sign in to comment.