use async_trait::async_trait;
use log::info;
use metrics::counter;
use redgold_schema::{EasyJson, RgResult, SafeOption, WithMetadataHashable};
use redgold_schema::errors::EnhanceErrorInfo;
use redgold_schema::structs::{ErrorInfo, Transaction};
use crate::core::internal_message::SendErrorInfo;
use crate::core::relay::Relay;
use crate::core::stream_handlers::TryRecvForEach;
use crate::observability::logging::Loggable;
use crate::observability::metrics_help::WithMetrics;
use crate::util;
#[derive(Clone)]
pub struct TransactionWithSender {
pub transaction: Transaction,
pub sender: flume::Sender<RgResult<()>>,
pub time: i64,
pub rejection_reason: Option<ErrorInfo>,
pub update_utxo: bool
}
#[derive(Clone)]
pub enum TxWriterMessage {
WriteTransaction(TransactionWithSender),
}
#[derive(Clone)]
pub struct TxWriter {
relay: Relay
}
impl TxWriter {
pub fn new(relay: &Relay) -> Self {
Self {
relay: relay.clone()
}
}
pub async fn write_transaction(&self, message: &TransactionWithSender) -> RgResult<()> {
let transaction = &message.transaction;
info!("Writing transaction: {}", transaction.hash_or());
counter!("redgold.transaction.tx_writer.write_transaction").increment(1);
info!("Accepting transaction: {}", transaction.hash_or());
self.relay
.ds
.accept_transaction(
&transaction, message.time, message.rejection_reason.clone(), message.update_utxo
).await.mark_abort()?;
info!("Sanity check on transaction: {}", transaction.hash_or());
for fixed in transaction.utxo_inputs() {
if message.rejection_reason.is_none() && message.update_utxo {
let utxo_valid = self.relay.ds.transaction_store.query_utxo_id_valid(
&fixed.transaction_hash.safe_get()?.clone(), fixed.output_index
).await.mark_abort()?;
let deleted = !utxo_valid;
if !deleted {
return Err(ErrorInfo::new("UTXO not deleted")).add(fixed.json_or())
.mark_abort();
}
}
}
info!("Wrote transaction: {}", transaction.hash_or());
return Ok(());
}
pub async fn process_message(&mut self, message: TxWriterMessage) -> RgResult<()> {
counter!("redgold.transaction.tx_writer.process_message").increment(1);
match message {
TxWriterMessage::WriteTransaction(tws) => {
let result = self.write_transaction(&tws).await
.log_error()
.bubble_abort()?
.with_err_count("redgold.transaction.tx_writer.write_transaction.error");
tws.sender.send_rg_err(result)
}
}
}
}
#[async_trait]
impl TryRecvForEach<TxWriterMessage> for TxWriter {
async fn try_recv_for_each(&mut self, message: TxWriterMessage) -> RgResult<()> {
self.process_message(message).await
}
}