use std::sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
};
use dashmap::{DashMap, DashSet};
use simulator_client::{AccountDiffNotification, balances::balance_changes};
use solana_address::Address;
use solana_signature::Signature;
use solana_transaction_status::{EncodedConfirmedTransactionWithStatusMeta, EncodedTransaction};
use tokio::sync::mpsc::UnboundedSender;
use crate::output::{
AccountDiff, AccountDiffRow, OutputEvent, SolChange, TokenChange, Transaction,
};
const RECORDS_RETENTION_SLOTS: u64 = 64;
#[derive(Clone)]
pub(crate) struct RecordsStore {
transactions: Arc<DashMap<Signature, BalanceChanges>>,
account_diffs: Arc<DashSet<DiffKey>>,
tx_max_slot: Arc<AtomicU64>,
diff_max_slot: Arc<AtomicU64>,
total: Arc<AtomicUsize>,
successes: Arc<AtomicUsize>,
received: Arc<AtomicU64>,
dedup_swallowed: Arc<AtomicU64>,
malformed_dropped: Arc<AtomicU64>,
}
type DiffKey = (u64, Signature, Address);
struct BalanceChanges {
slot: u64,
sol_changes: Vec<SolChange>,
token_changes: Vec<TokenChange>,
}
impl RecordsStore {
pub(crate) fn new() -> Self {
Self {
transactions: Arc::new(DashMap::new()),
account_diffs: Arc::new(DashSet::new()),
tx_max_slot: Arc::new(AtomicU64::new(0)),
diff_max_slot: Arc::new(AtomicU64::new(0)),
total: Arc::new(AtomicUsize::new(0)),
successes: Arc::new(AtomicUsize::new(0)),
received: Arc::new(AtomicU64::new(0)),
dedup_swallowed: Arc::new(AtomicU64::new(0)),
malformed_dropped: Arc::new(AtomicU64::new(0)),
}
}
pub(crate) fn total(&self) -> usize {
self.total.load(Ordering::Relaxed)
}
pub(crate) fn successes(&self) -> usize {
self.successes.load(Ordering::Relaxed)
}
pub(crate) fn received(&self) -> u64 {
self.received.load(Ordering::Relaxed)
}
pub(crate) fn dedup_swallowed(&self) -> u64 {
self.dedup_swallowed.load(Ordering::Relaxed)
}
pub(crate) fn malformed_dropped(&self) -> u64 {
self.malformed_dropped.load(Ordering::Relaxed)
}
fn get(
&self,
sig: &Signature,
) -> Option<dashmap::mapref::one::Ref<'_, Signature, BalanceChanges>> {
self.transactions.get(sig)
}
fn note_transaction(&self, sig: Signature, tx: &Transaction) -> bool {
let stored = BalanceChanges {
slot: tx.slot,
sol_changes: tx.sol_changes.clone(),
token_changes: tx.token_changes.clone(),
};
if self.transactions.insert(sig, stored).is_some() {
self.dedup_swallowed.fetch_add(1, Ordering::Relaxed);
return false;
}
self.total.fetch_add(1, Ordering::Relaxed);
if tx.success {
self.successes.fetch_add(1, Ordering::Relaxed);
}
advance_window(&self.tx_max_slot, tx.slot, |cutoff| {
self.transactions.retain(|_, v| v.slot >= cutoff)
});
true
}
fn note_diff(&self, slot: u64, sig: Signature, account: Address) -> bool {
let is_new = self.account_diffs.insert((slot, sig, account));
if !is_new {
self.dedup_swallowed.fetch_add(1, Ordering::Relaxed);
}
advance_window(&self.diff_max_slot, slot, |cutoff| {
self.account_diffs.retain(|(s, _, _)| *s >= cutoff)
});
is_new
}
}
fn advance_window(max_slot: &AtomicU64, slot: u64, prune: impl FnOnce(u64)) {
let prev_max = max_slot.fetch_max(slot, Ordering::Relaxed);
if slot > prev_max
&& let Some(cutoff) = slot.checked_sub(RECORDS_RETENTION_SLOTS)
{
prune(cutoff);
}
}
pub(crate) fn on_account_diff_notification(
records: &RecordsStore,
output_tx: &UnboundedSender<OutputEvent>,
notification: AccountDiffNotification,
) {
records.received.fetch_add(1, Ordering::Relaxed);
let Some(sig) = notification
.signature
.and_then(|s| s.parse::<Signature>().ok())
else {
return;
};
let Some(account) = notification.account.and_then(|a| a.parse::<Address>().ok()) else {
return;
};
let slot = notification.context.slot;
if !records.note_diff(slot, sig, account) {
return;
}
let tx_index = notification.tx_index;
let block_time = notification.block_time;
let diff = AccountDiff {
account,
pre_state: notification.pre,
post_state: notification.post,
};
let row = match records.get(&sig) {
Some(entry) => AccountDiffRow::from_diff(
slot,
sig,
tx_index,
block_time,
&diff,
&entry.sol_changes,
&entry.token_changes,
),
None => AccountDiffRow::from_diff(slot, sig, tx_index, block_time, &diff, &[], &[]),
};
let _ = output_tx.send(OutputEvent::Diff(row));
}
pub(crate) fn on_transaction_notification(
records: &RecordsStore,
output_tx: &UnboundedSender<OutputEvent>,
notification: EncodedConfirmedTransactionWithStatusMeta,
) {
records.received.fetch_add(1, Ordering::Relaxed);
let slot = notification.slot;
let Some(signature) = primary_signature(¬ification.transaction.transaction) else {
records.malformed_dropped.fetch_add(1, Ordering::Relaxed);
tracing::warn!(
slot,
"transactionSubscribe notification missing primary signature; dropping"
);
return;
};
let logs = notification
.transaction
.meta
.as_ref()
.and_then(|meta| match &meta.log_messages {
solana_transaction_status::option_serializer::OptionSerializer::Some(v) => {
Some(v.clone())
}
_ => None,
})
.unwrap_or_default();
let compute_units = notification.transaction.meta.as_ref().and_then(|meta| {
match &meta.compute_units_consumed {
solana_transaction_status::option_serializer::OptionSerializer::Some(units) => {
Some(*units)
}
_ => None,
}
});
let changes = match balance_changes(¬ification.transaction) {
Ok(changes) => changes,
Err(error) => {
records.malformed_dropped.fetch_add(1, Ordering::Relaxed);
tracing::warn!(
slot,
%signature,
%error,
"transactionSubscribe payload could not be decoded into a Transaction; dropping"
);
return;
}
};
let error = notification
.transaction
.meta
.as_ref()
.and_then(|meta| meta.err.as_ref())
.map(ToString::to_string);
let tx = Transaction {
slot,
timestamp: notification.block_time.map(|t| t as u64),
signature,
success: error.is_none(),
error,
compute_units,
logs,
sol_changes: changes.sol.into_iter().map(SolChange::from).collect(),
token_changes: changes.token.into_iter().map(TokenChange::from).collect(),
account_diffs: Vec::new(),
};
if records.note_transaction(signature, &tx) {
let _ = output_tx.send(OutputEvent::Tx(tx));
}
}
fn primary_signature(encoded: &EncodedTransaction) -> Option<Signature> {
let raw = match encoded {
EncodedTransaction::Json(ui_tx) => ui_tx.signatures.first(),
EncodedTransaction::LegacyBinary(_) | EncodedTransaction::Binary(_, _) => None,
EncodedTransaction::Accounts(parsed) => parsed.signatures.first(),
};
raw?.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn sig(label: &str) -> Signature {
let mut bytes = [0_u8; 64];
bytes[..label.len()].copy_from_slice(label.as_bytes());
Signature::from(bytes)
}
fn addr(label: &str) -> Address {
let mut bytes = [0_u8; 32];
bytes[..label.len()].copy_from_slice(label.as_bytes());
Address::from(bytes)
}
fn tx(slot: u64, signature: &str, success: bool) -> Transaction {
Transaction {
slot,
timestamp: None,
signature: sig(signature),
success,
error: None,
compute_units: None,
logs: Vec::new(),
sol_changes: Vec::new(),
token_changes: Vec::new(),
account_diffs: Vec::new(),
}
}
#[test]
fn note_transaction_dedups_repeated_signatures() {
let store = RecordsStore::new();
assert!(store.note_transaction(sig("sig"), &tx(10, "sig", true)));
assert!(!store.note_transaction(sig("sig"), &tx(10, "sig", true)));
assert_eq!(store.total(), 1);
assert_eq!(store.successes(), 1);
assert_eq!(store.dedup_swallowed(), 1);
}
fn notification(pre: &[u64], post: &[u64]) -> EncodedConfirmedTransactionWithStatusMeta {
serde_json::from_value(serde_json::json!({
"slot": 7,
"blockTime": 1_700_000_000,
"transaction": {
"signatures": [sig("sig").to_string()],
"message": {
"header": {
"numRequiredSignatures": 1,
"numReadonlySignedAccounts": 0,
"numReadonlyUnsignedAccounts": 0,
},
"accountKeys": [addr("payer").to_string()],
"recentBlockhash": "hash",
"instructions": [],
},
},
"meta": {
"err": null, "status": {"Ok": null}, "fee": 0,
"preBalances": pre, "postBalances": post,
"logMessages": ["log"],
"computeUnitsConsumed": 1_234,
},
}))
.expect("valid notification")
}
#[test]
fn transaction_notification_emits_record() {
let store = RecordsStore::new();
let (output_tx, mut output_rx) = tokio::sync::mpsc::unbounded_channel();
on_transaction_notification(&store, &output_tx, notification(&[100], &[90]));
let Ok(OutputEvent::Tx(tx)) = output_rx.try_recv() else {
panic!("expected a transaction record");
};
assert_eq!((tx.slot, tx.timestamp), (7, Some(1_700_000_000)));
assert!(tx.success);
assert_eq!(tx.logs, ["log"]);
assert_eq!(tx.compute_units, Some(1_234));
assert_eq!(tx.sol_changes[0].delta(), -10);
}
#[test]
fn malformed_transaction_notification_is_dropped() {
let store = RecordsStore::new();
let (output_tx, mut output_rx) = tokio::sync::mpsc::unbounded_channel();
on_transaction_notification(&store, &output_tx, notification(&[100], &[]));
assert!(output_rx.try_recv().is_err());
assert_eq!(store.malformed_dropped(), 1);
}
#[test]
fn note_diff_dedups_repeated_identities() {
let store = RecordsStore::new();
assert!(store.note_diff(5, sig("sig"), addr("acct")));
assert!(!store.note_diff(5, sig("sig"), addr("acct")));
assert!(store.note_diff(5, sig("sig"), addr("other")));
assert!(store.note_diff(6, sig("sig"), addr("acct")));
assert_eq!(store.dedup_swallowed(), 1);
}
}