use futures::stream::{FuturesUnordered, Stream};
use futures::StreamExt;
use moonproof_ledger::transient_crypto::proofs::ProvingProvider;
use moonproof_macros::async_trait;
use moonproof_node_client::{NodeClient, SubmissionEvent};
use crate::error::{Result, WalletError};
use crate::facade::submission::{
finalize_recipe, submit_finalized, FinalizedTransactionRecipe, SubmissionOptions,
};
use crate::facade::transfer::UnprovenTransactionRecipe;
#[async_trait(?Send)]
pub trait ProvingCapability: Send + Sync {
async fn prove(&self, recipe: &UnprovenTransactionRecipe)
-> Result<FinalizedTransactionRecipe>;
}
#[derive(Debug, Clone)]
pub struct LedgerProvingCapability<P>
where
P: ProvingProvider + Clone + Send + Sync,
{
provider: P,
}
impl<P> LedgerProvingCapability<P>
where
P: ProvingProvider + Clone + Send + Sync,
{
pub fn new(provider: P) -> Self {
Self { provider }
}
}
#[async_trait(?Send)]
impl<P> ProvingCapability for LedgerProvingCapability<P>
where
P: ProvingProvider + Clone + Send + Sync + 'static,
{
async fn prove(
&self,
recipe: &UnprovenTransactionRecipe,
) -> Result<FinalizedTransactionRecipe> {
finalize_recipe(recipe, self.provider.clone()).await
}
}
#[async_trait]
pub trait SubmissionCapability: Send + Sync {
async fn submit(&self, bytes: Vec<u8>, options: SubmissionOptions) -> Result<SubmissionEvent>;
}
#[derive(Debug, Clone)]
pub struct NodeSubmissionCapability<C>
where
C: NodeClient + Send + Sync,
{
client: C,
}
impl<C> NodeSubmissionCapability<C>
where
C: NodeClient + Send + Sync,
{
pub fn new(client: C) -> Self {
Self { client }
}
}
#[async_trait]
impl<C> SubmissionCapability for NodeSubmissionCapability<C>
where
C: NodeClient + Send + Sync + 'static,
{
async fn submit(&self, bytes: Vec<u8>, options: SubmissionOptions) -> Result<SubmissionEvent> {
submit_finalized(&self.client, bytes, options).await
}
}
#[derive(Debug)]
pub struct MockProvingCapability {
canned: std::sync::Mutex<Option<FinalizedTransactionRecipe>>,
}
impl MockProvingCapability {
pub fn new(recipe: FinalizedTransactionRecipe) -> Self {
Self {
canned: std::sync::Mutex::new(Some(recipe)),
}
}
}
#[async_trait(?Send)]
impl ProvingCapability for MockProvingCapability {
async fn prove(
&self,
_recipe: &UnprovenTransactionRecipe,
) -> Result<FinalizedTransactionRecipe> {
self.canned
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
.ok_or_else(|| {
WalletError::Serialization(
"MockProvingCapability already consumed; construct with a fresh recipe per call"
.to_owned(),
)
})
}
}
pub fn prove_batch<C, I>(
capability: std::sync::Arc<C>,
recipes: I,
max_in_flight: usize,
) -> impl Stream<Item = Result<FinalizedTransactionRecipe>>
where
C: ProvingCapability + 'static,
I: IntoIterator<Item = UnprovenTransactionRecipe>,
{
let recipes: Vec<UnprovenTransactionRecipe> = recipes.into_iter().collect();
async_stream::stream! {
type ProveFuture = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<FinalizedTransactionRecipe>>>,
>;
let mut iter = recipes.into_iter();
let mut in_flight: FuturesUnordered<ProveFuture> = FuturesUnordered::new();
let cap_limit = if max_in_flight == 0 { usize::MAX } else { max_in_flight };
while in_flight.len() < cap_limit {
let Some(recipe) = iter.next() else { break; };
let cap = capability.clone();
in_flight.push(Box::pin(async move { cap.prove(&recipe).await }) as ProveFuture);
}
while let Some(result) = in_flight.next().await {
yield result;
if in_flight.len() < cap_limit {
if let Some(recipe) = iter.next() {
let cap = capability.clone();
in_flight
.push(Box::pin(async move { cap.prove(&recipe).await }) as ProveFuture);
}
}
}
}
}
#[derive(Debug)]
pub struct MockSubmissionCapability {
canned: std::sync::Mutex<Option<SubmissionEvent>>,
}
impl MockSubmissionCapability {
pub fn new(event: SubmissionEvent) -> Self {
Self {
canned: std::sync::Mutex::new(Some(event)),
}
}
}
#[derive(Debug)]
pub struct QueueProvingCapability {
queue: std::sync::Mutex<Vec<FinalizedTransactionRecipe>>,
}
impl QueueProvingCapability {
pub fn new(recipes: Vec<FinalizedTransactionRecipe>) -> Self {
let mut q = recipes;
q.reverse();
Self {
queue: std::sync::Mutex::new(q),
}
}
}
#[async_trait(?Send)]
impl ProvingCapability for QueueProvingCapability {
async fn prove(
&self,
_recipe: &UnprovenTransactionRecipe,
) -> Result<FinalizedTransactionRecipe> {
self.queue
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.pop()
.ok_or_else(|| WalletError::Serialization("QueueProvingCapability empty".to_owned()))
}
}
#[async_trait]
impl SubmissionCapability for MockSubmissionCapability {
async fn submit(
&self,
_bytes: Vec<u8>,
_options: SubmissionOptions,
) -> Result<SubmissionEvent> {
self.canned
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
.ok_or_else(|| {
WalletError::Serialization(
"MockSubmissionCapability already consumed; construct with a fresh event per call"
.to_owned(),
)
})
}
}