Skip to content
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
114 changes: 108 additions & 6 deletions contracts/predictify-hybrid/src/audit_trail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,50 @@ pub struct AuditRecord {
pub override_nonce: Option<u64>,
}

/// Head of the audit trail, tracking the latest state.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]

#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuditEntryV2 {
pub action: Symbol,
pub reason_idx: u8,
pub actor: Address,
pub ts: u64,
pub ref_id: BytesN<32>,
}

#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuditRecordVersioned {
V1(AuditRecord),
V2(AuditEntryV2),
}

pub struct AuditReasonTable;

impl AuditReasonTable {
pub fn get_reasons(env: &Env) -> Vec<String> {
env.storage()
.persistent()
.get(&crate::storage::DataKey::AuditReasonTable)
.unwrap_or_else(|| Vec::new(env))
}

pub fn add_reason(env: &Env, admin: &Address, reason: String) -> u8 {
admin.require_auth();
crate::admin::AdminManager::require_admin(env, admin);
let mut reasons = Self::get_reasons(env);
let idx = reasons.len() as u8;
reasons.push_back(reason);
env.storage()
.persistent()
.set(&crate::storage::DataKey::AuditReasonTable, &reasons);
idx
}
}

/// Head of the audit trail, tracking the latest state.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -127,13 +171,65 @@ impl AuditTrailManager {
}

/// Retrieves a specific audit record by index.
pub fn get_record(env: &Env, index: u64) -> Option<AuditRecord> {

pub fn append_record_v2(
env: &Env,
action: Symbol,
actor: Address,
reason_idx: u8,
) -> u64 {
let mut head: AuditTrailHead = env
.storage()
.persistent()
.get(&Self::head_key(env))
.unwrap_or(AuditTrailHead {
latest_index: 0,
latest_hash: BytesN::from_array(env, &[0u8; 32]),
});

let new_index = head.latest_index + 1;

let record = AuditEntryV2 {
action,
reason_idx,
actor,
ts: env.ledger().timestamp(),
ref_id: head.latest_hash.clone(),
};

let versioned = AuditRecordVersioned::V2(record);
let record_key = (Symbol::new(env, "AUDIT_REC"), new_index);
env.storage().persistent().set(&record_key, &versioned);

use soroban_sdk::xdr::ToXdr;
let record_bytes = versioned.clone().to_xdr(env);
let new_hash: BytesN<32> = env.crypto().sha256(&record_bytes).into();

head.latest_index = new_index;
head.latest_hash = new_hash;
env.storage().persistent().set(&Self::head_key(env), &head);

new_index
}

/// Retrieves a specific audit record by index.
pub fn get_record(env: &Env, index: u64) -> Option<AuditRecordVersioned> {
let record_key = (Symbol::new(env, "AUDIT_REC"), index);
env.storage().persistent().get(&record_key)
let val_opt: Option<soroban_sdk::Val> = env.storage().persistent().get(&record_key);
if let Some(val) = val_opt {
use soroban_sdk::TryFromVal;
if let Ok(versioned) = AuditRecordVersioned::try_from_val(env, &val) {
return Some(versioned);
}
if let Ok(v1) = AuditRecord::try_from_val(env, &val) {
return Some(AuditRecordVersioned::V1(v1));
}
}
None
}

/// Retrieves the latest records from the audit trail.
pub fn get_latest_records(env: &Env, limit: u64) -> Vec<AuditRecord> {
pub fn get_latest_records(env: &Env, limit: u64) -> Vec<AuditRecordVersioned> {
let head_opt = Self::get_head(env);
if head_opt.is_none() {
return Vec::new(env);
Expand Down Expand Up @@ -180,15 +276,21 @@ impl AuditTrailManager {
return false;
}

let record = record_opt.unwrap();
let record_bytes = record.clone().to_xdr(env);
let versioned_record = record_opt.unwrap();
let record_bytes = match &versioned_record {
AuditRecordVersioned::V1(v1) => v1.clone().to_xdr(env),
AuditRecordVersioned::V2(_) => versioned_record.clone().to_xdr(env),
};
let actual_hash: BytesN<32> = env.crypto().sha256(&record_bytes).into();

if actual_hash != expected_hash {
return false;
}

expected_hash = record.prev_record_hash;
expected_hash = match &versioned_record {
AuditRecordVersioned::V1(v1) => v1.prev_record_hash.clone(),
AuditRecordVersioned::V2(v2) => v2.ref_id.clone(),
};
current_index -= 1;
checked += 1;
}
Expand Down
60 changes: 60 additions & 0 deletions contracts/predictify-hybrid/src/disputes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,15 @@ pub struct DisputeTimeoutOutcome {
pub reason: String,
}

/// Configuration for dispute collusion detection.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollusionDetectorConfig {
pub stake_delta_threshold: i128,
pub time_delta_threshold: u64,
pub window_size: u32,
}

/// Aggregate statistics about dispute timeouts across all markets.
///
/// Returned by timeout analytics queries; useful for governance dashboards
Expand Down Expand Up @@ -786,6 +795,27 @@ impl DisputeManager {
env.storage().persistent().get(&key)
}

/// Sets the collusion detector configuration.
pub fn set_collusion_detector_config(env: &Env, admin: Address, config: CollusionDetectorConfig) -> Result<(), Error> {
admin.require_auth();
DisputeValidator::validate_admin_permissions(env, &admin)?;

let key = DataKey::CollusionDetectorConfig;
env.storage().persistent().set(&key, &config);
env.storage().persistent().extend_ttl(&key, 535680, 535680);
Ok(())
}

/// Retrieves the collusion detector configuration.
pub fn get_collusion_detector_config(env: &Env) -> CollusionDetectorConfig {
let key = DataKey::CollusionDetectorConfig;
env.storage().persistent().get(&key).unwrap_or(CollusionDetectorConfig {
stake_delta_threshold: 1_000_000,
time_delta_threshold: 600, // 10 minutes
window_size: 8,
})
}

/// Evicts the oldest resolved/expired disputes if history size exceeds the cap.
pub fn apply_eviction(
env: &Env,
Expand Down Expand Up @@ -990,6 +1020,36 @@ impl DisputeManager {
None,
);

// --- Collusion Detector ---
let config = Self::get_collusion_detector_config(env);
let window_size = config.window_size;
let start_idx = if history.len() > window_size {
history.len() - window_size
} else {
0
};

for i in start_idx..history.len().saturating_sub(1) {
if let Some(prev_dispute) = history.get(i) {
if prev_dispute.user != user {
let stake_diff = if prev_dispute.stake > stake { prev_dispute.stake - stake } else { stake - prev_dispute.stake };
let time_diff = if prev_dispute.timestamp > dispute.timestamp { prev_dispute.timestamp - dispute.timestamp } else { dispute.timestamp - prev_dispute.timestamp };

if stake_diff <= config.stake_delta_threshold && time_diff <= config.time_delta_threshold {
crate::events::EventEmitter::emit_suspected_collusion_flag(
env,
&market_id,
&user,
&prev_dispute.user,
stake_diff,
time_diff,
);
}
}
}
}
// --------------------------

Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion contracts/predictify-hybrid/src/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ pub enum Error {
/// The upgrade chain predecessor hash does not match the expected value.
UpgradeChainMismatch = 525,
/// An admin override nonce was replayed; reject to prevent replay attacks.
ReplayedOverride = 526,
ReplayedAdminOverride = 526,
/// Oracle quote is an outlier relative to the rolling median history.
OracleQuoteOutlier = 527,
}
Expand Down
Loading
Loading