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

feat: rollback uncommitted tx #770

Open
wants to merge 4 commits into
base: next
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions crates/rust-client/src/store/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use miden_objects::{
/// The account should be stored in the database with its parts normalized. Meaning that the
/// account header, vault, storage and code are stored separately. This is done to avoid data
/// duplication as the header can reference the same elements if they have equal roots.
#[derive(Debug)]
pub struct AccountRecord {
/// Full account object.
account: Account,
Expand Down Expand Up @@ -54,6 +55,7 @@ impl From<AccountRecord> for Account {
/// Represents the status of an account tracked by the client.
///
/// The status of an account may change by local or external factors.
#[derive(Debug)]
pub enum AccountStatus {
/// The account is new and hasn't been used yet. The seed used to create the account is
/// stored in this state.
Expand Down
2 changes: 2 additions & 0 deletions crates/rust-client/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,8 @@ pub enum TransactionFilter {
/// Filter by transactions that haven't yet been committed to the blockchain as per the last
/// sync.
Uncomitted,
/// Return a list of the transaction that matches the provided [`TransactionId`]s.
Ids(Vec<TransactionId>),
}

// NOTE FILTER
Expand Down
11 changes: 11 additions & 0 deletions crates/rust-client/src/store/sqlite_store/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,17 @@ impl SqliteStore {
})
.collect::<Result<BTreeMap<AccountId, AccountCode>, _>>()
}

pub fn delete_accounts(
tx: &Transaction<'_>,
account_hashes: &[Digest],
) -> Result<(), StoreError> {
const QUERY: &str = "DELETE FROM accounts WHERE account_hash = ?";
for account_id in account_hashes {
tx.execute(QUERY, params![account_id.to_hex()])?;
}
Ok(())
}
}

// HELPERS
Expand Down
44 changes: 43 additions & 1 deletion crates/rust-client/src/store/sqlite_store/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{
account::{lock_account, update_account},
note::apply_note_updates_tx,
},
StoreError,
StoreError, TransactionFilter,
},
sync::{NoteTagRecord, NoteTagSource, StateSyncUpdate},
};
Expand Down Expand Up @@ -159,12 +159,54 @@ impl SqliteStore {
note_updates: &NoteUpdates,
transactions_to_discard: &[TransactionId],
) -> Result<(), StoreError> {
// First we need the `transaction` entries from the `transactions` table that matches the
// `transactions_to_discard`

let transactions_records_to_discard = Self::get_transactions(
conn,
&TransactionFilter::Ids(transactions_to_discard.to_vec()),
)?;

// Get the outdated accounts, handling potential errors
let mut outdated_accounts = Vec::new();
for transaction_record in &transactions_records_to_discard {
let account = Self::get_account(conn, transaction_record.account_id)
.map_err(|err| StoreError::QueryError(format!("Failed to get account: {err}")))?
.ok_or_else(|| StoreError::AccountDataNotFound(transaction_record.account_id))?;
outdated_accounts.push(account);
}

let tx = conn.transaction()?;

apply_note_updates_tx(&tx, note_updates)?;

Self::mark_transactions_as_discarded(&tx, transactions_to_discard)?;

// TODO: here we need to remove the `accounts` table entries that are originated from the
// discarded transactions

// Transaction records have a final_account_state field, which is the hash of the account in
// the final state after the transaction is applied. We can use this field to
// identify the accounts that are originated from the discarded transactions.

let mut accounts_to_remove = Vec::new();
for tx_record in &transactions_records_to_discard {
let final_account_state = tx_record.final_account_state;
let account = outdated_accounts
.iter()
.find(|account| account.account().hash() == final_account_state)
.ok_or_else(|| {
StoreError::QueryError(format!(
"Could not find account with hash {final_account_state}"
))
})?;

accounts_to_remove.push(account.account().hash());
}

// Remove the accounts that are originated from the discarded transactions
Self::delete_accounts(&tx, &accounts_to_remove)?;

tx.commit()?;

Ok(())
Expand Down
4 changes: 4 additions & 0 deletions crates/rust-client/src/store/sqlite_store/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ impl TransactionFilter {
match self {
TransactionFilter::All => QUERY.to_string(),
TransactionFilter::Uncomitted => format!("{QUERY} WHERE tx.commit_height IS NULL"),
TransactionFilter::Ids(ids) => {
let ids = ids.iter().map(|id| format!("'{id}'")).collect::<Vec<_>>().join(", ");
format!("{QUERY} WHERE tx.id IN ({ids})")
},
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion crates/rust-client/src/store/web_store/js/transactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ export async function getTransactions(filter) {
(tx) => tx.commitHeight === undefined || tx.commitHeight === null
)
.toArray();
} else if (filter.startsWith("Ids:")) {
const idsString = filter.substring(4); // Remove "Ids:" prefix
const ids = idsString.split(",");

if (ids.length > 0) {
transactionRecords = await transactions
.where("id")
.anyOf(ids)
.toArray();
} else {
transactionRecords = [];
}
} else {
transactionRecords = await transactions.toArray();
}
Expand Down Expand Up @@ -81,7 +93,7 @@ export async function getTransactions(filter) {
);

return processedTransactions;
} catch {
} catch (err) {
console.error("Failed to get transactions: ", err);
throw err;
}
Expand Down
10 changes: 9 additions & 1 deletion crates/rust-client/src/store/web_store/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use alloc::{string::ToString, vec::Vec};
use alloc::{
string::{String, ToString},
vec::Vec,
};

use miden_objects::{
account::AccountId,
Expand Down Expand Up @@ -33,6 +36,11 @@ impl WebStore {
let filter_as_str = match filter {
TransactionFilter::All => "All",
TransactionFilter::Uncomitted => "Uncomitted",
TransactionFilter::Ids(ids) => &{
let ids_str =
ids.iter().map(ToString::to_string).collect::<Vec<String>>().join(",");
format!("Ids:{ids_str}")
},
};

let promise = idxdb_get_transactions(filter_as_str.to_string());
Expand Down
Loading