rustkernel_compliance/types.rs
1//! Compliance types and data structures.
2
3use serde::{Deserialize, Serialize};
4
5// ============================================================================
6// Transaction Types
7// ============================================================================
8
9/// A financial transaction for compliance analysis.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Transaction {
12 /// Unique transaction ID.
13 pub id: u64,
14 /// Source account/entity ID.
15 pub source_id: u64,
16 /// Destination account/entity ID.
17 pub dest_id: u64,
18 /// Transaction amount.
19 pub amount: f64,
20 /// Timestamp (Unix epoch seconds).
21 pub timestamp: u64,
22 /// Currency code (e.g., "USD").
23 pub currency: String,
24 /// Transaction type (e.g., "wire", "ach", "internal").
25 pub tx_type: String,
26}
27
28/// Time window for analysis.
29#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
30pub struct TimeWindow {
31 /// Start timestamp (inclusive).
32 pub start: u64,
33 /// End timestamp (exclusive).
34 pub end: u64,
35}
36
37impl TimeWindow {
38 /// Create a new time window.
39 pub fn new(start: u64, end: u64) -> Self {
40 Self { start, end }
41 }
42
43 /// Check if a timestamp is within this window.
44 pub fn contains(&self, timestamp: u64) -> bool {
45 timestamp >= self.start && timestamp < self.end
46 }
47
48 /// Duration in seconds.
49 pub fn duration(&self) -> u64 {
50 self.end.saturating_sub(self.start)
51 }
52}
53
54// ============================================================================
55// AML Types
56// ============================================================================
57
58/// Result of circular flow analysis.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct CircularFlowResult {
61 /// Ratio of circular flow amount to total flow.
62 pub circular_ratio: f64,
63 /// Strongly connected components found.
64 pub sccs: Vec<Vec<u64>>,
65 /// Total amount in circular flows.
66 pub circular_amount: f64,
67 /// Total transaction amount analyzed.
68 pub total_amount: f64,
69}
70
71/// Result of reciprocity analysis.
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct ReciprocityResult {
74 /// Ratio of reciprocal transactions.
75 pub reciprocity_ratio: f64,
76 /// Pairs of entities with reciprocal transactions.
77 pub reciprocal_pairs: Vec<(u64, u64)>,
78 /// Amount involved in reciprocal transactions.
79 pub reciprocal_amount: f64,
80}
81
82/// Result of rapid movement (velocity) analysis.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct RapidMovementResult {
85 /// Entities flagged for rapid movement.
86 pub flagged_entities: Vec<u64>,
87 /// Velocity metrics per entity (transactions per hour).
88 pub velocity_metrics: Vec<(u64, f64)>,
89 /// Amount moved rapidly.
90 pub rapid_amount: f64,
91}
92
93/// AML pattern types.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95pub enum AMLPattern {
96 /// Structuring (smurfing) - breaking large amounts into smaller ones.
97 Structuring,
98 /// Layering - moving money through multiple accounts.
99 Layering,
100 /// Rapid movement - quick in/out of accounts.
101 RapidMovement,
102 /// Round tripping - money returning to origin.
103 RoundTripping,
104 /// Funnel account - many-to-one pattern.
105 FunnelAccount,
106 /// Fan out - one-to-many pattern.
107 FanOut,
108}
109
110/// Result of AML pattern detection.
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct AMLPatternResult {
113 /// Detected patterns with associated entities.
114 pub patterns: Vec<(AMLPattern, Vec<u64>)>,
115 /// Overall risk score (0-100).
116 pub risk_score: f64,
117 /// Details per pattern.
118 pub pattern_details: Vec<PatternDetail>,
119}
120
121/// Details of a detected pattern.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct PatternDetail {
124 /// Pattern type.
125 pub pattern: AMLPattern,
126 /// Involved entity IDs.
127 pub entities: Vec<u64>,
128 /// Amount involved.
129 pub amount: f64,
130 /// Confidence score (0-1).
131 pub confidence: f64,
132 /// Time span of the pattern.
133 pub time_span: TimeWindow,
134}
135
136// ============================================================================
137// KYC Types
138// ============================================================================
139
140/// KYC risk factors.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct KYCFactors {
143 /// Customer ID.
144 pub customer_id: u64,
145 /// Country risk score (0-100).
146 pub country_risk: f64,
147 /// Industry risk score (0-100).
148 pub industry_risk: f64,
149 /// Product risk score (0-100).
150 pub product_risk: f64,
151 /// Transaction pattern risk (0-100).
152 pub transaction_risk: f64,
153 /// Documentation completeness (0-100).
154 pub documentation_score: f64,
155 /// Years as customer.
156 pub tenure_years: f64,
157}
158
159/// Result of KYC scoring.
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct KYCResult {
162 /// Customer ID.
163 pub customer_id: u64,
164 /// Overall risk score (0-100).
165 pub risk_score: f64,
166 /// Risk tier (Low, Medium, High, Very High).
167 pub risk_tier: RiskTier,
168 /// Contributing factors.
169 pub factor_contributions: Vec<(String, f64)>,
170}
171
172/// Risk tier classification.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
174pub enum RiskTier {
175 /// Low risk (0-25).
176 Low,
177 /// Medium risk (25-50).
178 Medium,
179 /// High risk (50-75).
180 High,
181 /// Very high risk (75-100).
182 VeryHigh,
183}
184
185impl From<f64> for RiskTier {
186 fn from(score: f64) -> Self {
187 match score {
188 s if s < 25.0 => RiskTier::Low,
189 s if s < 50.0 => RiskTier::Medium,
190 s if s < 75.0 => RiskTier::High,
191 _ => RiskTier::VeryHigh,
192 }
193 }
194}
195
196/// Entity for resolution/matching.
197#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct Entity {
199 /// Entity ID.
200 pub id: u64,
201 /// Entity name.
202 pub name: String,
203 /// Alternative names/aliases.
204 pub aliases: Vec<String>,
205 /// Date of birth (YYYYMMDD format) or incorporation date.
206 pub date: Option<u32>,
207 /// Country code.
208 pub country: Option<String>,
209 /// Entity type.
210 pub entity_type: EntityType,
211}
212
213/// Type of entity.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215pub enum EntityType {
216 /// Individual person.
217 Individual,
218 /// Corporation/company.
219 Corporation,
220 /// Government entity.
221 Government,
222 /// Unknown.
223 Unknown,
224}
225
226/// Result of entity resolution.
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct EntityResolutionResult {
229 /// Query entity ID.
230 pub query_id: u64,
231 /// Potential matches with scores.
232 pub matches: Vec<EntityMatch>,
233}
234
235/// A potential entity match.
236#[derive(Debug, Clone, Serialize, Deserialize)]
237pub struct EntityMatch {
238 /// Matched entity ID.
239 pub entity_id: u64,
240 /// Overall match score (0-1).
241 pub score: f64,
242 /// Name similarity.
243 pub name_score: f64,
244 /// Date similarity.
245 pub date_score: f64,
246 /// Country match.
247 pub country_match: bool,
248}
249
250// ============================================================================
251// Sanctions Types
252// ============================================================================
253
254/// Sanctions list entry.
255#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct SanctionsEntry {
257 /// Entry ID.
258 pub id: u64,
259 /// Primary name.
260 pub name: String,
261 /// Alternative names.
262 pub aliases: Vec<String>,
263 /// List source (OFAC, UN, EU, etc.).
264 pub source: String,
265 /// Program (SDN, sectoral, etc.).
266 pub program: String,
267 /// Country.
268 pub country: Option<String>,
269 /// Date of birth.
270 pub dob: Option<u32>,
271}
272
273/// Result of sanctions screening.
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct SanctionsResult {
276 /// Query entity name.
277 pub query_name: String,
278 /// Potential matches.
279 pub matches: Vec<SanctionsMatch>,
280 /// Overall hit status.
281 pub is_hit: bool,
282}
283
284/// A sanctions list match.
285#[derive(Debug, Clone, Serialize, Deserialize)]
286pub struct SanctionsMatch {
287 /// Matched entry ID.
288 pub entry_id: u64,
289 /// Match score (0-1).
290 pub score: f64,
291 /// Matched name.
292 pub matched_name: String,
293 /// List source.
294 pub source: String,
295 /// Match reason.
296 pub reason: String,
297}
298
299/// PEP (Politically Exposed Person) entry.
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct PEPEntry {
302 /// Entry ID.
303 pub id: u64,
304 /// Name.
305 pub name: String,
306 /// Position/title.
307 pub position: String,
308 /// Country.
309 pub country: String,
310 /// Level (1=head of state, 2=senior official, 3=family member).
311 pub level: u8,
312 /// Still active in position.
313 pub active: bool,
314}
315
316/// Result of PEP screening.
317#[derive(Debug, Clone, Serialize, Deserialize)]
318pub struct PEPResult {
319 /// Query name.
320 pub query_name: String,
321 /// Potential matches.
322 pub matches: Vec<PEPMatch>,
323 /// Is a PEP hit.
324 pub is_pep: bool,
325}
326
327/// A PEP match.
328#[derive(Debug, Clone, Serialize, Deserialize)]
329pub struct PEPMatch {
330 /// Entry ID.
331 pub entry_id: u64,
332 /// Match score.
333 pub score: f64,
334 /// Matched name.
335 pub name: String,
336 /// Position.
337 pub position: String,
338 /// Country.
339 pub country: String,
340 /// PEP level.
341 pub level: u8,
342}
343
344// ============================================================================
345// Transaction Monitoring Types
346// ============================================================================
347
348/// Transaction monitoring rule.
349#[derive(Debug, Clone, Serialize, Deserialize)]
350pub struct MonitoringRule {
351 /// Rule ID.
352 pub id: u64,
353 /// Rule name.
354 pub name: String,
355 /// Rule type.
356 pub rule_type: RuleType,
357 /// Threshold value.
358 pub threshold: f64,
359 /// Time window in seconds.
360 pub window_seconds: u64,
361 /// Severity level.
362 pub severity: Severity,
363}
364
365/// Type of monitoring rule.
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
367pub enum RuleType {
368 /// Single transaction amount threshold.
369 SingleAmount,
370 /// Aggregate amount over time window.
371 AggregateAmount,
372 /// Transaction count threshold.
373 TransactionCount,
374 /// Velocity (amount per hour).
375 Velocity,
376 /// Geographic risk (cross-border).
377 GeographicRisk,
378}
379
380/// Alert severity.
381#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
382pub enum Severity {
383 /// Informational.
384 Info,
385 /// Low severity.
386 Low,
387 /// Medium severity.
388 Medium,
389 /// High severity.
390 High,
391 /// Critical.
392 Critical,
393}
394
395/// Generated alert from monitoring.
396#[derive(Debug, Clone, Serialize, Deserialize)]
397pub struct Alert {
398 /// Alert ID.
399 pub id: u64,
400 /// Rule that triggered the alert.
401 pub rule_id: u64,
402 /// Entity that triggered the alert.
403 pub entity_id: u64,
404 /// Alert timestamp.
405 pub timestamp: u64,
406 /// Severity.
407 pub severity: Severity,
408 /// Current value that triggered the alert.
409 pub current_value: f64,
410 /// Threshold that was exceeded.
411 pub threshold: f64,
412 /// Related transaction IDs.
413 pub transaction_ids: Vec<u64>,
414 /// Alert message.
415 pub message: String,
416}
417
418/// Result of transaction monitoring.
419#[derive(Debug, Clone, Serialize, Deserialize)]
420pub struct MonitoringResult {
421 /// Generated alerts.
422 pub alerts: Vec<Alert>,
423 /// Entities monitored.
424 pub entities_checked: usize,
425 /// Transactions analyzed.
426 pub transactions_analyzed: usize,
427}
428
429// ============================================================================
430// Flow Reversal Types
431// ============================================================================
432
433/// A detected flow reversal pair.
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct FlowReversalPair {
436 /// Original transaction ID.
437 pub original_tx_id: u64,
438 /// Reversal transaction ID.
439 pub reversal_tx_id: u64,
440 /// Source entity in original transaction.
441 pub entity_a: u64,
442 /// Destination entity in original transaction.
443 pub entity_b: u64,
444 /// Original amount.
445 pub original_amount: f64,
446 /// Reversal amount.
447 pub reversal_amount: f64,
448 /// Time delta between transactions (seconds).
449 pub time_delta: u64,
450 /// Amount match ratio (0-1, 1.0 = exact match).
451 pub amount_match_ratio: f64,
452 /// Risk level for this reversal.
453 pub risk_level: ReversalRiskLevel,
454}
455
456/// Risk level for flow reversal.
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458pub enum ReversalRiskLevel {
459 /// Normal - likely legitimate business reversal.
460 Normal,
461 /// Suspicious - short time window or repeated pattern.
462 Suspicious,
463 /// High - very short window with exact amount match.
464 High,
465 /// Critical - pattern indicates potential wash trading or layering.
466 Critical,
467}
468
469/// Result of flow reversal analysis.
470#[derive(Debug, Clone, Serialize, Deserialize)]
471pub struct FlowReversalResult {
472 /// Detected reversal pairs.
473 pub reversals: Vec<FlowReversalPair>,
474 /// Total reversal volume.
475 pub reversal_volume: f64,
476 /// Reversal ratio (reversal volume / total volume).
477 pub reversal_ratio: f64,
478 /// Entities with multiple reversals.
479 pub repeat_offenders: Vec<(u64, u32)>,
480 /// Overall risk score (0-100).
481 pub risk_score: f64,
482}
483
484// ============================================================================
485// Flow Split Ratio Types
486// ============================================================================
487
488/// A detected flow split pattern.
489#[derive(Debug, Clone, Serialize, Deserialize)]
490pub struct FlowSplitPattern {
491 /// Source entity performing the split.
492 pub source_entity: u64,
493 /// Destination entities receiving the split transactions.
494 pub dest_entities: Vec<u64>,
495 /// Individual transaction IDs in the split.
496 pub transaction_ids: Vec<u64>,
497 /// Individual amounts.
498 pub amounts: Vec<f64>,
499 /// Total split amount.
500 pub total_amount: f64,
501 /// Time span of the split (seconds).
502 pub time_span: u64,
503 /// Estimated original amount (if structuring detected).
504 pub estimated_threshold: f64,
505 /// Risk level.
506 pub risk_level: SplitRiskLevel,
507}
508
509/// Risk level for flow split.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
511pub enum SplitRiskLevel {
512 /// Normal - likely legitimate batch payments.
513 Normal,
514 /// Elevated - amounts near reporting threshold.
515 Elevated,
516 /// High - clear structuring pattern.
517 High,
518 /// Critical - multiple splits targeting exact threshold.
519 Critical,
520}
521
522/// Result of flow split ratio analysis.
523#[derive(Debug, Clone, Serialize, Deserialize)]
524pub struct FlowSplitResult {
525 /// Detected split patterns.
526 pub splits: Vec<FlowSplitPattern>,
527 /// Entities with structuring patterns.
528 pub structuring_entities: Vec<u64>,
529 /// Total amount in split patterns.
530 pub split_volume: f64,
531 /// Split ratio (split volume / total volume).
532 pub split_ratio: f64,
533 /// Overall risk score (0-100).
534 pub risk_score: f64,
535}