Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes: get_signature_statuses implementation, epoch progress #31

Merged
merged 2 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 49 additions & 56 deletions crates/core/src/rpc/full.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::simnet::EntryStatus;

use super::utils::{decode_and_deserialize, transform_tx_metadata_to_ui_accounts};
use jsonrpc_core::futures::future::{self, join_all};
use jsonrpc_core::BoxFuture;
Expand Down Expand Up @@ -219,69 +221,61 @@ impl Full for SurfpoolFullRpc {
signature_strs: Vec<String>,
_config: Option<RpcSignatureStatusConfig>,
) -> BoxFuture<Result<RpcResponse<Vec<Option<TransactionStatus>>>>> {
let signatures = signature_strs
.iter()
.map(|s| Signature::from_str(&s).ok())
.collect::<Vec<Option<Signature>>>();

let state_reader = match meta.get_state() {
Ok(s) => s,
Err(e) => return Box::pin(future::err(e.into())),
};
let local_statuses = signatures
.iter()
.map(|signature| {
signature
.map(|signature| {
state_reader.history.get(&signature).map(|tx| {
tx.clone()
.into_status(state_reader.epoch_info.absolute_slot)
})
})
.flatten()
})
.collect::<Vec<Option<TransactionStatus>>>();
let rpc_client = state_reader.rpc_client.clone();

let mut responses = Vec::with_capacity(signature_strs.len());
let mut indices_to_fetch = Vec::with_capacity(signature_strs.len());
for (i, signature_str) in signature_strs.iter().enumerate() {
let Ok(signature) = Signature::from_str(&signature_str) else {
responses.push(None);
continue;
};
let entry = state_reader
.history
.get(&signature)
.map(|entry| match entry {
EntryStatus::Received => TransactionStatus {
slot: 0,
confirmations: None,
status: Ok(()),
err: None,
confirmation_status: None,
},
EntryStatus::Processed(tx) => tx
.clone()
.into_status(state_reader.epoch_info.absolute_slot),
});
if let Some(status) = entry {
responses.push(Some(status));
continue;
}
indices_to_fetch.push((i, signature));
}

let current_slot = state_reader.epoch_info.absolute_slot;
drop(state_reader);
let rpc_client = state_reader.rpc_client.clone();

Box::pin(async move {
let fetched_statuses = join_all(signatures.iter().map(|signature| {
let rpc_client = rpc_client.clone();
async move {
if let Some(signature) = signature {
rpc_client
.get_transaction(&signature, UiTransactionEncoding::Json)
.await
.ok()
.map(|tx| TransactionStatus {
slot: tx.slot,
confirmations: Some((current_slot - tx.slot) as usize),
status: tx.transaction.meta.clone().map_or(Ok(()), |m| m.status),
err: tx.transaction.meta.map(|m| m.err).flatten(),
confirmation_status: Some(TransactionConfirmationStatus::Confirmed),
})
} else {
None
}
}
}))
.await;

let combined_statuses = local_statuses
.iter()
.zip(fetched_statuses)
.map(|(local, fetched)| {
if local.is_some() {
local.clone()
} else {
fetched
}
})
.collect::<Vec<Option<TransactionStatus>>>();
for (i, signature) in indices_to_fetch.iter() {
let response = rpc_client
.get_transaction(&signature, UiTransactionEncoding::Json)
.await
.ok()
.map(|tx| TransactionStatus {
slot: tx.slot,
confirmations: Some((current_slot - tx.slot) as usize),
status: tx.transaction.meta.clone().map_or(Ok(()), |m| m.status),
err: tx.transaction.meta.map(|m| m.err).flatten(),
confirmation_status: Some(TransactionConfirmationStatus::Confirmed),
});
responses.insert(*i, response);
}
Ok(RpcResponse {
context: RpcResponseContext::new(0),
value: combined_statuses,
value: responses,
})
})
}
Expand Down Expand Up @@ -339,7 +333,6 @@ impl Full for SurfpoolFullRpc {
let signature = signatures[0];
let _ = ctx.mempool_tx.send((ctx.id.clone(), unsanitized_tx));

// Todo I believe we're supposed to send back a signature
Ok(signature.to_string())
}

Expand Down Expand Up @@ -557,7 +550,7 @@ impl Full for SurfpoolFullRpc {
let tx = state_reader
.history
.get(&signature)
.map(|tx| tx.clone().into());
.map(|entry| entry.expect_processed().clone().into());

Box::pin(async move {
// TODO: implement new interfaces in LiteSVM to get all the relevant info
Expand Down
50 changes: 43 additions & 7 deletions crates/core/src/simnet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::{
net::SocketAddr,
sync::{Arc, RwLock},
thread::sleep,
time::{Duration, SystemTime, UNIX_EPOCH},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use crate::{
Expand All @@ -36,6 +36,8 @@ use crate::{
types::{RunloopTriggerMode, SurfpoolConfig},
};

const BLOCKHASH_SLOT_TTL: u64 = 75;

#[derive(Debug, Clone)]
pub struct TransactionWithStatusMeta(
u64,
Expand Down Expand Up @@ -147,12 +149,26 @@ impl Into<EncodedConfirmedTransactionWithStatusMeta> for TransactionWithStatusMe

pub struct GlobalState {
pub svm: LiteSVM,
pub history: HashMap<Signature, TransactionWithStatusMeta>,
pub history: HashMap<Signature, EntryStatus>,
pub transactions_processed: u64,
pub epoch_info: EpochInfo,
pub rpc_client: Arc<RpcClient>,
}

pub enum EntryStatus {
Received,
Processed(TransactionWithStatusMeta),
}

impl EntryStatus {
pub fn expect_processed(&self) -> &TransactionWithStatusMeta {
match &self {
EntryStatus::Received => unreachable!(),
EntryStatus::Processed(status) => status,
}
}
}

#[derive(Debug)]
pub enum SimnetEvent {
Ready,
Expand Down Expand Up @@ -185,6 +201,7 @@ pub enum ClockCommand {

pub enum ClockEvent {
Tick,
ExpireBlockHash,
}

pub async fn start(
Expand Down Expand Up @@ -242,6 +259,8 @@ pub async fn start(
.start_http(&server_bind)
.unwrap();
let _ = simnet_events_tx_copy.send(SimnetEvent::Ready);
let _ = simnet_events_tx_copy.send(SimnetEvent::EpochInfoUpdate(epoch_info));

server.wait();
let _ = simnet_events_tx_copy.send(SimnetEvent::Shutdown);
});
Expand All @@ -252,6 +271,8 @@ pub async fn start(
let mut slot_time = config.simnet.slot_time;
let _handle = hiro_system_kit::thread_named("clock").spawn(move || {
let mut enabled = true;
let mut block_hash_timeout = Instant::now();

loop {
match clock_command_rx.try_recv() {
Ok(ClockCommand::Pause) => {
Expand All @@ -271,11 +292,15 @@ pub async fn start(
sleep(Duration::from_millis(slot_time));
if enabled {
let _ = clock_event_tx.send(ClockEvent::Tick);
// Todo: the block expiration is not completely accurate.
if block_hash_timeout.elapsed() > Duration::from_millis(BLOCKHASH_SLOT_TTL * slot_time) {
let _ = clock_event_tx.send(ClockEvent::ExpireBlockHash);
block_hash_timeout = Instant::now();
}
}
}
});

let _ = simnet_events_tx.send(SimnetEvent::EpochInfoUpdate(epoch_info.clone()));
let mut runloop_trigger_mode = config.simnet.runloop_trigger_mode.clone();
let mut transactions_to_process = vec![];
loop {
Expand All @@ -289,6 +314,11 @@ pub async fn start(
create_slot = true;
}
}
ClockEvent::ExpireBlockHash => {
if let Ok(mut ctx) = context.write() {
ctx.svm.expire_blockhash();
}
}
}
},
Err(_) => {},
Expand Down Expand Up @@ -316,8 +346,15 @@ pub async fn start(
Err(_) => {},
},
recv(mempool_rx) -> msg => match msg {
Ok(transaction) => {
transactions_to_process.push(transaction);
Ok((key, transaction)) => {
let signature = transaction.signatures[0].clone();
transactions_to_process.push((key, transaction));
if let Ok(mut ctx) = context.write() {
ctx.history.insert(
signature,
EntryStatus::Received,
);
}
},
Err(_) => {},
},
Expand Down Expand Up @@ -377,7 +414,7 @@ pub async fn start(
let slot = ctx.epoch_info.absolute_slot;
ctx.history.insert(
tx.signatures[0],
TransactionWithStatusMeta(slot, tx, meta, err),
EntryStatus::Processed(TransactionWithStatusMeta(slot, tx, meta, err)),
);
}
ctx.epoch_info.slot_index += 1;
Expand All @@ -386,7 +423,6 @@ pub async fn start(
ctx.epoch_info.slot_index = 0;
ctx.epoch_info.epoch += 1;
}
ctx.svm.expire_blockhash();
let clock: Clock = Clock {
slot: ctx.epoch_info.slot_index,
epoch: ctx.epoch_info.epoch,
Expand Down
Loading