use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use crossbeam_channel::{unbounded, Receiver, Sender};
use dashmap::mapref::entry::Entry;
use flume::TryRecvError;
use futures::{TryFutureExt, TryStreamExt};
use itertools::Itertools;
use log::{debug, error, info};
use metrics::increment_counter;
use tokio::runtime::Runtime;
use tokio::select;
use tokio::task::{JoinError, JoinHandle};
use uuid::Uuid;
use redgold_schema::{json_or, ProtoHashable, SafeOption, struct_metadata_new, structs, task_local, task_local_map, WithMetadataHashableFields};
use redgold_schema::structs::{FixedUtxoId, GossipTransactionRequest, Hash, PublicResponse, QueryObservationProofRequest, Request, Response, ValidationType};
use crate::core::internal_message::{Channel, new_bounded_channel, PeerMessage, RecvAsyncErrorInfo, SendErrorInfo, TransactionMessage};
use crate::core::relay::Relay;
use crate::core::transaction::{TransactionTestContext, validate_utxo};
use crate::data::data_store::DataStore;
use crate::schema::structs::{Error, ResponseMetadata};
use crate::schema::structs::{HashType, ObservationMetadata, State, Transaction};
use crate::schema::structs::{QueryTransactionResponse, SubmitTransactionResponse};
use crate::schema::{SafeBytesAccess, WithMetadataHashable};
use crate::util::runtimes::build_runtime;
use crate::schema::structs::ErrorInfo;
use crate::schema::structs::ObservationProof;
use crate::schema::{empty_public_response, error_info, error_message};
use crate::util;
use futures::{stream::FuturesUnordered, StreamExt};
use redgold_schema::output::tx_output_data;
use crate::core::resolver::resolve_transaction;
use crate::core::transact::utxo_conflict_resolver::check_utxo_conflicts;
use crate::util::current_time_millis_i64;
use redgold_schema::EasyJson;
use crate::util::logging::Loggable;
#[derive(Clone)]
pub struct Conflict {
transaction_hash: Hash,
abort: bool,
processing_start_time: i64,
request_processer: RequestProcessor,
}
#[derive(Clone)]
pub enum ProcessTransactionMessage {
ProofReceived(ObservationProof),
}
#[derive(Clone)]
pub struct RequestProcessor {
sender: flume::Sender<Conflict>,
receiver: flume::Receiver<Conflict>,
request_id: String,
pub transaction_hash: Hash,
pub transaction: Transaction,
pub internal_channel: Channel<ProcessTransactionMessage>
}
#[derive(Clone)]
pub struct UTXOContentionPool {
active_requests: Vec<Conflict>,
}
impl RequestProcessor {
fn new(transaction_hash: &Hash, request_id: String, transaction: Transaction) -> RequestProcessor {
let (s, r) = flume::unbounded::<Conflict>();
return RequestProcessor {
sender: s,
receiver: r,
request_id,
transaction_hash: transaction_hash.clone(),
transaction,
internal_channel: new_bounded_channel(200),
};
}
}
#[derive(Clone)]
pub struct TransactionProcessContext {
relay: Relay,
request_processor: Option<RequestProcessor>,
transaction_hash: Option<Hash>,
utxo_ids: Option<Vec<FixedUtxoId>>
}
async fn resolve_conflict(relay: Relay, conflicts: Vec<Conflict>) -> Result<Hash, ErrorInfo> {
let peer_publics = relay.ds.select_broadcast_peers().unwrap();
let mut map = HashMap::<Vec<u8>, f64>::new();
for peer in peer_publics {
map.insert(peer.public_key, peer.trust);
}
let mut trust_conflicts = vec![];
for c in conflicts {
let res = relay
.ds
.observation.select_observation_edge(&c.transaction_hash.clone())
.await?;
let sum_trust = res
.iter()
.into_group_map_by(|x| {
let ret: Vec<u8> = x
.proof
.as_ref()
.map(|p| p.public_key_bytes().as_ref().unwrap().clone())
.ok_or("")
.unwrap();
ret
})
.iter()
.map(|(k, _)| map.get(k).unwrap_or(&(0 as f64)))
.sum::<f64>();
trust_conflicts.push((
(-1 as f64) * sum_trust,
c.processing_start_time,
c.transaction_hash.clone(),
));
}
trust_conflicts.sort_by(|(_, _, h1), (_, _, h2)| h1.vec().cmp(&h2.vec()));
Ok(trust_conflicts.get(0).unwrap().2.clone())
}
impl TransactionProcessContext {
pub fn new(relay: Relay
) -> JoinHandle<Result<(), ErrorInfo>> {
let context = Self {
relay,
request_processor: None,
transaction_hash: None,
utxo_ids: None,
};
return tokio::spawn(async move { context.run().await });
}
async fn run(&self) -> Result<(), ErrorInfo> {
increment_counter!("redgold.node.async_started");
let receiver = self.relay.transaction.receiver.clone();
receiver.into_stream().map(|x| {
Ok(x)
})
.try_for_each_concurrent(100, |transaction| {
let mut x = self.clone();
async move {
x.scoped_process_and_respond(transaction).await
}
}).await
}
async fn scoped_process_and_respond(&mut self, transaction_message: TransactionMessage) -> Result<(), ErrorInfo> {
let request_uuid = Uuid::new_v4().to_string();
let hex = transaction_message.transaction.calculate_hash().hex();
let time = transaction_message.transaction.time().map(|x| x.clone()).unwrap_or(0);
let current_time = util::current_time_millis_i64();
let input_address = transaction_message.transaction.first_input_address().clone()
.and_then(|a| a.render_string().ok()).unwrap_or("".to_string());
let output_address = transaction_message.transaction.first_output_address()
.and_then(|a| a.render_string().ok()).unwrap_or("".to_string());
let node_id = self.relay.node_config.short_id()?;
let mut hm = HashMap::new();
hm.insert("request_uuid".to_string(), request_uuid.clone());
hm.insert("transaction_hash".to_string(), hex.clone());
hm.insert("transaction_time".to_string(), time.to_string());
hm.insert("current_time".to_string(), current_time.to_string());
hm.insert("input_address".to_string(), input_address.clone());
hm.insert("output_address".to_string(), output_address.clone());
hm.insert("node_id".to_string(), node_id.clone());
let res = task_local_map(hm, async move {
self.transaction(
transaction_message, request_uuid, hex,
time, current_time, input_address, output_address,
node_id
).await
}).await;
res
}
#[allow(unused_variables)]
#[tracing::instrument(skip(self, transaction_message, transaction_time, current_time, input_address, output_address))]
async fn transaction(
&mut self,
transaction_message: TransactionMessage,
request_uuid: String,
transaction_hash: String,
transaction_time: i64,
current_time: i64,
input_address: String,
output_address: String,
node_id: String
) -> Result<(), ErrorInfo> {
if self.check_peer_message(&transaction_message.transaction).await? {
return Ok(());
}
let result_or_error = {
match self.immediate_validation(&transaction_message.transaction).await {
Ok(_) => {
let res = self.process(&transaction_message.transaction.clone(), current_time, request_uuid).await;
self.cleanup(None)?;
res
}
Err(e) => {Err(e)}
}
};
let mut metadata = ResponseMetadata::default();
let mut pr = structs::Response::default();
match result_or_error {
Ok(o) => {
metadata.success = true;
pr.submit_transaction_response = Some(o);
}
Err(ee) => {
metadata.success = false;
metadata.error_info = Some(ee);
}
}
pr.response_metadata = Some(metadata);
match transaction_message.response_channel {
None => {
}
Some(r) => if let Some(e) = r.send_err(pr).err() {
error!("Error sending transaction response to channel {}", json_or(&e));
}
};
Ok(())
}
fn cleanup(&mut self, ii: Option<usize>) -> Result<(), ErrorInfo> {
if let Some(request_processor) = &self.request_processor {
if let Some(utxo_ids) = &self.utxo_ids {
self.clean_utxo(&request_processor, utxo_ids, ii);
self.relay.transaction_channels.remove(self.transaction_hash.safe_get()?);
}
}
Ok(())
}
async fn observe(&self, validation_type: ValidationType, state: State) -> Result<ObservationProof, ErrorInfo> {
let mut hash: Hash = self.transaction_hash.safe_get()?.clone();
hash.hash_type = HashType::Transaction as i32;
let mut om = structs::ObservationMetadata::default();
om.observed_hash = Some(hash);
om.state = Some(state as i32);
om.struct_metadata = struct_metadata_new();
om.observation_type = validation_type as i32;
self.relay.observe(om).await
}
async fn immediate_validation(&mut self, transaction: &Transaction) -> Result<(), ErrorInfo> {
let ds = self.relay.ds.clone();
if let Some((_, Some(pre_rejection))) = ds.transaction_store.query_maybe_transaction(&transaction.hash_or()).await? {
return Err(pre_rejection);
}
transaction.prevalidate()?;
Ok(())
}
async fn process(&mut self, transaction: &Transaction, processing_time_start: i64, request_uuid: String) -> Result<SubmitTransactionResponse, ErrorInfo> {
increment_counter!("redgold.transaction.received");
let hash = transaction.hash_or();
self.transaction_hash = Some(hash.clone());
let request_processor = self.create_receiver_or_err(&hash, request_uuid, &transaction)?;
let resolver_data = resolve_transaction(&transaction,
self.relay.clone(),
).await?;
resolver_data.validate()?;
let fixed_utxo_ids = transaction.fixed_utxo_ids_of_inputs()?;
self.utxo_ids = Some(fixed_utxo_ids.clone());
check_utxo_conflicts(self.relay.clone(), &fixed_utxo_ids, &hash).await?;
let mut conflict_detected = false;
let self_conflict = Conflict {
transaction_hash: hash.clone(),
abort: false,
processing_start_time: processing_time_start.clone(),
request_processer: request_processor.clone(),
};
let mut conflicts: Vec<Conflict> = vec![];
for utxo_id in fixed_utxo_ids {
let entry = self.relay.utxo_channels.entry(utxo_id.clone());
match entry {
Entry::Occupied(mut entry) => {
conflict_detected = true;
for active_request in entry.get().active_requests.iter() {
conflicts.push(active_request.clone());
info!(
"Conflict between current: {} and {} on utxo_id {} output: {}",
hash.hex(), active_request.transaction_hash.hex(),
utxo_id.clone().transaction_hash.expect("h").hex(),
utxo_id.output_index.clone()
);
active_request
.request_processer
.sender
.send_err(self_conflict.clone())?
}
entry.get_mut().active_requests.push(self_conflict.clone());
}
Entry::Vacant(entry) => {
entry.insert(UTXOContentionPool {
active_requests: vec![self_conflict.clone()],
});
}
};
}
let resolver_data = resolve_transaction(&transaction,
self.relay.clone(),
).await?;
resolver_data.validate()?;
let validation_type = if resolver_data.resolved_internally {
ValidationType::Full
} else {
ValidationType::Partial
};
let mut observation_proofs = HashSet::new();
let mut self_signed_pending = false;
if !conflict_detected {
tracing::info!("Signing pending transaction");
let prf = self.observe(validation_type, State::Pending).await?;
self_signed_pending = true;
observation_proofs.insert(prf);
} else {
tracing::info!("Conflict detected on current {}", hash.hex());
}
self.relay.gossip(transaction).await?;
let elapsed_time = || {
current_time_millis_i64() - processing_time_start
};
while elapsed_time() < (self.relay.node_config.transaction_finalization_time.as_millis() as i64) {
let res = tokio::time::timeout(
Duration::from_secs(1), request_processor.receiver.recv_async_err())
.await.ok();
if let Some(o) = res {
let conflict = o?;
if conflict.abort {
return Err(error_message(Error::TransactionRejectedDoubleSpend, "Double spend detected in live context"));
}
conflicts.push(conflict);
}
}
tracing::info!("Conflict resolution stage started with {:?} conflicts", conflicts.len());
if !conflicts.is_empty() {
let this_as_conflict = Conflict {
transaction_hash: hash.clone(),
abort: true,
processing_start_time: processing_time_start.clone(),
request_processer: request_processor.clone(),
};
let mut all_conflicts = conflicts.clone();
all_conflicts.push(this_as_conflict.clone());
let winner = resolve_conflict(self.relay.clone(), all_conflicts)
.await?;
if winner != hash {
Err(error_message(Error::TransactionRejectedDoubleSpend,
format!("Lost conflict to other transaction winner: {}", winner.hex())))?;
} else {
for c in &conflicts {
c.request_processer
.sender
.send_err(this_as_conflict.clone())?;
}
}
}
let prf = self.observe(validation_type, State::Finalized).await?;
observation_proofs.insert(prf);
self.insert_transaction(&transaction).await?;
increment_counter!("redgold.transaction.accepted");
tracing::info!("Accepted transaction");
tokio::time::sleep(Duration::from_secs(6)).await;
let stored_proofs = self.relay.ds.observation.select_observation_edge(&hash).await?;
tracing::info!("Found {:?} stored proofs in ds", stored_proofs.len());
observation_proofs.extend(stored_proofs);
let peers = self.relay.ds.peer_store.active_nodes(None).await?;
let mut obs_proof_req = Request::default();
obs_proof_req.query_observation_proof_request = Some(QueryObservationProofRequest {
hash: Some(hash.clone())
});
if !peers.is_empty() {
tracing::info!("Collecting observation proofs from {} peers", peers.len());
let results = Relay::broadcast(self.relay.clone(),
peers, obs_proof_req,
Some(
Duration::from_secs(5))).await;
for (pk, r) in results {
match r {
Ok(r) => {
let num_proofs = r.clone().query_observation_proof_response.map(|o| o.observation_proof.len()).unwrap_or(0);
tracing::info!("Received {:?} observation proofs from peer: {}", num_proofs, pk.short_id());
if let Some(obs_proof) = r.query_observation_proof_response {
observation_proofs.extend(obs_proof.observation_proof);
}
}
Err(e) => {
tracing::error!("Error collecting observation proofs from peer: {} error: {}", pk.short_id(), e.json_or())
}
}
}
} else {
tracing::info!("No peers to collect observation proofs from");
}
observation_proofs.extend(self.relay.ds.observation.select_observation_edge(&hash).await?);
let mut submit_response = SubmitTransactionResponse::default();
let mut query_transaction_response = QueryTransactionResponse::default();
query_transaction_response.observation_proofs = observation_proofs.iter().map(|o| o.clone()).collect_vec();
submit_response.query_transaction_response = Some(query_transaction_response);
submit_response.transaction = Some(transaction.clone());
submit_response.transaction_hash = Some(hash.clone());
let counts = submit_response.count_unique_by_state()?;
tracing::info!("Finished processing transaction \
num_observation_proofs {} self_signed_pending {:?} num_pending: {:?} num_accepted: {:?}",
observation_proofs.len(), self_signed_pending, counts.get(&(State::Pending as i32)).unwrap_or(&0),
counts.get(&(State::Finalized as i32)).unwrap_or(&0),
);
Ok(submit_response)
}
fn poll_internal_proof_messages(request_processor: &RequestProcessor, observation_proofs: &mut HashSet<ObservationProof>) -> Option<Result<SubmitTransactionResponse, ErrorInfo>> {
while {
let err = request_processor.internal_channel.receiver.try_recv();
let mut done = true;
match err {
Ok(o) => {
match o {
ProcessTransactionMessage::ProofReceived(o) => {
observation_proofs.insert(o);
}
}
}
Err(e) => {
match e {
TryRecvError::Empty => {
done = true;
}
TryRecvError::Disconnected => {
return Some(Err(error_info("request processor channel closed unexpectedly")));
}
}
}
}
done
} {}
None
}
async fn insert_transaction(
&self,
transaction: &Transaction,
) -> Result<(), ErrorInfo> {
self.relay
.ds
.transaction_store
.insert_transaction(
&transaction, util::current_time_millis_i64(), true, None
).await?;
for fixed in transaction.fixed_utxo_ids_of_inputs()? {
tracing::info!("Attempting to delete utxo: {}", fixed.format_str());
self.relay.ds.transaction_store.delete_utxo(&fixed).await?;
let utxo_valid = self.relay.ds.transaction_store.query_utxo_id_valid(
&fixed.transaction_hash.safe_get()?.clone(), fixed.output_index
).await?;
let deleted = !utxo_valid;
tracing::info!("Utxo should be deleted: {}", deleted);
}
return Ok(());
}
fn clean_utxo(
&self,
request_processor: &RequestProcessor,
utxo_ids: &Vec<FixedUtxoId>,
i: Option<usize>,
) {
let i = i.unwrap_or(utxo_ids.len());
for utxo_id_cleanup in &utxo_ids[0..i] {
let cleanup = self.relay.utxo_channels.get_mut(utxo_id_cleanup);
match cleanup {
None => {}
Some(mut pool) => {
let idx = pool
.active_requests
.iter()
.enumerate()
.find(|(_, req)| {
req.request_processer.request_id == request_processor.request_id
})
.map(|x| x.0);
match idx {
None => {}
Some(idx_actual) => {
pool.active_requests.remove(idx_actual);
}
}
}
}
}
}
fn create_receiver_or_err(
&self,
transaction_hash: &Hash,
request_uuid: String,
transaction: &Transaction
) -> Result<RequestProcessor, ErrorInfo> {
let entry = self
.relay
.transaction_channels
.entry(transaction_hash.clone());
let res = match entry {
Entry::Occupied(_) => Err(error_message(Error::TransactionAlreadyProcessing, "Duplicate TX hash found in processing queue")),
Entry::Vacant(entry) => {
let req = RequestProcessor::new(&transaction_hash, request_uuid, transaction.clone());
entry.insert(req.clone());
Ok(req)
}
};
res
}
async fn check_peer_message(&self, p0: &Transaction) -> Result<bool, ErrorInfo> {
let is_peer_tx = p0.node_metadata().is_ok();
if is_peer_tx {
}
Ok(is_peer_tx)
}
}