use std::time::Duration;
use futures::stream::BoxStream;
use futures::StreamExt;
use moonproof_indexer_client::{
PublicDataProvider, Transaction as IndexedTransaction, TransactionOffset, TransactionResult,
TransactionResultStatus,
};
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::structure::{BindingKind, ProofKind, SignatureKind, Transaction};
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::storage::Storable;
use moonproof_node_client::{NodeClient, NodeClientError, SubmissionEvent, SubmissionStage};
use crate::dust::ledger_adapter::Db;
use crate::error::{Result, WalletError};
use crate::facade::submission::{format_node_error_chain, FinalizedTransaction};
use crate::pending_tx::{PendingTransactionResult, PendingTransactionStatus, SegmentResult};
use crate::runtime::ExponentialBackoff;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubmissionEnd {
Included,
Excluded,
Undetermined,
}
pub struct SubmissionWatch {
events: Option<BoxStream<'static, std::result::Result<SubmissionEvent, NodeClientError>>>,
refusal: Option<WalletError>,
end: Option<SubmissionEnd>,
}
impl SubmissionWatch {
pub async fn submit<C: NodeClient + ?Sized>(client: &C, bytes: Vec<u8>) -> Self {
match client.send_midnight_transaction(bytes).await {
Ok(events) => Self {
events: Some(events),
refusal: None,
end: None,
},
Err(e) => Self {
events: None,
end: Some(if refusal_excludes(&e) {
SubmissionEnd::Excluded
} else {
SubmissionEnd::Undetermined
}),
refusal: Some(submission_error(&e)),
},
}
}
pub async fn wait_for(&mut self, stage: SubmissionStage) -> Result<SubmissionEvent> {
if let Some(refusal) = self.refusal.take() {
return Err(refusal);
}
while let Some(item) = self.next().await {
match item {
Ok(event) if event.stage() >= stage => return Ok(event),
Ok(_) => {}
Err(e) => return Err(submission_error(&e)),
}
}
Err(WalletError::Submission(format!(
"submission ended before reaching stage '{stage}'"
)))
}
#[must_use]
pub fn settled(&self) -> Option<SubmissionEnd> {
self.end
}
pub async fn end(mut self) -> SubmissionEnd {
while self.end.is_none() {
if self.next().await.is_none() {
break;
}
}
self.end.unwrap_or(SubmissionEnd::Undetermined)
}
async fn next(&mut self) -> Option<std::result::Result<SubmissionEvent, NodeClientError>> {
if matches!(
self.end,
Some(SubmissionEnd::Excluded | SubmissionEnd::Undetermined)
) {
return None;
}
let events = self.events.as_mut()?;
let Some(item) = events.next().await else {
self.events = None;
self.end.get_or_insert(SubmissionEnd::Undetermined);
return None;
};
match &item {
Ok(event) if event.stage() >= SubmissionStage::InBlock => {
self.end = Some(SubmissionEnd::Included);
}
Ok(_) => {}
Err(e) => {
self.events = None;
if self.end.is_none() {
self.end = Some(if stream_error_excludes(e) {
SubmissionEnd::Excluded
} else {
SubmissionEnd::Undetermined
});
}
}
}
Some(item)
}
}
fn refusal_excludes(e: &NodeClientError) -> bool {
match e {
NodeClientError::Connection { .. } => true,
NodeClientError::Submission { .. } => {
let rendered = format_node_error_chain("", e).to_lowercase();
!(rendered.contains("temporarily banned")
|| rendered.contains("already imported")
|| names_an_applied_transaction(&rendered))
}
_ => false,
}
}
fn stream_error_excludes(e: &NodeClientError) -> bool {
match e {
NodeClientError::TransactionInvalid { .. } => {
!names_an_applied_transaction(&format_node_error_chain("", e).to_lowercase())
}
NodeClientError::TransactionUsurped { .. } => true,
_ => false,
}
}
fn names_an_applied_transaction(rendered: &str) -> bool {
const ALREADY_APPLIED: [u16; 6] = [
195, 196, 230, 239, 244, 247, ];
crate::session::submit::extract_custom_error_code(rendered)
.is_some_and(|code| ALREADY_APPLIED.contains(&code))
}
fn submission_error(e: &NodeClientError) -> WalletError {
WalletError::Submission(format_node_error_chain("submit_finalized", e))
}
pub async fn transaction_result<P: PublicDataProvider + ?Sized>(
indexer: &P,
tx: &FinalizedTransaction,
) -> Result<Option<PendingTransactionResult>> {
let identifiers = identifiers_hex(tx)?;
let Some(first) = identifiers.first() else {
return Ok(None);
};
let reported = indexer
.transactions(TransactionOffset::Identifier(first.clone()))
.await
.map_err(|e| WalletError::Submission(format!("indexer transaction result lookup: {e}")))?;
Ok(result_among(&identifiers, &reported))
}
pub async fn ended_transaction_result<P: PublicDataProvider + ?Sized>(
indexer: &P,
tx: &FinalizedTransaction,
end: SubmissionEnd,
give_up_after: Duration,
) -> Option<PendingTransactionResult> {
if end == SubmissionEnd::Excluded {
return Some(failure());
}
let ttl = earliest_ttl(tx);
let deadline = moonproof_utils::rt::Instant::now() + give_up_after;
let mut backoff = ExponentialBackoff::new()
.with_initial(Duration::from_secs(1))
.with_max(Duration::from_secs(30));
loop {
match lookup_until_ttl(indexer, tx, ttl).await {
Ok(Some(result)) => return Some(result),
Ok(None) => {}
Err(e) => tracing::debug!(error = %e, "transaction result lookup failed; retrying"),
}
if moonproof_utils::rt::Instant::now() >= deadline {
return None;
}
moonproof_utils::rt::sleep(backoff.next_delay()).await;
}
}
async fn lookup_until_ttl<P: PublicDataProvider + ?Sized>(
indexer: &P,
tx: &FinalizedTransaction,
ttl: Option<Timestamp>,
) -> Result<Option<PendingTransactionResult>> {
if let Some(result) = transaction_result(indexer, tx).await? {
return Ok(Some(result));
}
let Some(ttl) = ttl else {
return Ok(None);
};
if !indexer_passed(indexer, ttl).await? {
return Ok(None);
}
Ok(Some(
transaction_result(indexer, tx)
.await?
.unwrap_or_else(failure),
))
}
fn failure() -> PendingTransactionResult {
PendingTransactionResult {
status: PendingTransactionStatus::Failure,
segments: Vec::new(),
}
}
async fn indexer_passed<P: PublicDataProvider + ?Sized>(
indexer: &P,
ttl: Timestamp,
) -> Result<bool> {
let tip = indexer
.block(None)
.await
.map_err(|e| WalletError::Submission(format!("indexer latest block lookup: {e}")))?;
Ok(tip.is_some_and(|block| {
u64::try_from(block.timestamp / 1000).is_ok_and(|secs| secs > ttl.to_secs())
}))
}
fn earliest_ttl<S, P, B>(tx: &Transaction<S, P, B, Db>) -> Option<Timestamp>
where
S: SignatureKind<Db>,
P: ProofKind<Db>,
B: BindingKind<S, P, Db> + Storable<Db>,
{
match tx {
Transaction::Standard(stx) => stx.intents.iter().map(|entry| entry.1.ttl).min(),
Transaction::ClaimRewards(_) => None,
}
}
pub(crate) fn identifiers_hex(tx: &FinalizedTransaction) -> Result<Vec<String>> {
tx.identifiers()
.map(|id| {
let mut buf = Vec::new();
Serializable::serialize(&id, &mut buf).map_err(|e| {
WalletError::Serialization(format!("serialize transaction identifier: {e}"))
})?;
Ok(hex::encode(buf))
})
.collect()
}
fn result_among(
identifiers: &[String],
reported: &[IndexedTransaction],
) -> Option<PendingTransactionResult> {
reported
.iter()
.filter_map(|tx| tx.regular.as_ref())
.find(|regular| {
identifiers
.iter()
.all(|id| regular.identifiers.contains(id))
})
.map(|regular| pending_result(®ular.transaction_result))
}
fn pending_result(result: &TransactionResult) -> PendingTransactionResult {
PendingTransactionResult {
status: match result.status {
TransactionResultStatus::Success => PendingTransactionStatus::Success,
TransactionResultStatus::PartialSuccess => PendingTransactionStatus::PartialSuccess,
TransactionResultStatus::Failure => PendingTransactionStatus::Failure,
},
segments: result
.segments
.iter()
.map(|segment| SegmentResult {
id: segment.id,
success: segment.success,
})
.collect(),
}
}
#[cfg(test)]
mod tests {
use async_trait::async_trait;
use futures::stream;
use moonproof_indexer_client::{
BlockRef, RegularTransactionData, TransactionKind, TransactionSegment,
};
use moonproof_node_client::{Genesis, SerializedTransaction};
use super::*;
struct ScriptedNode {
refusal: std::sync::Mutex<Option<NodeClientError>>,
events: std::sync::Mutex<Vec<std::result::Result<SubmissionEvent, NodeClientError>>>,
}
impl ScriptedNode {
fn reporting(events: Vec<std::result::Result<SubmissionEvent, NodeClientError>>) -> Self {
Self {
refusal: std::sync::Mutex::new(None),
events: std::sync::Mutex::new(events),
}
}
fn refusing(e: NodeClientError) -> Self {
Self {
refusal: std::sync::Mutex::new(Some(e)),
events: std::sync::Mutex::new(Vec::new()),
}
}
}
#[async_trait]
impl NodeClient for ScriptedNode {
async fn send_midnight_transaction(
&self,
_tx: SerializedTransaction,
) -> std::result::Result<
BoxStream<'static, std::result::Result<SubmissionEvent, NodeClientError>>,
NodeClientError,
> {
if let Some(e) = self.refusal.lock().unwrap().take() {
return Err(e);
}
let events = std::mem::take(&mut *self.events.lock().unwrap());
Ok(stream::iter(events).boxed())
}
async fn get_genesis(&self) -> std::result::Result<Genesis, NodeClientError> {
Ok(Genesis::default())
}
}
fn submitted() -> SubmissionEvent {
SubmissionEvent::Submitted {
tx: vec![],
tx_hash: "0x01".into(),
}
}
fn in_block() -> SubmissionEvent {
SubmissionEvent::InBlock {
tx: vec![],
block_hash: "0x02".into(),
block_height: 5,
tx_hash: "0x01".into(),
}
}
fn finalized() -> SubmissionEvent {
SubmissionEvent::Finalized {
tx: vec![],
block_hash: "0x02".into(),
block_height: 5,
tx_hash: "0x01".into(),
}
}
fn invalid() -> NodeClientError {
NodeClientError::TransactionInvalid {
tx_data: vec![],
source: Some("Invalid transaction with custom error: 170".into()),
}
}
fn already_applied() -> NodeClientError {
NodeClientError::TransactionInvalid {
tx_data: vec![],
source: Some("Invalid transaction with custom error: 230".into()),
}
}
fn dropped() -> NodeClientError {
NodeClientError::TransactionDropped { tx_data: vec![] }
}
#[tokio::test]
async fn an_event_past_the_requested_stage_answers_it() {
let node = ScriptedNode::reporting(vec![Ok(submitted()), Ok(in_block()), Ok(finalized())]);
let mut watch = SubmissionWatch::submit(&node, vec![]).await;
let event = watch.wait_for(SubmissionStage::Submitted).await.unwrap();
assert_eq!(event.stage(), SubmissionStage::Submitted);
assert_eq!(watch.end().await, SubmissionEnd::Included);
}
#[tokio::test]
async fn an_invalid_transaction_is_excluded() {
let node = ScriptedNode::reporting(vec![Ok(submitted()), Err(invalid())]);
let mut watch = SubmissionWatch::submit(&node, vec![]).await;
assert!(watch.wait_for(SubmissionStage::InBlock).await.is_err());
assert_eq!(watch.end().await, SubmissionEnd::Excluded);
}
#[tokio::test]
async fn a_refusal_naming_an_applied_transaction_settles_nothing() {
let node = ScriptedNode::reporting(vec![Ok(submitted()), Err(already_applied())]);
let watch = SubmissionWatch::submit(&node, vec![]).await;
assert_eq!(watch.end().await, SubmissionEnd::Undetermined);
}
#[tokio::test]
async fn a_dropped_transaction_may_still_land() {
let node = ScriptedNode::reporting(vec![Ok(submitted()), Err(dropped())]);
let watch = SubmissionWatch::submit(&node, vec![]).await;
assert_eq!(watch.end().await, SubmissionEnd::Undetermined);
}
#[tokio::test]
async fn an_error_after_a_block_held_it_leaves_it_included() {
let node = ScriptedNode::reporting(vec![
Ok(submitted()),
Ok(in_block()),
Err(NodeClientError::TransactionProgress {
message: "finality timeout".into(),
tx_data: vec![],
desired_stage: SubmissionStage::Finalized,
}),
]);
let mut watch = SubmissionWatch::submit(&node, vec![]).await;
assert!(watch.wait_for(SubmissionStage::Finalized).await.is_err());
assert_eq!(watch.end().await, SubmissionEnd::Included);
}
#[tokio::test]
async fn reports_ending_before_a_block_settle_nothing() {
let node = ScriptedNode::reporting(vec![Ok(submitted())]);
let watch = SubmissionWatch::submit(&node, vec![]).await;
assert_eq!(watch.end().await, SubmissionEnd::Undetermined);
}
#[tokio::test]
async fn a_refused_submission_reports_why_and_is_excluded() {
let node = ScriptedNode::refusing(NodeClientError::Submission {
message: "submit_and_watch rejected the extrinsic: Invalid Transaction".into(),
tx_data: vec![],
source: None,
});
let mut watch = SubmissionWatch::submit(&node, vec![]).await;
let err = watch.wait_for(SubmissionStage::InBlock).await.unwrap_err();
assert!(err.to_string().contains("Invalid Transaction"), "{err}");
assert_eq!(watch.end().await, SubmissionEnd::Excluded);
}
#[tokio::test]
async fn a_pool_that_already_holds_it_settles_nothing() {
let node = ScriptedNode::refusing(NodeClientError::Submission {
message: "submit_and_watch rejected the extrinsic: Transaction Already Imported".into(),
tx_data: vec![],
source: None,
});
let watch = SubmissionWatch::submit(&node, vec![]).await;
assert_eq!(watch.end().await, SubmissionEnd::Undetermined);
}
fn indexed(identifiers: &[&str], status: TransactionResultStatus) -> IndexedTransaction {
IndexedTransaction {
kind: TransactionKind::Regular,
id: 1,
hash: "aa".into(),
protocol_version: 9000,
raw: String::new(),
block: BlockRef {
hash: "bb".into(),
height: 3,
},
regular: Some(RegularTransactionData {
fee: "0".into(),
zswap_merkle_tree_root: String::new(),
zswap_start_index: 0,
zswap_end_index: 0,
identifiers: identifiers.iter().map(|id| (*id).to_owned()).collect(),
transaction_result: TransactionResult {
status,
segments: vec![
TransactionSegment {
id: 0,
success: true,
},
TransactionSegment {
id: 1,
success: false,
},
],
},
}),
bridge_claim: None,
dust_ledger_events: Vec::new(),
}
}
#[test]
fn the_result_comes_from_the_transaction_carrying_every_identifier() {
let ours = ["01".to_owned(), "02".to_owned()];
let reported = [
indexed(&["01"], TransactionResultStatus::Success),
indexed(&["01", "02", "03"], TransactionResultStatus::PartialSuccess),
];
let result = result_among(&ours, &reported).expect("our transaction is reported");
assert_eq!(result.status, PendingTransactionStatus::PartialSuccess);
assert_eq!(
result.segments,
vec![
SegmentResult {
id: 0,
success: true
},
SegmentResult {
id: 1,
success: false
},
]
);
}
#[test]
fn a_transaction_sharing_one_identifier_is_not_ours() {
let ours = ["01".to_owned(), "02".to_owned()];
let reported = [indexed(&["01"], TransactionResultStatus::Success)];
assert_eq!(result_among(&ours, &reported), None);
}
}