use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use miden_protocol::account::{
Account,
AccountCode,
AccountHeader,
AccountId,
AccountPatch,
AccountStoragePatch,
AccountVaultPatch,
StorageMapPatch,
StorageMapPatchEntries,
StorageSlotName,
StorageSlotPatch,
StorageValuePatch,
};
use miden_protocol::block::{BlockHeader, BlockNumber};
use miden_protocol::crypto::merkle::mmr::{InOrderIndex, MmrPeaks};
use miden_protocol::errors::AccountPatchError;
use miden_protocol::note::{NoteId, Nullifier};
use miden_protocol::transaction::TransactionId;
use miden_protocol::{Felt, ONE, Word};
use super::SyncSummary;
use crate::note::{NoteUpdateTracker, NoteUpdateType};
use crate::rpc::domain::transaction::TransactionRecord as RpcTransactionRecord;
use crate::transaction::{DiscardCause, TransactionRecord, TransactionStatus};
#[derive(Default)]
pub struct StateSyncUpdate {
pub block_num: BlockNumber,
pub partial_blockchain_updates: PartialBlockchainUpdates,
pub note_updates: NoteUpdateTracker,
pub transaction_updates: TransactionUpdateTracker,
pub account_updates: AccountUpdates,
}
impl From<&StateSyncUpdate> for SyncSummary {
fn from(value: &StateSyncUpdate) -> Self {
let new_public_note_ids = value
.note_updates
.updated_input_notes()
.filter_map(|note_update| {
let note = note_update.inner();
if let NoteUpdateType::Insert = note_update.update_type() {
note.id()
} else {
None
}
})
.collect();
let committed_note_ids: BTreeSet<NoteId> = value
.note_updates
.updated_input_notes()
.filter_map(|note_update| {
let note = note_update.inner();
if matches!(
note_update.update_type(),
NoteUpdateType::Update | NoteUpdateType::InsertCommitted
) && note.is_committed()
{
note.id()
} else {
None
}
})
.chain(value.note_updates.updated_output_notes().filter_map(|note_update| {
let note = note_update.inner();
if let NoteUpdateType::Update = note_update.update_type() {
note.is_committed().then_some(note.id())
} else {
None
}
}))
.collect();
let consumed_note_ids: BTreeSet<NoteId> =
value.note_updates.consumed_input_note_ids().collect();
SyncSummary::new(
value.block_num,
new_public_note_ids,
Vec::new(),
committed_note_ids.into_iter().collect(),
consumed_note_ids.into_iter().collect(),
value
.account_updates
.updated_public_accounts()
.iter()
.map(PublicAccountUpdate::id)
.collect(),
value
.account_updates
.mismatched_private_accounts()
.iter()
.map(|(id, _)| *id)
.collect(),
value.transaction_updates.committed_transactions().map(|t| t.id).collect(),
)
}
}
#[derive(Debug, Clone, Default)]
pub struct PartialBlockchainUpdates {
block_headers: BTreeMap<BlockNumber, (BlockHeader, bool)>,
new_authentication_nodes: Vec<(InOrderIndex, Word)>,
pub new_peaks: MmrPeaks,
}
impl PartialBlockchainUpdates {
pub fn insert(
&mut self,
block_header: BlockHeader,
has_client_notes: bool,
new_authentication_nodes: Vec<(InOrderIndex, Word)>,
) {
self.block_headers
.entry(block_header.block_num())
.and_modify(|(_, existing_has_notes)| {
*existing_has_notes |= has_client_notes;
})
.or_insert((block_header, has_client_notes));
self.new_authentication_nodes.extend(new_authentication_nodes);
}
pub fn block_headers(&self) -> impl Iterator<Item = &(BlockHeader, bool)> {
self.block_headers.values()
}
pub fn new_authentication_nodes(&self) -> &[(InOrderIndex, Word)] {
&self.new_authentication_nodes
}
}
#[derive(Default)]
pub struct TransactionUpdateTracker {
transactions: BTreeMap<TransactionId, TransactionRecord>,
external_nullifier_accounts: BTreeMap<Nullifier, AccountId>,
}
impl TransactionUpdateTracker {
pub fn new(transactions: Vec<TransactionRecord>) -> Self {
let transactions =
transactions.into_iter().map(|tx| (tx.id, tx)).collect::<BTreeMap<_, _>>();
Self {
transactions,
external_nullifier_accounts: BTreeMap::new(),
}
}
pub fn committed_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
self.transactions
.values()
.filter(|tx| matches!(tx.status, TransactionStatus::Committed { .. }))
}
pub fn discarded_transactions(&self) -> impl Iterator<Item = &TransactionRecord> {
self.transactions
.values()
.filter(|tx| matches!(tx.status, TransactionStatus::Discarded(_)))
}
fn mutable_pending_transactions(&mut self) -> impl Iterator<Item = &mut TransactionRecord> {
self.transactions
.values_mut()
.filter(|tx| matches!(tx.status, TransactionStatus::Pending))
}
pub fn updated_transaction_ids(&self) -> impl Iterator<Item = TransactionId> {
self.committed_transactions()
.chain(self.discarded_transactions())
.map(|tx| tx.id)
}
pub fn external_nullifier_account(&self, nullifier: &Nullifier) -> Option<AccountId> {
self.external_nullifier_accounts.get(nullifier).copied()
}
pub fn apply_transaction_inclusion(&mut self, record: &RpcTransactionRecord, timestamp: u64) {
let header = &record.transaction_header;
let account_id = header.account_id();
if let Some(transaction) = self.transactions.get_mut(&header.id()) {
transaction.commit_transaction(record.block_num, timestamp);
return;
}
if let Some(transaction) = self.transactions.values_mut().find(|tx| {
tx.details.account_id == account_id
&& tx.details.init_account_state == header.initial_state_commitment()
}) {
transaction.commit_transaction(record.block_num, timestamp);
return;
}
for commitment in header.input_notes().iter() {
self.external_nullifier_accounts.insert(commitment.nullifier(), account_id);
}
}
pub fn apply_sync_height_update(
&mut self,
new_sync_height: BlockNumber,
tx_discard_delta: Option<u32>,
) {
if let Some(tx_discard_delta) = tx_discard_delta {
self.discard_transaction_with_predicate(
|transaction| {
transaction.details.submission_height
< new_sync_height.checked_sub(tx_discard_delta).unwrap_or_default()
},
DiscardCause::Stale,
);
}
self.discard_transaction_with_predicate(
|transaction| transaction.details.expiration_block_num <= new_sync_height,
DiscardCause::Expired,
);
}
pub fn apply_input_note_nullified(&mut self, input_note_nullifier: Nullifier) {
self.discard_transaction_with_predicate(
|transaction| {
transaction
.details
.input_note_nullifiers
.contains(&input_note_nullifier.as_word())
},
DiscardCause::InputConsumed,
);
}
pub fn apply_superseded_account_state(&mut self, superseded_account_state: Word) {
self.discard_transaction_with_predicate(
|transaction| transaction.details.final_account_state == superseded_account_state,
DiscardCause::Superseded,
);
}
pub fn apply_invalid_initial_account_state(&mut self, invalid_account_state: Word) {
self.discard_transaction_with_predicate(
|transaction| transaction.details.init_account_state == invalid_account_state,
DiscardCause::DiscardedInitialState,
);
}
fn discard_transaction_with_predicate<F>(&mut self, predicate: F, discard_cause: DiscardCause)
where
F: Fn(&TransactionRecord) -> bool,
{
let mut new_invalid_account_states = vec![];
for transaction in self.mutable_pending_transactions() {
if predicate(transaction) && transaction.discard_transaction(discard_cause) {
new_invalid_account_states.push(transaction.details.final_account_state);
}
}
for state in new_invalid_account_states {
self.apply_invalid_initial_account_state(state);
}
}
}
#[derive(Debug, Clone)]
pub enum PublicAccountUpdate {
Full(Account),
Patch {
new_header: AccountHeader,
patch: AccountPatch,
},
}
impl PublicAccountUpdate {
pub fn id(&self) -> AccountId {
match self {
Self::Full(account) => account.id(),
Self::Patch { new_header, .. } => new_header.id(),
}
}
pub fn nonce(&self) -> Felt {
match self {
Self::Full(account) => account.nonce(),
Self::Patch { new_header, .. } => new_header.nonce(),
}
}
}
pub(crate) fn build_account_patch(
new_header: &AccountHeader,
value_slot_updates: Vec<(StorageSlotName, Word)>,
map_entries: BTreeMap<StorageSlotName, StorageMapPatchEntries>,
vault_patch: AccountVaultPatch,
code: AccountCode,
) -> Result<AccountPatch, AccountPatchError> {
let is_full_state = new_header.nonce() == ONE;
let value_entries = value_slot_updates.into_iter().map(|(slot_name, new_value)| {
let value_patch = if is_full_state {
StorageValuePatch::Create { value: new_value }
} else {
StorageValuePatch::Update { value: new_value }
};
(slot_name, StorageSlotPatch::Value(value_patch))
});
let map_entries = map_entries.into_iter().map(|(slot_name, entries)| {
let map_patch = if is_full_state {
StorageMapPatch::Create { entries }
} else {
StorageMapPatch::Update { entries }
};
(slot_name, StorageSlotPatch::Map(map_patch))
});
let storage = AccountStoragePatch::from_entries(value_entries.chain(map_entries))?;
let code = is_full_state.then_some(code);
AccountPatch::new(new_header.id(), storage, vault_patch, code, Some(new_header.nonce()))
}
#[derive(Debug, Clone, Default)]
#[allow(clippy::struct_field_names)]
pub struct AccountUpdates {
updated_public_accounts: Vec<PublicAccountUpdate>,
mismatched_private_accounts: Vec<(AccountId, Word)>,
}
impl AccountUpdates {
pub fn new(
updated_public_accounts: Vec<PublicAccountUpdate>,
mismatched_private_accounts: Vec<(AccountId, Word)>,
) -> Self {
Self {
updated_public_accounts,
mismatched_private_accounts,
}
}
pub fn updated_public_accounts(&self) -> &[PublicAccountUpdate] {
&self.updated_public_accounts
}
pub fn mismatched_private_accounts(&self) -> &[(AccountId, Word)] {
&self.mismatched_private_accounts
}
pub fn extend(&mut self, other: AccountUpdates) {
self.updated_public_accounts.extend(other.updated_public_accounts);
self.mismatched_private_accounts.extend(other.mismatched_private_accounts);
}
}
#[cfg(test)]
mod tests {
use alloc::collections::BTreeMap;
use alloc::vec;
use miden_protocol::account::{AccountCode, StorageMapKey, StorageMapPatchEntries};
use miden_protocol::testing::account_id::ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE;
use super::*;
fn account_id() -> AccountId {
ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE.try_into().unwrap()
}
fn slot_name(name: &str) -> StorageSlotName {
StorageSlotName::new(name).unwrap()
}
fn word(n: u64) -> Word {
Word::from([
Felt::new_unchecked(n),
Felt::new_unchecked(0),
Felt::new_unchecked(0),
Felt::new_unchecked(0),
])
}
fn header_with_nonce(nonce: u64) -> AccountHeader {
AccountHeader::new(
account_id(),
Felt::new(nonce).expect("test nonce must be a valid Felt"),
Word::default(),
Word::default(),
Word::default(),
)
}
fn build_patch(
new_nonce: u64,
value_slot_updates: Vec<(StorageSlotName, Word)>,
map_entries: BTreeMap<StorageSlotName, StorageMapPatchEntries>,
) -> Result<AccountPatch, AccountPatchError> {
build_account_patch(
&header_with_nonce(new_nonce),
value_slot_updates,
map_entries,
AccountVaultPatch::default(),
AccountCode::mock(),
)
}
#[test]
fn build_patch_empty_payload_carries_only_nonce() {
let patch = build_patch(4, vec![], BTreeMap::new()).unwrap();
assert_eq!(patch.final_nonce(), Some(Felt::new_unchecked(4)));
assert!(patch.storage().is_empty());
assert!(patch.vault().is_empty());
assert!(!patch.is_full_state());
}
#[test]
fn build_patch_sets_value_slot_absolutely() {
let value_slot = slot_name("miden::test::value");
let patch = build_patch(2, vec![(value_slot.clone(), word(2))], BTreeMap::new()).unwrap();
assert_eq!(patch.storage().updated_value(&value_slot), Some(word(2)));
}
#[test]
fn build_patch_wraps_merged_map_entries() {
let map_slot = slot_name("miden::test::map");
let key = StorageMapKey::from_raw(word(42));
let mut entries = StorageMapPatchEntries::new();
entries.insert(key, word(300));
let map_entries = BTreeMap::from([(map_slot.clone(), entries)]);
let patch = build_patch(2, vec![], map_entries).unwrap();
let entries =
patch.storage().updated_map(&map_slot).expect("patch should contain map slot");
assert_eq!(entries.as_map().len(), 1);
assert_eq!(*entries.as_map().values().next().unwrap(), word(300));
}
#[test]
fn build_patch_rejects_zero_nonce() {
let result = build_patch(0, vec![], BTreeMap::new());
assert!(result.is_err());
}
#[test]
fn build_patch_for_new_account_is_full_state() {
let value_slot = slot_name("miden::test::value");
let patch = build_patch(1, vec![(value_slot, word(1))], BTreeMap::new()).unwrap();
assert!(patch.is_full_state());
assert_eq!(patch.final_nonce(), Some(ONE));
}
#[test]
fn build_patch_emits_map_create_for_new_account() {
let map_slot = slot_name("miden::test::map");
let mut entries = StorageMapPatchEntries::new();
entries.insert(StorageMapKey::from_raw(word(1)), word(100));
let map_entries = BTreeMap::from([(map_slot.clone(), entries)]);
let patch = build_patch(1, vec![], map_entries).unwrap();
assert!(patch.storage().created_map(&map_slot).is_some());
}
#[test]
fn build_patch_emits_map_update_for_existing_account() {
let map_slot = slot_name("miden::test::map");
let mut entries = StorageMapPatchEntries::new();
entries.insert(StorageMapKey::from_raw(word(1)), word(100));
let map_entries = BTreeMap::from([(map_slot.clone(), entries)]);
let patch = build_patch(2, vec![], map_entries).unwrap();
assert!(patch.storage().updated_map(&map_slot).is_some());
}
}