| |
| """ |
| 简化的统一交易模式主程序 |
| 基于TransactionManager和UnifiedTransactionGenerator生成交易 |
| 支持真实的交易时间分布 |
| """ |
|
|
| import json |
| import csv |
| import numpy as np |
| import networkx as nx |
| import pandas as pd |
| from datetime import datetime, timedelta |
| from typing import Dict, List, Tuple |
| from collections import defaultdict |
| import time |
| import os |
| try: |
| import psutil |
| HAS_PSUTIL = True |
| except ImportError: |
| HAS_PSUTIL = False |
| from transaction_manager import TransactionManager |
| from unified_transaction_generator4 import UnifiedTransactionGenerator |
|
|
| def get_process_info() -> str: |
| """获取进程信息(内存使用等)""" |
| info = [] |
| if HAS_PSUTIL: |
| process = psutil.Process(os.getpid()) |
| mem_info = process.memory_info() |
| mem_mb = mem_info.rss / 1024 / 1024 |
| info.append(f"内存: {mem_mb:.1f} MB") |
| return ", ".join(info) if info else "" |
|
|
| def load_data(edges_file: str, accounts_file: str) -> Tuple: |
| """加载所有必要的数据""" |
| |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始加载图数据... {get_process_info()}") |
| edges_start = time.time() |
| g = nx.DiGraph() |
| with open(edges_file, 'r') as f: |
| reader = csv.reader(f) |
| next(reader) |
| for row in reader: |
| if len(row) >= 2: |
| g.add_edge(row[0], row[1]) |
| edges_elapsed = time.time() - edges_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 图数据加载完成: {g.number_of_nodes()} 个节点, {g.number_of_edges()} 条边, 耗时 {edges_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始加载账户数据... {get_process_info()}") |
| accounts_start = time.time() |
| balances = {} |
| wallet_to_attrs = {} |
| wallet_open_timestamps = {} |
| abnormal_wallets = set() |
| attr_headers = [] |
| with open(accounts_file, 'r') as f: |
| reader = csv.reader(f) |
| attr_headers = next(reader) |
| for row in reader: |
| if len(row) >= 14: |
| wallet_id = row[0] |
| |
| balance = float(row[11]) if row[11] else 0.0 |
| balances[wallet_id] = balance |
| wallet_to_attrs[wallet_id] = row[1:] |
| |
| |
| wallet_open_timestamp_str = row[6] if len(row) > 6 else None |
| if wallet_open_timestamp_str: |
| try: |
| wallet_open_timestamps[wallet_id] = datetime.strptime( |
| wallet_open_timestamp_str, "%Y-%m-%d %H:%M:%S" |
| ) |
| except ValueError: |
| |
| wallet_open_timestamps[wallet_id] = datetime(2024, 1, 1, 0, 0, 0) |
| else: |
| wallet_open_timestamps[wallet_id] = datetime(2024, 1, 1, 0, 0, 0) |
| |
| |
| |
| try: |
| is_abnormal_idx = attr_headers.index('is_abnormal') |
| if len(row) > is_abnormal_idx: |
| is_abnormal_value = row[is_abnormal_idx].strip() |
| |
| if is_abnormal_value in ['1', 'True', 'true', 'TRUE', 'Yes', 'yes', 'YES']: |
| abnormal_wallets.add(wallet_id) |
| except ValueError: |
| |
| if len(row) >= 14: |
| is_abnormal_value = row[13].strip() |
| if is_abnormal_value in ['1', 'True', 'true', 'TRUE', 'Yes', 'yes', 'YES']: |
| abnormal_wallets.add(wallet_id) |
| |
| accounts_elapsed = time.time() - accounts_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 账户数据加载完成: {len(balances)} 个账户, {len(abnormal_wallets)} 个异常账户, 耗时 {accounts_elapsed:.2f} 秒 {get_process_info()}") |
| |
| return g, balances, wallet_to_attrs, attr_headers, wallet_open_timestamps, abnormal_wallets |
|
|
| def generate_daily_transaction_schedule(config: Dict, rng) -> List[datetime]: |
| """基于配置生成每日交易时间表""" |
| daily_config = config.get("daily_transaction_config", {}) |
| base_transactions = daily_config.get("base_transactions_per_day", 500) |
| variance = daily_config.get("transaction_variance", 0.3) |
| hourly_dist = daily_config.get("hourly_distribution", {}) |
| |
| |
| actual_transactions = int(base_transactions * (1 + rng.normal(0, variance))) |
| actual_transactions = max(1, actual_transactions) |
| |
| |
| transaction_times = [] |
| |
| for _ in range(actual_transactions): |
| |
| hour_weights = [] |
| hour_ranges = [] |
| |
| for hour_range, weight in hourly_dist.items(): |
| hour_weights.append(weight) |
| |
| start_str, end_str = hour_range.split('-') |
| start_hour = int(start_str.split(':')[0]) |
| end_hour = int(end_str.split(':')[0]) |
| hour_ranges.append((start_hour, end_hour)) |
| |
| |
| total_weight = sum(hour_weights) |
| if total_weight > 0: |
| hour_weights = [w / total_weight for w in hour_weights] |
| |
| |
| selected_hour_range = rng.choice(len(hour_ranges), p=hour_weights) |
| start_hour, end_hour = hour_ranges[selected_hour_range] |
| |
| |
| if start_hour == end_hour: |
| hour = start_hour |
| else: |
| hour = rng.integers(start_hour, end_hour) |
| minute = rng.integers(0, 60) |
| second = rng.integers(0, 60) |
| |
| |
| transaction_time = datetime(2024, 1, 1, hour, minute, second) |
| transaction_times.append(transaction_time) |
| |
| |
| transaction_times.sort() |
| return transaction_times |
|
|
| def fix_merchant_laundering_many_to_many(transactions: List[Dict], merchant_wallet: str, |
| base_time: datetime, rng, |
| wallet_open_timestamps: Dict[str, datetime] = None) -> List[Dict]: |
| """ |
| 修复 merchant_laundering 的所有模式(many_to_many, one_to_many, many_to_one): |
| 1. 确保转入交易时间早于转出交易时间 |
| 2. 确保转入总额 = 转出总额 / (1 - 佣金率),其中佣金率在 0.8%-1.8% 之间 |
| """ |
| if not transactions: |
| return transactions |
| |
| |
| first_tx = transactions[0] |
| transaction_mode = first_tx.get("transaction_mode") |
| supported_modes = ["many_to_many", "one_to_many", "many_to_one"] |
| |
| if transaction_mode not in supported_modes: |
| return transactions |
| |
| |
| |
| |
| if transaction_mode == "one_to_many": |
| main_wallet = merchant_wallet |
| else: |
| |
| dst_counts = {} |
| for tx in transactions: |
| dst = tx.get("dst") |
| if dst: |
| dst_counts[dst] = dst_counts.get(dst, 0) + 1 |
| |
| if dst_counts: |
| main_wallet = max(dst_counts, key=dst_counts.get) |
| else: |
| main_wallet = merchant_wallet |
| |
| |
| incoming_txs = [] |
| outgoing_txs = [] |
| |
| for tx in transactions: |
| if tx.get("dst") == main_wallet: |
| incoming_txs.append(tx) |
| elif tx.get("src") == main_wallet: |
| outgoing_txs.append(tx) |
| |
| |
| if not incoming_txs or not outgoing_txs: |
| return transactions |
| |
| |
| total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| total_outgoing = sum(float(tx.get("amount", 0)) for tx in outgoing_txs) |
| |
| |
| if total_incoming <= 0 or total_outgoing <= 0: |
| return transactions |
| |
| |
| commission_rate = rng.uniform(0.008, 0.018) |
| |
| |
| |
| |
| |
| if total_incoming < total_outgoing: |
| |
| target_incoming_total = total_outgoing / (1 - commission_rate) |
| scale_factor = target_incoming_total / total_incoming |
| |
| for tx in incoming_txs: |
| original_amount = float(tx.get("amount", 0)) |
| new_amount = original_amount * scale_factor |
| tx["amount"] = round(new_amount, 2) |
| else: |
| |
| target_outgoing_total = total_incoming * (1 - commission_rate) |
| scale_factor = target_outgoing_total / total_outgoing |
| |
| for tx in outgoing_txs: |
| original_amount = float(tx.get("amount", 0)) |
| new_amount = original_amount * scale_factor |
| tx["amount"] = round(new_amount, 2) |
| |
| |
| |
| time_offset = 0 |
| for tx in incoming_txs: |
| tx_time = base_time + timedelta(seconds=int(time_offset)) |
| tx["timestamp"] = tx_time.strftime("%Y-%m-%d %H:%M:%S") |
| time_offset += int(rng.integers(60, 300)) |
| |
| |
| |
| base_outgoing_time = base_time + timedelta(seconds=int(time_offset + 60)) |
| time_offset = 0 |
| for tx in outgoing_txs: |
| tx_time = base_outgoing_time + timedelta(seconds=int(time_offset)) |
| tx["timestamp"] = tx_time.strftime("%Y-%m-%d %H:%M:%S") |
| time_offset += int(rng.integers(60, 300)) |
| |
| |
| fixed_transactions = incoming_txs + outgoing_txs |
| |
| |
| fixed_transactions.sort(key=lambda x: x.get("timestamp", "")) |
| |
| return fixed_transactions |
|
|
| def adjust_motif_balance_after_limit_check(motif_id: str, pending_motifs: Dict, |
| saved_incoming: float, saved_outgoing: float, |
| main_wallet: str, rng) -> None: |
| """ |
| 在限额检查之后,动态调整 pending_motifs 中剩余交易的金额,确保转入总额 > 转出总额 |
| 这个函数会在每次从 pending_motifs 取出交易并通过限额检查后调用 |
| """ |
| if motif_id not in pending_motifs: |
| return |
| |
| motif_data = pending_motifs[motif_id] |
| remaining_txs = motif_data['transactions'][motif_data['current_index']:] |
| |
| if not remaining_txs: |
| return |
| |
| |
| remaining_incoming = 0.0 |
| remaining_outgoing = 0.0 |
| remaining_incoming_txs = [] |
| remaining_outgoing_txs = [] |
| |
| for tx in remaining_txs: |
| if tx.get("dst") == main_wallet: |
| remaining_incoming += float(tx.get("amount", 0)) |
| remaining_incoming_txs.append(tx) |
| elif tx.get("src") == main_wallet: |
| remaining_outgoing += float(tx.get("amount", 0)) |
| remaining_outgoing_txs.append(tx) |
| |
| |
| total_incoming = saved_incoming + remaining_incoming |
| total_outgoing = saved_outgoing + remaining_outgoing |
| |
| |
| |
| |
| |
| if remaining_incoming > 0 and total_incoming < total_outgoing: |
| |
| margin = rng.uniform(0.05, 0.15) |
| target_total_incoming = (saved_outgoing + remaining_outgoing) * (1 + margin) |
| target_remaining_incoming = target_total_incoming - saved_incoming |
| |
| if target_remaining_incoming > 0: |
| scale_factor = target_remaining_incoming / remaining_incoming |
| |
| |
| |
| for tx in remaining_incoming_txs: |
| original_amount = float(tx.get("amount", 0)) |
| new_amount = original_amount * scale_factor |
| tx["amount"] = round(new_amount, 2) |
| |
| |
| new_remaining_incoming = sum(float(tx.get("amount", 0)) for tx in remaining_incoming_txs) |
| new_total_incoming = saved_incoming + new_remaining_incoming |
| new_total_outgoing = saved_outgoing + remaining_outgoing |
| |
| |
| |
| if new_total_incoming <= new_total_outgoing and remaining_incoming_txs: |
| diff = new_total_outgoing - new_total_incoming |
| last_tx = remaining_incoming_txs[-1] |
| old_last_amount = float(last_tx.get("amount", 0)) |
| last_tx["amount"] = round(old_last_amount + diff + 0.01, 2) |
| |
| |
| final_remaining_incoming = sum(float(tx.get("amount", 0)) for tx in remaining_incoming_txs) |
| final_total_incoming = saved_incoming + final_remaining_incoming |
| |
| |
| elif remaining_incoming == 0 and remaining_outgoing > 0 and saved_incoming > 0 and total_incoming < total_outgoing: |
| |
| |
| margin = rng.uniform(0.05, 0.15) |
| target_total_outgoing = saved_incoming * (1 - margin) |
| target_remaining_outgoing = target_total_outgoing - saved_outgoing |
| |
| if target_remaining_outgoing > 0 and target_remaining_outgoing < remaining_outgoing: |
| scale_factor = target_remaining_outgoing / remaining_outgoing |
| |
| |
| |
| for tx in remaining_outgoing_txs: |
| original_amount = float(tx.get("amount", 0)) |
| new_amount = original_amount * scale_factor |
| tx["amount"] = round(new_amount, 2) |
| |
| |
| new_remaining_outgoing = sum(float(tx.get("amount", 0)) for tx in remaining_outgoing_txs) |
| new_total_incoming = saved_incoming |
| new_total_outgoing = saved_outgoing + new_remaining_outgoing |
| |
| |
| |
| if new_total_incoming <= new_total_outgoing and remaining_outgoing_txs: |
| diff = new_total_outgoing - new_total_incoming |
| last_tx = remaining_outgoing_txs[-1] |
| old_last_amount = float(last_tx.get("amount", 0)) |
| last_tx["amount"] = round(old_last_amount - diff - 0.01, 2) |
| |
| |
| final_remaining_outgoing = sum(float(tx.get("amount", 0)) for tx in remaining_outgoing_txs) |
| final_total_outgoing = saved_outgoing + final_remaining_outgoing |
| else: |
| pass |
|
|
| def fix_transaction_balance(transactions: List[Dict], source_wallet: str, |
| base_time: datetime, rng, |
| wallet_open_timestamps: Dict[str, datetime] = None) -> List[Dict]: |
| """ |
| 通用的交易平衡修复函数(适用于所有交易类型,除了 merchant_laundering): |
| 对于 many_to_many, one_to_many, many_to_one 模式: |
| 1. 确保转入交易时间早于转出交易时间 |
| 2. 确保转入总额 > 转出总额(转入必须高于转出,无佣金) |
| """ |
| if not transactions: |
| return transactions |
| |
| |
| first_tx = transactions[0] |
| transaction_mode = first_tx.get("transaction_mode") |
| transaction_motif = first_tx.get("risk_type", "unknown") |
| motif_id = first_tx.get("motif_id", "unknown") |
| supported_modes = ["many_to_many", "one_to_many", "many_to_one"] |
| |
| |
| |
| if transaction_mode not in supported_modes: |
| return transactions |
| |
| |
| |
| |
| if transaction_mode == "one_to_many": |
| main_wallet = source_wallet |
| else: |
| |
| dst_counts = {} |
| for tx in transactions: |
| dst = tx.get("dst") |
| if dst: |
| dst_counts[dst] = dst_counts.get(dst, 0) + 1 |
| |
| if dst_counts: |
| main_wallet = max(dst_counts, key=dst_counts.get) |
| else: |
| main_wallet = source_wallet |
| |
| |
| incoming_txs = [] |
| outgoing_txs = [] |
| |
| for tx in transactions: |
| if tx.get("dst") == main_wallet: |
| incoming_txs.append(tx) |
| elif tx.get("src") == main_wallet: |
| outgoing_txs.append(tx) |
| |
| |
| if not incoming_txs or not outgoing_txs: |
| return transactions |
| |
| |
| total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| total_outgoing = sum(float(tx.get("amount", 0)) for tx in outgoing_txs) |
| |
| |
| if total_incoming <= 0 or total_outgoing <= 0: |
| return transactions |
| |
| |
| |
| |
| if total_incoming < total_outgoing: |
| |
| margin = rng.uniform(0.05, 0.15) |
| target_incoming_total = total_outgoing * (1 + margin) |
| scale_factor = target_incoming_total / total_incoming |
| |
| |
| |
| adjusted_details = [] |
| for tx in incoming_txs: |
| original_amount = float(tx.get("amount", 0)) |
| new_amount = original_amount * scale_factor |
| tx["amount"] = round(new_amount, 2) |
| adjusted_details.append((tx.get("tx_id"), original_amount, tx.get("amount"))) |
| |
| |
| |
| new_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| |
| if new_total_incoming < total_outgoing: |
| |
| diff = total_outgoing - new_total_incoming |
| if incoming_txs and diff > 0: |
| |
| last_tx = incoming_txs[-1] |
| old_last_amount = float(last_tx.get("amount", 0)) |
| last_tx["amount"] = round(old_last_amount + diff + 0.01, 2) |
| |
| |
| |
| if wallet_open_timestamps: |
| min_open_time = None |
| for tx in transactions: |
| src = tx.get("src") |
| dst = tx.get("dst") |
| if src and src in wallet_open_timestamps: |
| open_time = wallet_open_timestamps[src] |
| if min_open_time is None or open_time > min_open_time: |
| min_open_time = open_time |
| if dst and dst in wallet_open_timestamps: |
| open_time = wallet_open_timestamps[dst] |
| if min_open_time is None or open_time > min_open_time: |
| min_open_time = open_time |
| if min_open_time and base_time < min_open_time: |
| base_time = min_open_time |
| |
| |
| time_offset = 0 |
| for tx in incoming_txs: |
| tx_time = base_time + timedelta(seconds=int(time_offset)) |
| |
| if wallet_open_timestamps: |
| src = tx.get("src") |
| dst = tx.get("dst") |
| if src and src in wallet_open_timestamps: |
| src_open_time = wallet_open_timestamps[src] |
| if tx_time < src_open_time: |
| tx_time = src_open_time |
| if dst and dst in wallet_open_timestamps: |
| dst_open_time = wallet_open_timestamps[dst] |
| if tx_time < dst_open_time: |
| tx_time = dst_open_time |
| tx["timestamp"] = tx_time.strftime("%Y-%m-%d %H:%M:%S") |
| time_offset += int(rng.integers(60, 300)) |
| |
| |
| |
| base_outgoing_time = base_time + timedelta(seconds=int(time_offset + 60)) |
| time_offset = 0 |
| for tx in outgoing_txs: |
| tx_time = base_outgoing_time + timedelta(seconds=int(time_offset)) |
| |
| if wallet_open_timestamps: |
| src = tx.get("src") |
| dst = tx.get("dst") |
| if src and src in wallet_open_timestamps: |
| src_open_time = wallet_open_timestamps[src] |
| if tx_time < src_open_time: |
| tx_time = src_open_time |
| if dst and dst in wallet_open_timestamps: |
| dst_open_time = wallet_open_timestamps[dst] |
| if tx_time < dst_open_time: |
| tx_time = dst_open_time |
| tx["timestamp"] = tx_time.strftime("%Y-%m-%d %H:%M:%S") |
| time_offset += int(rng.integers(60, 300)) |
| |
| |
| final_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| final_total_outgoing = sum(float(tx.get("amount", 0)) for tx in outgoing_txs) |
| |
| |
| if final_total_incoming < final_total_outgoing: |
| |
| |
| if incoming_txs: |
| diff = final_total_outgoing - final_total_incoming |
| last_tx = incoming_txs[-1] |
| old_last_amount = float(last_tx.get("amount", 0)) |
| |
| last_tx["amount"] = round(old_last_amount + diff + 0.01, 2) |
| |
| |
| final_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| elif final_total_incoming > final_total_outgoing and final_total_outgoing > 0: |
| |
| diff = final_total_incoming - final_total_outgoing |
| diff_ratio = diff / final_total_outgoing |
| if diff_ratio > 0.01: |
| if incoming_txs: |
| |
| target_total_incoming = final_total_outgoing |
| current_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| reduction_needed = current_total_incoming - target_total_incoming |
| |
| if reduction_needed > 0: |
| |
| scale_factor = target_total_incoming / current_total_incoming |
| |
| for tx in incoming_txs: |
| old_amount = float(tx.get("amount", 0)) |
| tx["amount"] = round(old_amount * scale_factor, 2) |
| |
| |
| new_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| if new_total_incoming != final_total_outgoing: |
| |
| diff_remaining = new_total_incoming - final_total_outgoing |
| last_tx = incoming_txs[-1] |
| old_last_amount = float(last_tx.get("amount", 0)) |
| last_tx["amount"] = round(old_last_amount - diff_remaining, 2) |
| |
| |
| final_total_incoming = sum(float(tx.get("amount", 0)) for tx in incoming_txs) |
| |
| |
| fixed_transactions = incoming_txs + outgoing_txs |
| |
| |
| fixed_transactions.sort(key=lambda x: x.get("timestamp", "")) |
| |
| |
| final_incoming_details = [(tx.get("tx_id"), tx.get("src"), tx.get("dst"), tx.get("amount"), tx.get("timestamp")) for tx in incoming_txs] |
| final_outgoing_details = [(tx.get("tx_id"), tx.get("src"), tx.get("dst"), tx.get("amount"), tx.get("timestamp")) for tx in outgoing_txs] |
| |
| if final_total_incoming < final_total_outgoing: |
| pass |
| else: |
| |
| diff_value = final_total_incoming - final_total_outgoing |
| if diff_value == 0.0: |
| pass |
| elif final_total_outgoing > 0 and diff_value / final_total_outgoing > 0.01: |
| |
| pass |
| else: |
| pass |
| |
| return fixed_transactions |
|
|
| def generate_transactions(g: nx.DiGraph, balances: Dict[str, float], |
| wallet_to_attrs: Dict[str, List[str]], attr_headers: List[str], |
| wallet_open_timestamps: Dict[str, datetime], abnormal_wallets: set, |
| config: Dict, output_file: str = None) -> List[Dict]: |
| """生成交易的主函数""" |
| |
| |
| generation_start_time = time.time() |
| |
| |
| manager = TransactionManager("transaction_config.json") |
| generator = UnifiedTransactionGenerator("transaction_config.json") |
| |
| |
| start_time = datetime.strptime(config.get("start_time", "2024-01-01 00:00:00"), "%Y-%m-%d %H:%M:%S") |
| duration_days = int(config.get("duration_days", 7)) |
| max_frac_per_tx = float(config.get("max_frac_per_tx", 0.2)) |
| min_abs_amount = float(config.get("min_abs_amount", 0.01)) |
| seed = int(config.get("random_seed", 44)) |
| |
| rng = np.random.default_rng(seed) |
| transactions = [] |
| current_balances = balances.copy() |
| |
| |
| csv_file = None |
| csv_writer = None |
| transaction_buffer = [] |
| buffer_size = 10000 |
| safe_motifs = {'single_transaction', 'normal_small_high_freq', 'regular_large_low_freq'} |
| wallet_info_cache = {} |
| |
| |
| motif_saved_amounts = {} |
| |
| |
| wallet_first_tx_time = {} |
| abandoned_wallets = set() |
| |
| if output_file: |
| csv_file = open(output_file, 'w', newline='', encoding='utf-8') |
| csv_writer = csv.writer(csv_file) |
| |
| csv_writer.writerow(["tx_id", "timestamp", "src", "dst", "amount", "transaction_motif", |
| "motif_id", "transaction_mode", "is_risk", "src_bank_account_number", |
| "dst_bank_account_number", "src_wallet_level", "dst_wallet_level"]) |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已创建CSV文件: {output_file},将每 {buffer_size} 笔交易批量写入 {get_process_info()}") |
| |
| |
| |
| wallet_plans = {} |
| allowed_levels = ["1", "2", "3", "4"] |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 正在初始化钱包计划并预计算属性(wallet_level='1', '2', '3', '4')... {get_process_info()}") |
| init_start = time.time() |
| level_1_count = 0 |
| level_2_count = 0 |
| level_3_count = 0 |
| level_4_count = 0 |
| skipped_count = 0 |
| for wallet_id in g.nodes(): |
| wallet_attrs = wallet_to_attrs.get(wallet_id, []) |
| wallet_type = None |
| wallet_level = None |
| |
| |
| for i, h in enumerate(attr_headers): |
| if h in ['wallet_type', 'type'] and i > 0 and i-1 < len(wallet_attrs): |
| wallet_type = wallet_attrs[i-1] |
| elif h in ['wallet_level', 'level'] and i > 0 and i-1 < len(wallet_attrs): |
| wallet_level = wallet_attrs[i-1] |
| |
| |
| if wallet_type is None and len(wallet_attrs) > 0: |
| wallet_type = wallet_attrs[0] |
| if wallet_level is None and len(wallet_attrs) > 1: |
| wallet_level = wallet_attrs[1] |
| |
| |
| if wallet_type is not None: |
| wallet_type = str(wallet_type) |
| if wallet_level is not None: |
| wallet_level = str(wallet_level) |
| |
| |
| if wallet_level not in allowed_levels: |
| skipped_count += 1 |
| continue |
| |
| |
| if wallet_level == "1": |
| level_1_count += 1 |
| elif wallet_level == "2": |
| level_2_count += 1 |
| elif wallet_level == "3": |
| level_3_count += 1 |
| elif wallet_level == "4": |
| level_4_count += 1 |
| |
| |
| cached_wallet_level = manager.get_wallet_level(wallet_id, wallet_to_attrs, attr_headers) |
| cached_limits = manager.get_wallet_level_limits(cached_wallet_level) |
| |
| wallet_plans[wallet_id] = { |
| 'neighbors': list(g.successors(wallet_id)), |
| 'last_tx_time': start_time, |
| 'tx_count': 0, |
| 'risk_tx_count': 0, |
| 'wallet_type': wallet_type, |
| 'wallet_level': wallet_level, |
| 'cached_wallet_level': cached_wallet_level, |
| 'cached_limits': cached_limits, |
| 'current_daily_amount': 0.0, |
| 'daily_limit_reached': False, |
| 'reservation_transactions': [], |
| 'last_salary_time': None, |
| 'next_salary_time': None, |
| 'salary_interval_days': None, |
| 'salary_employees': [], |
| 'base_salary': None, |
| 'can_generate_salary': True |
| } |
| init_elapsed = time.time() - init_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 完成初始化 {len(wallet_plans)} 个钱包计划 (level 1: {level_1_count}, level 2: {level_2_count}, level 3: {level_3_count}, level 4: {level_4_count}), 跳过 {skipped_count} 个其他等级钱包, 耗时 {init_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| |
| current_date = None |
| |
| |
| cached_available_wallets = None |
| cached_available_wallets_date = None |
| |
| |
| all_wallets_list = list(wallet_plans.keys()) |
| all_wallets_set = set(all_wallets_list) |
|
|
| |
| motif_stats_cache = {} |
| |
| |
| current_mixed_count = 0 |
|
|
| |
| total_transactions = 0 |
| risk_transactions = 0 |
| normal_transactions = 0 |
| |
| |
| risk_wallets_set = set() |
| |
| |
| |
| |
| |
| wallet_tx_type_preference = {} |
| max_mixed_wallets_ratio = 0.1 |
| max_mixed_wallets_count = int(len(g.nodes()) * max_mixed_wallets_ratio) |
| |
| |
| forced_risk_wallets = set() |
| |
| |
| wallet_policy = manager.global_settings.get("wallet_selection_policy", {}) |
| abnormal_wallet_risk_ratio = wallet_policy.get("abnormal_wallet_risk_ratio", 0.95) |
| normal_wallet_risk_ratio = wallet_policy.get("normal_wallet_risk_ratio", 0.05) |
| abnormal_wallet_normal_ratio = wallet_policy.get("abnormal_wallet_normal_ratio", 0.1) |
| normal_wallet_normal_ratio = wallet_policy.get("normal_wallet_normal_ratio", 0.95) |
| max_risk_wallets_ratio = wallet_policy.get("max_risk_wallets_ratio", 0.15) |
| |
| |
| |
| |
| max_risk_wallets_count_by_ratio = int(len(g.nodes()) * max_risk_wallets_ratio) |
| |
| |
| max_risk_wallets_count_by_abnormal = int(len(abnormal_wallets) * 1.2) |
| |
| |
| max_risk_wallets_count = min(max_risk_wallets_count_by_ratio, max_risk_wallets_count_by_abnormal) |
| |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始生成交易,风险交易比例目标: {manager.get_risk_ratio():.1%} {get_process_info()}") |
| print(f"每个钱包最大风险交易次数: {manager.get_max_risk_transactions_per_wallet()}") |
| print(f"异常账户数量: {len(abnormal_wallets):,}") |
| print(f"最多参与风险交易的钱包数: {max_risk_wallets_count:,} (基于比例: {max_risk_wallets_ratio*100:.1f}% = {max_risk_wallets_count_by_ratio:,}, 基于异常账户1.2倍: {max_risk_wallets_count_by_abnormal:,})") |
| print(f"策略:优先使用异常账户(is_abnormal=1),如果异常账户不足,允许少量正常账户补充") |
| print(f" 一旦正常账户被选中参与异常交易,将加入forced_risk_wallets,以后只能参与异常交易") |
| print(f" 一旦达到限制,只从已参与风险交易的钱包中选择(不再扩展)") |
| print(f"异常账户参与风险交易比例: {abnormal_wallet_risk_ratio*100:.1f}%") |
| print(f"正常账户参与风险交易比例: {normal_wallet_risk_ratio*100:.1f}%") |
| print(f"最多混合钱包数量: {max_mixed_wallets_count:,} ({max_mixed_wallets_ratio*100:.1f}%)") |
| |
| |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始生成交易时间表... {get_process_info()}") |
| schedule_start = time.time() |
| all_transaction_times = [] |
| for day in range(duration_days): |
| current_date = start_time + timedelta(days=day) |
| daily_times = generate_daily_transaction_schedule(config, rng) |
| |
| |
| for tx_time in daily_times: |
| actual_time = current_date.replace(hour=tx_time.hour, minute=tx_time.minute, second=tx_time.second) |
| all_transaction_times.append(actual_time) |
| |
| |
| all_transaction_times.sort() |
| schedule_elapsed = time.time() - schedule_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 生成了 {len(all_transaction_times):,} 个交易时间点, 耗时 {schedule_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| tx_id = 1 |
| processed_count = 0 |
| |
| |
| |
| pending_motifs = {} |
| |
| motif_interleaving_config = config.get("motif_interleaving", {}) |
| continue_motif_probability = float(motif_interleaving_config.get("continue_motif_probability", 0.3)) |
| |
| for current_time in all_transaction_times: |
| processed_count += 1 |
| |
| if processed_count % 5000 == 0: |
| progress = processed_count / len(all_transaction_times) * 100 |
| elapsed = time.time() - generation_start_time |
| if processed_count > 0 and elapsed > 0: |
| rate = processed_count / elapsed |
| remaining = (len(all_transaction_times) - processed_count) / rate if rate > 0 else 0 |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 进度: {processed_count:,}/{len(all_transaction_times):,} ({progress:.1f}%) | " |
| f"已用时: {elapsed/60:.1f}分钟 | 预计剩余: {remaining/60:.1f}分钟 | " |
| f"已生成交易: {total_transactions:,} 笔 (风险: {risk_transactions:,}, 正常: {normal_transactions:,}) {get_process_info()}") |
| else: |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 进度: {processed_count:,}/{len(all_transaction_times):,} ({progress:.1f}%) {get_process_info()}") |
| |
| |
| new_date = current_time.date() |
| if current_date != new_date: |
| current_date = new_date |
| |
| |
| |
| for wallet_id in wallet_plans: |
| wallet_plans[wallet_id]['current_daily_amount'] = 0.0 |
| wallet_plans[wallet_id]['daily_limit_reached'] = False |
| |
| |
| |
| wallets_with_balance = [w for w in all_wallets_list |
| if w in wallet_plans and |
| current_balances.get(w, 0) > 0] |
| |
| |
| |
| cached_available_wallets = [] |
| for wallet in wallets_with_balance: |
| plan = wallet_plans[wallet] |
| |
| if plan.get('daily_limit_reached', False): |
| continue |
| |
| |
| if not plan['neighbors']: |
| continue |
| |
| |
| limits = plan['cached_limits'] |
| daily_limit = limits.get('daily_limit') |
| |
| |
| |
| if daily_limit is not None: |
| current_daily_amount = plan['current_daily_amount'] |
| if current_daily_amount >= daily_limit: |
| plan['daily_limit_reached'] = True |
| continue |
| |
| |
| cached_available_wallets.append(wallet) |
| |
| cached_available_wallets_date = current_date |
| |
| |
| if not cached_available_wallets: |
| |
| for wallet in all_wallets_list: |
| if wallet not in wallet_plans: |
| continue |
| if wallet in current_balances: |
| plan = wallet_plans[wallet] |
| if plan.get('daily_limit_reached', False): |
| continue |
| if not plan['neighbors']: |
| continue |
| cached_available_wallets.append(wallet) |
| |
| |
| |
| if cached_available_wallets: |
| |
| |
| available_wallets_set = set(cached_available_wallets) |
| |
| |
| |
| wallets_to_check = [] |
| for wallet in cached_available_wallets: |
| plan = wallet_plans[wallet] |
| if plan.get('daily_limit_reached', False): |
| available_wallets_set.discard(wallet) |
| continue |
| |
| limits = plan['cached_limits'] |
| daily_limit = limits.get('daily_limit') |
| if daily_limit is not None: |
| wallets_to_check.append((wallet, daily_limit)) |
| |
| |
| for wallet, daily_limit in wallets_to_check: |
| |
| plan = wallet_plans[wallet] |
| current_daily_amount = plan['current_daily_amount'] |
| if current_daily_amount >= daily_limit: |
| plan['daily_limit_reached'] = True |
| available_wallets_set.discard(wallet) |
| |
| |
| available_wallets_filtered = list(available_wallets_set) |
| else: |
| available_wallets_filtered = [] |
| |
| |
| available_wallets_filtered = [w for w in available_wallets_filtered if w not in abandoned_wallets] |
| |
| if not available_wallets_filtered: |
| |
| if processed_count % 10000 == 0: |
| print(f"当前时间点所有钱包都达到日交易额度限制,跳过(已处理 {processed_count:,}/{len(all_transaction_times):,} 个时间点,等待下一天重置限额)") |
| continue |
| |
| |
| new_transactions = [] |
| selected_transaction_type = None |
| source_wallet = None |
| plan = None |
| is_continue_motif = False |
| is_continued_motif_processed = False |
| |
| |
| if pending_motifs and rng.random() < continue_motif_probability: |
| is_continue_motif = True |
| |
| if is_continue_motif and pending_motifs: |
| |
| motif_id = rng.choice(list(pending_motifs.keys())) |
| motif_data = pending_motifs[motif_id] |
| |
| |
| if motif_data['current_index'] < len(motif_data['transactions']): |
| next_tx = motif_data['transactions'][motif_data['current_index']].copy() |
| next_tx_amount_before = next_tx.get("amount") |
| next_tx_timestamp_before = next_tx.get("timestamp") |
| |
| if motif_data['transaction_type'] == 'merchant_laundering': |
| pass |
| |
| elif next_tx.get("transaction_mode") in ["many_to_many", "many_to_one", "one_to_many"]: |
| pass |
| else: |
| next_tx['timestamp'] = current_time.strftime("%Y-%m-%d %H:%M:%S") |
| new_transactions = [next_tx] |
| motif_data['current_index'] += 1 |
| |
| |
| if motif_data['current_index'] >= len(motif_data['transactions']): |
| del pending_motifs[motif_id] |
| |
| selected_transaction_type = motif_data['transaction_type'] |
| source_wallet = motif_data['source_wallet'] |
| plan = motif_data.get('plan') |
| |
| |
| is_continued_motif_processed = True |
| |
| |
| if new_transactions: |
| |
| tx = new_transactions[0] |
| src = tx['src'] |
| dst = tx.get('dst') |
| amount = float(tx['amount']) |
| motif_id_check = tx.get('motif_id') |
| tx_id_check = tx.get('tx_id') |
| tx_timestamp_str = tx.get("timestamp") |
| |
| |
| if src in abandoned_wallets or (dst and dst in abandoned_wallets): |
| new_transactions = [] |
| continue |
| |
| |
| if tx_timestamp_str: |
| try: |
| tx_timestamp = datetime.strptime(tx_timestamp_str, "%Y-%m-%d %H:%M:%S") |
| |
| |
| if src not in wallet_first_tx_time: |
| src_open_time = wallet_open_timestamps.get(src) |
| if src_open_time and tx_timestamp < src_open_time: |
| |
| abandoned_wallets.add(src) |
| new_transactions = [] |
| continue |
| else: |
| |
| wallet_first_tx_time[src] = tx_timestamp |
| |
| |
| if dst and dst not in wallet_first_tx_time: |
| dst_open_time = wallet_open_timestamps.get(dst) |
| if dst_open_time and tx_timestamp < dst_open_time: |
| |
| abandoned_wallets.add(dst) |
| new_transactions = [] |
| continue |
| else: |
| |
| wallet_first_tx_time[dst] = tx_timestamp |
| except: |
| pass |
| |
| |
| if not new_transactions: |
| continue |
| |
| if src in wallet_plans: |
| plan_wallet = wallet_plans[src] |
| limits = plan_wallet['cached_limits'] |
| single_limit = limits.get('single_transaction_limit') |
| daily_limit = limits.get('daily_limit') |
| current_daily_amount = plan_wallet['current_daily_amount'] |
| current_balance = current_balances.get(src, 0) |
| |
| |
| |
| |
| transaction_mode = tx.get("transaction_mode") |
| should_adjust = (transaction_mode in ["many_to_many", "many_to_one", "one_to_many"] and motif_id_check) |
| |
| if should_adjust: |
| |
| if transaction_mode == "one_to_many": |
| main_wallet = source_wallet |
| else: |
| |
| if motif_id_check in motif_saved_amounts: |
| main_wallet = motif_saved_amounts[motif_id_check].get('main_wallet', tx.get('dst')) |
| else: |
| |
| if motif_id_check in pending_motifs: |
| motif_data_temp = pending_motifs[motif_id_check] |
| dst_counts = {} |
| for temp_tx in motif_data_temp['transactions']: |
| temp_dst = temp_tx.get("dst") |
| if temp_dst: |
| dst_counts[temp_dst] = dst_counts.get(temp_dst, 0) + 1 |
| main_wallet = max(dst_counts, key=dst_counts.get) if dst_counts else tx.get('dst') |
| else: |
| main_wallet = tx.get('dst') |
| |
| |
| if motif_id_check not in motif_saved_amounts: |
| motif_saved_amounts[motif_id_check] = { |
| 'main_wallet': main_wallet, |
| 'saved_incoming': 0.0, |
| 'saved_outgoing': 0.0 |
| } |
| |
| |
| if single_limit is not None and amount > single_limit: |
| new_transactions = [] |
| plan_wallet['daily_limit_reached'] = True |
| |
| elif daily_limit is not None and (current_daily_amount + amount) > daily_limit: |
| new_transactions = [] |
| plan_wallet['daily_limit_reached'] = True |
| |
| elif current_balance < amount: |
| new_transactions = [] |
| else: |
| |
| current_balances[src] -= amount |
| current_balances[tx['dst']] = current_balances.get(tx['dst'], 0) + amount |
| plan_wallet['current_daily_amount'] += amount |
| |
| |
| |
| |
| if should_adjust: |
| saved_incoming = motif_saved_amounts[motif_id_check]['saved_incoming'] |
| saved_outgoing = motif_saved_amounts[motif_id_check]['saved_outgoing'] |
| adjust_motif_balance_after_limit_check( |
| motif_id_check, pending_motifs, saved_incoming, saved_outgoing, main_wallet, rng |
| ) |
| else: |
| new_transactions = [] |
| |
| |
| if not new_transactions: |
| |
| if 'motif_id_check' in locals(): |
| pass |
| else: |
| pass |
| continue |
| |
| |
| |
| if not new_transactions: |
| |
| if total_transactions > 0: |
| current_risk_ratio = risk_transactions / total_transactions |
| else: |
| current_risk_ratio = 0.0 |
| target_risk_ratio = manager.get_risk_ratio() |
| |
| |
| |
| is_risk_tx_decision = False |
| |
| |
| available_wallets_set = set(available_wallets_filtered) |
| |
| |
| |
| if len(risk_wallets_set) >= max_risk_wallets_count: |
| |
| risk_available_set = available_wallets_set & risk_wallets_set |
| |
| risk_available_check = [w for w in risk_available_set if wallet_plans[w]['neighbors']] |
| if not risk_available_check: |
| |
| is_risk_tx_decision = False |
| else: |
| |
| if current_risk_ratio < target_risk_ratio: |
| |
| risk_probability = target_risk_ratio + (target_risk_ratio - current_risk_ratio) * 0.5 |
| is_risk_tx_decision = rng.random() < min(risk_probability, target_risk_ratio * 2) |
| else: |
| |
| risk_probability = max(0.0, target_risk_ratio * 0.1) |
| is_risk_tx_decision = rng.random() < risk_probability |
| else: |
| |
| if current_risk_ratio < target_risk_ratio: |
| |
| risk_probability = target_risk_ratio + (target_risk_ratio - current_risk_ratio) * 0.5 |
| is_risk_tx_decision = rng.random() < min(risk_probability, target_risk_ratio * 2) |
| else: |
| |
| risk_probability = max(0.0, target_risk_ratio * 0.1) |
| is_risk_tx_decision = rng.random() < risk_probability |
| |
| |
| if is_risk_tx_decision: |
| |
| |
| |
| |
| |
| |
| if len(risk_wallets_set) >= max_risk_wallets_count: |
| |
| |
| risk_candidates_set = available_wallets_set & risk_wallets_set |
| risk_available = [w for w in risk_candidates_set if wallet_plans[w]['neighbors']] |
| if risk_available: |
| |
| preferred_risk = [w for w in risk_available |
| if wallet_tx_type_preference.get(w) in ['risk', None]] |
| non_preferred_risk = [w for w in risk_available |
| if wallet_tx_type_preference.get(w) == 'normal'] |
| |
| if preferred_risk: |
| |
| abnormal_preferred = [w for w in preferred_risk if w in abnormal_wallets] |
| if abnormal_preferred and rng.random() < abnormal_wallet_risk_ratio: |
| source_wallet = rng.choice(abnormal_preferred) |
| else: |
| source_wallet = rng.choice(preferred_risk) |
| elif non_preferred_risk: |
| |
| source_wallet = rng.choice(non_preferred_risk) |
| else: |
| source_wallet = rng.choice(risk_available) |
| else: |
| |
| is_risk_tx_decision = False |
| source_wallet = None |
| else: |
| |
| |
| abnormal_available_set = abnormal_wallets & available_wallets_set - risk_wallets_set |
| abnormal_available = [w for w in abnormal_available_set if wallet_plans[w]['neighbors']] |
| |
| |
| if not abnormal_available: |
| |
| abnormal_available_set = abnormal_wallets & all_wallets_set |
| abnormal_available = [w for w in abnormal_available_set |
| if w in current_balances and |
| not wallet_plans[w].get('daily_limit_reached', False) and |
| wallet_plans[w]['neighbors']] |
| |
| |
| remaining_slots = max_risk_wallets_count - len(risk_wallets_set) |
| abnormal_not_in_set = len([w for w in abnormal_wallets if w not in risk_wallets_set]) |
| |
| if abnormal_available and rng.random() < abnormal_wallet_risk_ratio: |
| |
| source_wallet = rng.choice(abnormal_available) |
| risk_wallets_set.add(source_wallet) |
| elif abnormal_not_in_set < remaining_slots: |
| |
| |
| normal_candidates = available_wallets_set - abnormal_wallets - risk_wallets_set - forced_risk_wallets |
| normal_available = [w for w in normal_candidates if wallet_plans[w]['neighbors']] |
| if normal_available and len(risk_wallets_set) < max_risk_wallets_count: |
| source_wallet = rng.choice(normal_available) |
| risk_wallets_set.add(source_wallet) |
| |
| forced_risk_wallets.add(source_wallet) |
| elif abnormal_available: |
| |
| source_wallet = rng.choice(abnormal_available) |
| risk_wallets_set.add(source_wallet) |
| else: |
| |
| if abnormal_available: |
| source_wallet = rng.choice(abnormal_available) |
| risk_wallets_set.add(source_wallet) |
| else: |
| |
| |
| normal_candidates = available_wallets_set - abnormal_wallets - risk_wallets_set - forced_risk_wallets |
| normal_available = [w for w in normal_candidates if wallet_plans[w]['neighbors']] |
| if normal_available and len(risk_wallets_set) < max_risk_wallets_count: |
| source_wallet = rng.choice(normal_available) |
| risk_wallets_set.add(source_wallet) |
| |
| forced_risk_wallets.add(source_wallet) |
| |
| if not source_wallet: |
| |
| if len(risk_wallets_set) >= max_risk_wallets_count: |
| is_risk_tx_decision = False |
| |
| else: |
| continue |
| |
| if source_wallet and is_risk_tx_decision: |
| plan = wallet_plans[source_wallet] |
| |
| |
| wallet_type = plan['wallet_type'] |
| wallet_level = plan['wallet_level'] |
| current_risk_ratio = risk_transactions / total_transactions if total_transactions > 0 else 0 |
| weights = manager.get_wallet_weights(wallet_type, wallet_level, current_risk_ratio) |
| |
| |
| risk_types = [tx for tx in weights.keys() if manager.is_risk_transaction(tx)] |
| if not risk_types: |
| continue |
| |
| risk_weights = [weights[tx] for tx in risk_types] |
| |
| valid_risk_types = [] |
| valid_risk_weights = [] |
| for tx_type, weight in zip(risk_types, risk_weights): |
| if weight is not None and not np.isnan(weight) and not np.isinf(weight) and weight >= 0: |
| valid_risk_types.append(tx_type) |
| valid_risk_weights.append(weight) |
| |
| if not valid_risk_types or sum(valid_risk_weights) == 0: |
| continue |
| |
| |
| total_weight = sum(valid_risk_weights) |
| if total_weight > 0: |
| transaction_weights = [w / total_weight for w in valid_risk_weights] |
| if any(np.isnan(w) or np.isinf(w) for w in transaction_weights): |
| continue |
| selected_transaction_type = rng.choice(valid_risk_types, p=transaction_weights) |
| else: |
| continue |
| else: |
| |
| |
| |
| |
| normal_candidates_set = available_wallets_set - abnormal_wallets - forced_risk_wallets |
| normal_available_all = [w for w in normal_candidates_set if wallet_plans[w]['neighbors']] |
| |
| abnormal_normal_candidates_set = abnormal_wallets & available_wallets_set |
| abnormal_normal_available_all = [w for w in abnormal_normal_candidates_set if wallet_plans[w]['neighbors']] |
| |
| |
| normal_preferred = [w for w in normal_available_all |
| if wallet_tx_type_preference.get(w) in ['normal', None]] |
| normal_non_preferred = [w for w in normal_available_all |
| if wallet_tx_type_preference.get(w) == 'risk'] |
| |
| abnormal_normal_preferred = [w for w in abnormal_normal_available_all |
| if wallet_tx_type_preference.get(w) in ['normal', None]] |
| abnormal_normal_non_preferred = [w for w in abnormal_normal_available_all |
| if wallet_tx_type_preference.get(w) == 'risk'] |
| |
| |
| |
| |
| if normal_preferred and rng.random() < normal_wallet_normal_ratio: |
| |
| source_wallet = rng.choice(normal_preferred) |
| elif abnormal_normal_preferred and rng.random() < abnormal_wallet_normal_ratio: |
| |
| source_wallet = rng.choice(abnormal_normal_preferred) |
| elif normal_preferred: |
| source_wallet = rng.choice(normal_preferred) |
| elif abnormal_normal_preferred: |
| source_wallet = rng.choice(abnormal_normal_preferred) |
| elif current_mixed_count < max_mixed_wallets_count: |
| |
| if normal_non_preferred: |
| source_wallet = rng.choice(normal_non_preferred) |
| elif abnormal_normal_non_preferred: |
| source_wallet = rng.choice(abnormal_normal_non_preferred) |
| elif normal_available_all: |
| source_wallet = rng.choice(normal_available_all) |
| elif abnormal_normal_available_all: |
| source_wallet = rng.choice(abnormal_normal_available_all) |
| |
| if not source_wallet: |
| continue |
| |
| plan = wallet_plans[source_wallet] |
| |
| |
| wallet_type = plan['wallet_type'] |
| if (str(wallet_type) == '1' and |
| plan['next_salary_time'] and |
| current_time >= plan['next_salary_time'] and |
| plan['can_generate_salary']): |
| selected_transaction_type = 'regular_large_low_freq' |
| else: |
| |
| wallet_level = plan['wallet_level'] |
| current_risk_ratio = risk_transactions / total_transactions if total_transactions > 0 else 0 |
| weights = manager.get_wallet_weights(wallet_type, wallet_level, current_risk_ratio) |
| |
| |
| normal_types = [tx for tx in weights.keys() if not manager.is_risk_transaction(tx)] |
| |
| |
| |
| if str(wallet_type) != '1': |
| normal_types = [tx for tx in normal_types if tx != 'regular_large_low_freq'] |
| |
| |
| if 'regular_large_low_freq' in weights and not plan.get('next_salary_time'): |
| original_weight = weights.get('regular_large_low_freq', 0) |
| if original_weight > 0 and not np.isnan(original_weight) and not np.isinf(original_weight): |
| weights['regular_large_low_freq'] = original_weight * 1.2 |
| |
| if not normal_types: |
| continue |
| |
| normal_weights = [weights[tx] for tx in normal_types] |
| |
| valid_normal_types = [] |
| valid_normal_weights = [] |
| for tx_type, weight in zip(normal_types, normal_weights): |
| if weight is not None and not np.isnan(weight) and not np.isinf(weight) and weight >= 0: |
| valid_normal_types.append(tx_type) |
| valid_normal_weights.append(weight) |
| |
| if not valid_normal_types or sum(valid_normal_weights) == 0: |
| continue |
| |
| |
| total_weight = sum(valid_normal_weights) |
| if total_weight > 0: |
| transaction_weights = [w / total_weight for w in valid_normal_weights] |
| if any(np.isnan(w) or np.isinf(w) for w in transaction_weights): |
| continue |
| selected_transaction_type = rng.choice(valid_normal_types, p=transaction_weights) |
| else: |
| continue |
| |
| |
| if not is_continued_motif_processed: |
| |
| if not source_wallet: |
| continue |
| |
| if source_wallet in abandoned_wallets: |
| continue |
| plan = wallet_plans[source_wallet] |
| limits = plan['cached_limits'] |
| daily_limit = limits.get('daily_limit') |
| single_limit = limits.get('single_transaction_limit') |
| |
| |
| current_daily_amount = plan['current_daily_amount'] |
| |
| |
| if daily_limit is not None and current_daily_amount >= daily_limit: |
| plan['daily_limit_reached'] = True |
| continue |
| |
| |
| if not plan['neighbors']: |
| continue |
|
|
| |
| |
| if manager.is_risk_transaction(selected_transaction_type): |
| if plan['risk_tx_count'] >= manager.get_max_risk_transactions_per_wallet(): |
| continue |
| else: |
| |
| if not source_wallet or not plan: |
| continue |
| |
| if selected_transaction_type == 'regular_large_low_freq': |
| |
| if str(plan.get('wallet_type')) != '1': |
| |
| continue |
| |
| |
| generator._reservation_mode = True |
| |
| |
| result = generator.generate_transaction( |
| selected_transaction_type, g, source_wallet, current_balances, |
| current_time, tx_id, max_frac_per_tx, min_abs_amount, rng, |
| wallet_to_attrs, attr_headers, None, wallet_tx_type_preference |
| ) |
| |
| |
| generator._reservation_mode = False |
| |
| if result is None: |
| |
| if source_wallet and plan: |
| wallet_type = plan['wallet_type'] |
| wallet_level = plan['wallet_level'] |
| current_risk_ratio = risk_transactions / total_transactions if total_transactions > 0 else 0 |
| weights = manager.get_wallet_weights(wallet_type, wallet_level, current_risk_ratio) |
| |
| |
| normal_types = [tx for tx in weights.keys() |
| if not manager.is_risk_transaction(tx) and tx != 'regular_large_low_freq'] |
| |
| |
| available_types_with_weights = [(tx_type, weights.get(tx_type, 0)) |
| for tx_type in normal_types |
| if weights.get(tx_type, 0) > 0] |
| available_types_with_weights.sort(key=lambda x: x[1], reverse=True) |
| |
| |
| max_retries = min(3, len(available_types_with_weights)) |
| for i in range(max_retries): |
| retry_type, retry_weight = available_types_with_weights[i] |
| retry_result = generator.generate_transaction( |
| retry_type, g, source_wallet, current_balances, |
| current_time, tx_id, max_frac_per_tx, min_abs_amount, rng, |
| wallet_to_attrs, attr_headers, None, wallet_tx_type_preference |
| ) |
| if retry_result is not None: |
| result = retry_result |
| selected_transaction_type = retry_type |
| |
| break |
| |
| |
| if result is None: |
| continue |
| |
| new_transactions, tx_id, current_time = result |
| |
| |
| plan['reservation_transactions'].extend(new_transactions) |
| |
| |
| if new_transactions: |
| first_tx = new_transactions[0] |
| salary_interval_days = first_tx.get('reservation_data', {}).get('salary_interval_days') |
| if salary_interval_days: |
| plan['last_salary_time'] = current_time |
| plan['next_salary_time'] = current_time + timedelta(days=int(salary_interval_days)) |
| plan['salary_interval_days'] = salary_interval_days |
| plan['base_salary'] = first_tx.get('reservation_data', {}).get('base_salary') |
| plan['can_generate_salary'] = False |
| |
| continue |
| |
| |
| if not new_transactions: |
| result = generator.generate_transaction( |
| selected_transaction_type, g, source_wallet, current_balances, |
| current_time, tx_id, max_frac_per_tx, min_abs_amount, rng, |
| wallet_to_attrs, attr_headers, None, wallet_tx_type_preference |
| ) |
| |
| if result is None: |
| |
| if source_wallet and plan: |
| wallet_type = plan['wallet_type'] |
| wallet_level = plan['wallet_level'] |
| current_risk_ratio = risk_transactions / total_transactions if total_transactions > 0 else 0 |
| weights = manager.get_wallet_weights(wallet_type, wallet_level, current_risk_ratio) |
| |
| |
| is_risk = manager.is_risk_transaction(selected_transaction_type) |
| |
| |
| all_available_types = list(weights.keys()) |
| if selected_transaction_type in all_available_types: |
| all_available_types.remove(selected_transaction_type) |
| |
| |
| if is_risk: |
| |
| retry_types = [tx for tx in all_available_types if manager.is_risk_transaction(tx)] |
| else: |
| |
| retry_types = [tx for tx in all_available_types if not manager.is_risk_transaction(tx)] |
| |
| |
| available_types_with_weights = [(tx_type, weights.get(tx_type, 0)) |
| for tx_type in retry_types |
| if weights.get(tx_type, 0) > 0] |
| available_types_with_weights.sort(key=lambda x: x[1], reverse=True) |
| |
| |
| max_retries = min(3, len(available_types_with_weights)) |
| for i in range(max_retries): |
| retry_type, retry_weight = available_types_with_weights[i] |
| retry_result = generator.generate_transaction( |
| retry_type, g, source_wallet, current_balances, |
| current_time, tx_id, max_frac_per_tx, min_abs_amount, rng, |
| wallet_to_attrs, attr_headers, None, wallet_tx_type_preference |
| ) |
| if retry_result is not None: |
| result = retry_result |
| selected_transaction_type = retry_type |
| break |
| |
| |
| if result is None: |
| continue |
| |
| all_motif_transactions, tx_id, current_time = result |
| |
| |
| if all_motif_transactions: |
| motif_id_gen = all_motif_transactions[0].get("motif_id") if all_motif_transactions else None |
| transaction_mode_gen = all_motif_transactions[0].get("transaction_mode") if all_motif_transactions else None |
| transaction_motif_gen = all_motif_transactions[0].get("risk_type", "unknown") if all_motif_transactions else None |
| amounts_before_fix = [tx.get("amount") for tx in all_motif_transactions] |
| |
| |
| valid_transactions = [] |
| for tx in all_motif_transactions: |
| src = tx.get("src") |
| dst = tx.get("dst") |
| tx_timestamp_str = tx.get("timestamp") |
| |
| if not tx_timestamp_str: |
| continue |
| |
| try: |
| tx_timestamp = datetime.strptime(tx_timestamp_str, "%Y-%m-%d %H:%M:%S") |
| except: |
| continue |
| |
| |
| if src not in wallet_first_tx_time: |
| |
| src_open_time = wallet_open_timestamps.get(src) |
| if src_open_time and tx_timestamp < src_open_time: |
| |
| abandoned_wallets.add(src) |
| continue |
| else: |
| |
| wallet_first_tx_time[src] = tx_timestamp |
| |
| elif src in abandoned_wallets: |
| continue |
| |
| |
| if dst and dst not in wallet_first_tx_time: |
| |
| dst_open_time = wallet_open_timestamps.get(dst) |
| if dst_open_time and tx_timestamp < dst_open_time: |
| |
| abandoned_wallets.add(dst) |
| continue |
| else: |
| |
| wallet_first_tx_time[dst] = tx_timestamp |
| |
| elif dst and dst in abandoned_wallets: |
| continue |
| |
| |
| valid_transactions.append(tx) |
| |
| all_motif_transactions = valid_transactions |
| |
| |
| if all_motif_transactions and selected_transaction_type == 'merchant_laundering': |
| all_motif_transactions = fix_merchant_laundering_many_to_many( |
| all_motif_transactions, source_wallet, current_time, rng, wallet_open_timestamps |
| ) |
| |
| |
| if all_motif_transactions and selected_transaction_type != 'merchant_laundering': |
| motif_id_before = all_motif_transactions[0].get("motif_id") if all_motif_transactions else None |
| transaction_count_before = len(all_motif_transactions) |
| amounts_before = [tx.get("amount") for tx in all_motif_transactions] |
| all_motif_transactions = fix_transaction_balance( |
| all_motif_transactions, source_wallet, current_time, rng, wallet_open_timestamps |
| ) |
| motif_id_after = all_motif_transactions[0].get("motif_id") if all_motif_transactions else None |
| transaction_count_after = len(all_motif_transactions) |
| amounts_after = [tx.get("amount") for tx in all_motif_transactions] |
| |
| |
| if all_motif_transactions: |
| valid_transactions_after_fix = [] |
| for tx in all_motif_transactions: |
| src = tx.get("src") |
| dst = tx.get("dst") |
| tx_timestamp_str = tx.get("timestamp") |
| |
| if not tx_timestamp_str: |
| continue |
| |
| try: |
| tx_timestamp = datetime.strptime(tx_timestamp_str, "%Y-%m-%d %H:%M:%S") |
| except: |
| continue |
| |
| |
| if src in abandoned_wallets: |
| continue |
| |
| if src not in wallet_first_tx_time: |
| |
| src_open_time = wallet_open_timestamps.get(src) |
| if src_open_time and tx_timestamp < src_open_time: |
| |
| abandoned_wallets.add(src) |
| continue |
| else: |
| |
| wallet_first_tx_time[src] = tx_timestamp |
| elif tx_timestamp < wallet_first_tx_time[src]: |
| |
| |
| src_open_time = wallet_open_timestamps.get(src) |
| if src_open_time and tx_timestamp < src_open_time: |
| |
| abandoned_wallets.add(src) |
| continue |
| else: |
| wallet_first_tx_time[src] = tx_timestamp |
| |
| |
| if dst: |
| if dst in abandoned_wallets: |
| continue |
| |
| if dst not in wallet_first_tx_time: |
| |
| dst_open_time = wallet_open_timestamps.get(dst) |
| if dst_open_time and tx_timestamp < dst_open_time: |
| |
| abandoned_wallets.add(dst) |
| continue |
| else: |
| |
| wallet_first_tx_time[dst] = tx_timestamp |
| elif tx_timestamp < wallet_first_tx_time[dst]: |
| |
| |
| dst_open_time = wallet_open_timestamps.get(dst) |
| if dst_open_time and tx_timestamp < dst_open_time: |
| |
| abandoned_wallets.add(dst) |
| continue |
| else: |
| wallet_first_tx_time[dst] = tx_timestamp |
| |
| |
| valid_transactions_after_fix.append(tx) |
| |
| all_motif_transactions = valid_transactions_after_fix |
| |
| if all_motif_transactions: |
| |
| first_tx = all_motif_transactions[0].copy() |
| motif_id_first = first_tx.get("motif_id") |
| |
| if selected_transaction_type == 'merchant_laundering': |
| pass |
| |
| elif first_tx.get("transaction_mode") in ["many_to_many", "many_to_one", "one_to_many"]: |
| pass |
| else: |
| first_tx['timestamp'] = current_time.strftime("%Y-%m-%d %H:%M:%S") |
| new_transactions = [first_tx] |
| |
| |
| if len(all_motif_transactions) > 1: |
| motif_id = first_tx.get("motif_id") |
| if motif_id: |
| remaining_txs = [tx.copy() for tx in all_motif_transactions[1:]] |
| remaining_amounts = [tx.get("amount") for tx in remaining_txs] |
| remaining_details = [(tx.get("tx_id"), tx.get("src"), tx.get("dst"), tx.get("amount"), tx.get("timestamp")) for tx in remaining_txs] |
| pending_motifs[motif_id] = { |
| 'transactions': remaining_txs, |
| 'current_index': 0, |
| 'transaction_type': selected_transaction_type, |
| 'source_wallet': source_wallet, |
| 'plan': plan |
| } |
| |
| |
| first_tx_mode = first_tx.get("transaction_mode") |
| if first_tx_mode in ["many_to_many", "many_to_one", "one_to_many"] and selected_transaction_type != 'merchant_laundering': |
| |
| if first_tx_mode == "one_to_many": |
| main_wallet = source_wallet |
| else: |
| |
| dst_counts = {} |
| for temp_tx in all_motif_transactions: |
| temp_dst = temp_tx.get("dst") |
| if temp_dst: |
| dst_counts[temp_dst] = dst_counts.get(temp_dst, 0) + 1 |
| main_wallet = max(dst_counts, key=dst_counts.get) if dst_counts else source_wallet |
| |
| motif_saved_amounts[motif_id] = { |
| 'main_wallet': main_wallet, |
| 'saved_incoming': 0.0, |
| 'saved_outgoing': 0.0 |
| } |
| |
| |
| |
| |
| if new_transactions and not is_continued_motif_processed: |
| |
| motif_id = new_transactions[0].get("motif_id") if new_transactions else None |
| |
| |
| |
| all_transactions_valid = True |
| wallets_exceeded_limit = set() |
| current_date = current_time.date() |
| |
| |
| if new_transactions: |
| tx = new_transactions[0] |
| src = tx['src'] |
| dst = tx.get('dst') |
| amount = float(tx['amount']) |
| |
| |
| if src in abandoned_wallets or (dst and dst in abandoned_wallets): |
| all_transactions_valid = False |
| if motif_id and motif_id in pending_motifs: |
| del pending_motifs[motif_id] |
| new_transactions = [] |
| elif src in wallet_plans: |
| plan_wallet = wallet_plans[src] |
| limits = plan_wallet['cached_limits'] |
| single_limit = limits.get('single_transaction_limit') |
| daily_limit = limits.get('daily_limit') |
| current_daily_amount = plan_wallet['current_daily_amount'] |
| |
| |
| if single_limit is not None and amount > single_limit: |
| all_transactions_valid = False |
| wallets_exceeded_limit.add(src) |
| plan_wallet['daily_limit_reached'] = True |
| |
| elif daily_limit is not None and (current_daily_amount + amount) > daily_limit: |
| all_transactions_valid = False |
| wallets_exceeded_limit.add(src) |
| plan_wallet['daily_limit_reached'] = True |
| |
| elif current_balances.get(src, 0) < amount: |
| all_transactions_valid = False |
| |
| |
| if all_transactions_valid: |
| current_balances[src] -= amount |
| current_balances[tx['dst']] = current_balances.get(tx['dst'], 0) + amount |
| plan_wallet['current_daily_amount'] += amount |
| else: |
| all_transactions_valid = False |
| |
| |
| if not all_transactions_valid: |
| if motif_id and motif_id in pending_motifs: |
| del pending_motifs[motif_id] |
| new_transactions = [] |
| if source_wallet and source_wallet in wallets_exceeded_limit: |
| plan['daily_limit_reached'] = True |
| |
| |
| if not new_transactions: |
| continue |
| |
| if new_transactions: |
| |
| |
| if manager.is_risk_transaction(selected_transaction_type): |
| |
| motif_id = new_transactions[0].get("motif_id") if new_transactions else None |
| if motif_id: |
| |
| |
| |
| if motif_id not in motif_stats_cache: |
| existing_risk_count = sum(1 for tx in transactions |
| if tx.get("motif_id") == motif_id |
| and manager.is_risk_transaction(tx.get("risk_type", "unknown"))) |
| existing_normal_count = sum(1 for tx in transactions |
| if tx.get("motif_id") == motif_id |
| and not manager.is_risk_transaction(tx.get("risk_type", "unknown"))) |
| motif_stats_cache[motif_id] = (existing_risk_count, existing_normal_count) |
| else: |
| existing_risk_count, existing_normal_count = motif_stats_cache[motif_id] |
| |
| if manager.is_risk_transaction(selected_transaction_type): |
| existing_risk_count += len(new_transactions) |
| else: |
| existing_normal_count += len(new_transactions) |
| motif_stats_cache[motif_id] = (existing_risk_count, existing_normal_count) |
| |
| |
| |
| if existing_normal_count >= existing_risk_count: |
| |
| pass |
| |
| transactions.extend(new_transactions) |
| total_transactions += len(new_transactions) |
| |
| |
| if csv_writer and new_transactions: |
| for tx in new_transactions: |
| motif_id_save = tx.get("motif_id") |
| tx_id_save = tx.get("tx_id") |
| tx_amount_save = tx.get("amount") |
| tx_timestamp_save = tx.get("timestamp") |
| tx_mode_save = tx.get("transaction_mode") |
| |
| transaction_motif = tx.get("risk_type", "unknown") |
| is_risk = '0' if transaction_motif in safe_motifs else '1' |
| |
| src_id = tx["src"] |
| dst_id = tx["dst"] |
| |
| if src_id not in wallet_info_cache: |
| wallet_info_cache[src_id] = get_wallet_info(src_id, wallet_to_attrs, attr_headers) |
| if dst_id not in wallet_info_cache: |
| wallet_info_cache[dst_id] = get_wallet_info(dst_id, wallet_to_attrs, attr_headers) |
| |
| src_info = wallet_info_cache[src_id] |
| dst_info = wallet_info_cache[dst_id] |
| |
| transaction_buffer.append([ |
| tx["tx_id"], tx["timestamp"], tx["src"], tx["dst"], tx["amount"], |
| transaction_motif, tx["motif_id"], tx.get("transaction_mode", ""), is_risk, |
| src_info['bank_account_number'], dst_info['bank_account_number'], |
| src_info['wallet_level'], dst_info['wallet_level'] |
| ]) |
| |
| |
| motif_id_for_tracking = tx.get("motif_id") |
| transaction_mode_for_tracking = tx.get("transaction_mode") |
| if motif_id_for_tracking and transaction_mode_for_tracking in ["many_to_many", "many_to_one", "one_to_many"]: |
| if motif_id_for_tracking in motif_saved_amounts: |
| main_wallet_tracking = motif_saved_amounts[motif_id_for_tracking].get('main_wallet') |
| if main_wallet_tracking: |
| if tx.get("dst") == main_wallet_tracking: |
| |
| motif_saved_amounts[motif_id_for_tracking]['saved_incoming'] += float(tx.get("amount", 0)) |
| elif tx.get("src") == main_wallet_tracking: |
| |
| motif_saved_amounts[motif_id_for_tracking]['saved_outgoing'] += float(tx.get("amount", 0)) |
| |
| |
| if len(transaction_buffer) >= buffer_size: |
| csv_writer.writerows(transaction_buffer) |
| csv_file.flush() |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已批量写入 {len(transaction_buffer):,} 笔交易到CSV文件 (累计: {total_transactions:,} 笔, 风险: {risk_transactions:,}, 正常: {normal_transactions:,}) {get_process_info()}") |
| transaction_buffer = [] |
| |
| |
| is_risk_tx = manager.is_risk_transaction(selected_transaction_type) |
| |
| |
| wallets_in_tx = set() |
| for tx in new_transactions: |
| wallets_in_tx.add(str(tx.get("src", ""))) |
| wallets_in_tx.add(str(tx.get("dst", ""))) |
| |
| if manager.is_risk_transaction(tx.get("risk_type", "unknown")): |
| risk_transactions += 1 |
| plan['risk_tx_count'] += 1 |
| else: |
| normal_transactions += 1 |
| |
| |
| for wallet_id in wallets_in_tx: |
| if not wallet_id or wallet_id not in g.nodes(): |
| continue |
| |
| |
| if wallet_id in forced_risk_wallets: |
| wallet_tx_type_preference[wallet_id] = 'risk' |
| continue |
| |
| if wallet_id not in wallet_tx_type_preference: |
| |
| wallet_tx_type_preference[wallet_id] = 'risk' if is_risk_tx else 'normal' |
| else: |
| |
| current_pref = wallet_tx_type_preference[wallet_id] |
| if current_pref == 'risk' and not is_risk_tx: |
| |
| |
| if current_mixed_count < max_mixed_wallets_count: |
| wallet_tx_type_preference[wallet_id] = 'mixed' |
| current_mixed_count += 1 |
| |
| elif current_pref == 'normal' and is_risk_tx: |
| |
| |
| if current_mixed_count < max_mixed_wallets_count: |
| wallet_tx_type_preference[wallet_id] = 'mixed' |
| current_mixed_count += 1 |
| |
| |
| |
| plan['last_tx_time'] = current_time |
| plan['tx_count'] += len(new_transactions) |
| |
| |
| if plan['reservation_transactions']: |
| |
| plan['reservation_transactions'].sort(key=lambda x: x['timestamp']) |
| |
| |
| current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S") |
| expired_reservations = [] |
| |
| for i, tx in enumerate(plan['reservation_transactions']): |
| if tx['timestamp'] <= current_time_str: |
| expired_reservations.append(i) |
| |
| if expired_reservations: |
| |
| expired_txs = [plan['reservation_transactions'][i] for i in expired_reservations] |
| processed_transactions = process_reservation_transactions( |
| expired_txs, current_balances, rng, manager |
| ) |
| |
| if processed_transactions: |
| transactions.extend(processed_transactions) |
| total_transactions += len(processed_transactions) |
| |
| |
| if csv_writer and processed_transactions: |
| for tx in processed_transactions: |
| transaction_motif = tx.get("risk_type", "unknown") |
| is_risk = '0' if transaction_motif in safe_motifs else '1' |
| |
| src_id = tx["src"] |
| dst_id = tx["dst"] |
| |
| if src_id not in wallet_info_cache: |
| wallet_info_cache[src_id] = get_wallet_info(src_id, wallet_to_attrs, attr_headers) |
| if dst_id not in wallet_info_cache: |
| wallet_info_cache[dst_id] = get_wallet_info(dst_id, wallet_to_attrs, attr_headers) |
| |
| src_info = wallet_info_cache[src_id] |
| dst_info = wallet_info_cache[dst_id] |
| |
| transaction_buffer.append([ |
| tx["tx_id"], tx["timestamp"], tx["src"], tx["dst"], tx["amount"], |
| transaction_motif, tx["motif_id"], tx.get("transaction_mode", ""), is_risk, |
| src_info['bank_account_number'], dst_info['bank_account_number'], |
| src_info['wallet_level'], dst_info['wallet_level'] |
| ]) |
| |
| |
| if len(transaction_buffer) >= buffer_size: |
| csv_writer.writerows(transaction_buffer) |
| csv_file.flush() |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已批量写入 {len(transaction_buffer):,} 笔交易到CSV文件 (累计: {total_transactions:,} 笔, 风险: {risk_transactions:,}, 正常: {normal_transactions:,}) {get_process_info()}") |
| transaction_buffer = [] |
| |
| |
| for i in sorted(expired_reservations, reverse=True): |
| del plan['reservation_transactions'][i] |
| |
| |
| if csv_writer and transaction_buffer: |
| csv_writer.writerows(transaction_buffer) |
| csv_file.flush() |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已批量写入剩余 {len(transaction_buffer):,} 笔交易到CSV文件 (累计: {total_transactions:,} 笔) {get_process_info()}") |
| transaction_buffer = [] |
| |
| |
| if csv_file: |
| csv_file.close() |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] CSV文件已关闭: {output_file} {get_process_info()}") |
| |
| |
| |
| generation_elapsed = time.time() - generation_start_time |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 交易生成完成, 耗时 {generation_elapsed:.2f} 秒 ({generation_elapsed/60:.2f} 分钟) {get_process_info()}") |
| print(f"\n=== 交易生成统计 ===") |
| print(f"总交易数: {total_transactions}") |
| print(f"正常交易数: {normal_transactions}") |
| print(f"风险交易数: {risk_transactions}") |
| |
| if total_transactions > 0: |
| actual_risk_ratio = risk_transactions / total_transactions |
| print(f"实际风险交易比例: {actual_risk_ratio:.1%}") |
| print(f"目标风险交易比例: {manager.get_risk_ratio():.1%}") |
| |
| |
| print(f"\n=== 异常账户参与情况统计 ===") |
| risk_txs_with_abnormal = 0 |
| risk_txs_with_normal = 0 |
| for tx in transactions: |
| if manager.is_risk_transaction(tx.get("risk_type", "unknown")): |
| src = tx.get("src", "") |
| if src in abnormal_wallets: |
| risk_txs_with_abnormal += 1 |
| else: |
| risk_txs_with_normal += 1 |
| |
| if risk_transactions > 0: |
| abnormal_participation_ratio = risk_txs_with_abnormal / risk_transactions |
| print(f"风险交易总数: {risk_transactions}") |
| print(f"异常账户参与的风险交易: {risk_txs_with_abnormal} ({abnormal_participation_ratio:.1%})") |
| print(f"正常账户参与的风险交易: {risk_txs_with_normal} ({1-abnormal_participation_ratio:.1%})") |
| |
| |
| abnormal_total_txs = sum(1 for tx in transactions if tx.get("src", "") in abnormal_wallets) |
| if abnormal_total_txs > 0: |
| abnormal_risk_in_abnormal = sum(1 for tx in transactions |
| if tx.get("src", "") in abnormal_wallets and |
| manager.is_risk_transaction(tx.get("risk_type", "unknown"))) |
| print(f"\n异常账户总交易数: {abnormal_total_txs}") |
| print(f"异常账户风险交易数: {abnormal_risk_in_abnormal} ({abnormal_risk_in_abnormal/abnormal_total_txs:.1%})") |
| |
| |
| risk_wallets_abnormal = len([w for w in risk_wallets_set if w in abnormal_wallets]) |
| risk_wallets_normal = len([w for w in risk_wallets_set if w not in abnormal_wallets]) |
| print(f"\n=== 参与风险交易的钱包统计 ===") |
| print(f"总参与风险交易的钱包数: {len(risk_wallets_set):,} (限制: {max_risk_wallets_count:,})") |
| print(f" - 异常账户(is_abnormal=1): {risk_wallets_abnormal:,} 个 ({risk_wallets_abnormal/len(risk_wallets_set)*100:.1f}%)") |
| print(f" - 正常账户(is_abnormal=0): {risk_wallets_normal:,} 个 ({risk_wallets_normal/len(risk_wallets_set)*100:.1f}%)") |
| print(f"异常账户参与率: {risk_wallets_abnormal/len(abnormal_wallets)*100:.1f}% ({risk_wallets_abnormal}/{len(abnormal_wallets)})") |
| if len(risk_wallets_set) > 0: |
| print(f"参与风险交易的钱包占比: {len(risk_wallets_set)/len(g.nodes())*100:.2f}% ({len(risk_wallets_set)}/{len(g.nodes())})") |
| |
| |
| print(f"\n=== forced_risk_wallets 统计 ===") |
| print(f"forced_risk_wallets数量: {len(forced_risk_wallets):,}") |
| print(f" - 这些钱包原本是is_abnormal=0,但被选中参与异常交易后,只能参与异常交易") |
| print(f" - 这些钱包已被排除在正常交易选择之外") |
| |
| |
| mixed_wallets_count = len([w for w in wallet_tx_type_preference.values() if w == 'mixed']) |
| print(f"\n=== 混合钱包统计 ===") |
| print(f"混合钱包数量: {mixed_wallets_count:,} (限制: {max_mixed_wallets_count:,}, {max_mixed_wallets_ratio*100:.1f}%)") |
| print(f" - 这些钱包既参与异常交易又参与正常交易") |
| if len(wallet_tx_type_preference) > 0: |
| risk_only_count = len([w for w in wallet_tx_type_preference.values() if w == 'risk']) |
| normal_only_count = len([w for w in wallet_tx_type_preference.values() if w == 'normal']) |
| print(f"只参与异常交易的钱包: {risk_only_count:,}") |
| print(f"只参与正常交易的钱包: {normal_only_count:,}") |
| |
| |
| print(f"\n=== 各类型交易统计 ===") |
| type_counts = {} |
| for tx in transactions: |
| transaction_type = tx.get("risk_type", "unknown") |
| type_counts[transaction_type] = type_counts.get(transaction_type, 0) + 1 |
| |
| for transaction_type, count in type_counts.items(): |
| percentage = (count / total_transactions * 100) if total_transactions > 0 else 0 |
| print(f"{transaction_type}: {count}笔 ({percentage:.1f}%)") |
| |
| |
| print(f"\n=== 各交易模式统计 ===") |
| mode_counts = {} |
| for tx in transactions: |
| transaction_mode = tx.get("transaction_mode", "unknown") |
| mode_counts[transaction_mode] = mode_counts.get(transaction_mode, 0) + 1 |
| |
| for transaction_mode, count in mode_counts.items(): |
| percentage = (count / total_transactions * 100) if total_transactions > 0 else 0 |
| print(f"{transaction_mode}: {count}笔 ({percentage:.1f}%)") |
| |
| |
| print(f"\n=== 风险类型+交易模式组合统计 ===") |
| risk_mode_counts = {} |
| for tx in transactions: |
| risk_type = tx.get("risk_type", "unknown") |
| transaction_mode = tx.get("transaction_mode", "unknown") |
| key = f"{risk_type}_{transaction_mode}" |
| risk_mode_counts[key] = risk_mode_counts.get(key, 0) + 1 |
| |
| for key, count in risk_mode_counts.items(): |
| percentage = (count / total_transactions * 100) if total_transactions > 0 else 0 |
| print(f"{key}: {count}笔 ({percentage:.1f}%)") |
| |
| |
| print(f"\n=== 按motif_id为单位的异常/正常占比统计 ===") |
| motif_classification = {} |
| |
| for tx in transactions: |
| motif_id = tx.get("motif_id", "unknown") |
| is_risk_tx = manager.is_risk_transaction(tx.get("risk_type", "unknown")) |
| |
| if motif_id not in motif_classification: |
| |
| motif_classification[motif_id] = 'risk' if is_risk_tx else 'normal' |
| else: |
| |
| |
| if is_risk_tx and motif_classification[motif_id] == 'normal': |
| motif_classification[motif_id] = 'risk' |
| |
| |
| total_motifs = len(motif_classification) |
| risk_motifs = sum(1 for classification in motif_classification.values() if classification == 'risk') |
| normal_motifs = total_motifs - risk_motifs |
| |
| print(f"总motif数: {total_motifs}") |
| print(f"异常motif数: {risk_motifs} ({risk_motifs/total_motifs*100:.1f}%)") |
| print(f"正常motif数: {normal_motifs} ({normal_motifs/total_motifs*100:.1f}%)") |
| |
| |
| print(f"\n前10个motif的详细统计:") |
| sorted_motifs = sorted(motif_classification.items(), key=lambda x: x[0])[:10] |
| for motif_id, classification in sorted_motifs: |
| |
| motif_tx_count = sum(1 for tx in transactions if tx.get("motif_id") == motif_id) |
| motif_tx_types = set(tx.get("risk_type", "unknown") for tx in transactions if tx.get("motif_id") == motif_id) |
| print(f" motif_id={motif_id}: {classification} motif, {motif_tx_count}笔交易, 类型={', '.join(list(motif_tx_types)[:3])}") |
| |
| return transactions |
|
|
| def process_reservation_transactions(transactions: List[Dict], current_balances: Dict[str, float], |
| rng, manager) -> List[Dict]: |
| """处理预留交易,填充金额信息""" |
| processed_transactions = [] |
| |
| for tx in transactions: |
| if tx.get("is_reservation", False): |
| |
| reservation_data = tx.get("reservation_data", {}) |
| base_salary = reservation_data.get("base_salary", 50) |
| amount_range = reservation_data.get("amount_range", {"min": 10, "max": 100}) |
| min_abs_amount = reservation_data.get("min_abs_amount", 0.01) |
| salary_variation = reservation_data.get("salary_variation", 0.1) |
| |
| |
| variation = rng.uniform(1 - salary_variation, 1 + salary_variation) |
| salary_amount = base_salary * variation |
| salary_amount = max(salary_amount, min_abs_amount) |
| |
| |
| if current_balances[tx["src"]] >= salary_amount: |
| current_balances[tx["src"]] -= salary_amount |
| current_balances[tx["dst"]] += salary_amount |
| |
| |
| tx["amount"] = round(salary_amount, 2) |
| del tx["is_reservation"] |
| del tx["reservation_data"] |
| processed_transactions.append(tx) |
| else: |
| |
| |
| continue |
| else: |
| |
| processed_transactions.append(tx) |
| |
| return processed_transactions |
|
|
| def get_wallet_info(wallet_id: str, wallet_to_attrs: Dict[str, List[str]], attr_headers: List[str]) -> Dict[str, str]: |
| """获取钱包的银行账户号和等级信息""" |
| wallet_attrs = wallet_to_attrs.get(wallet_id, []) |
| |
| |
| wallet_info = { |
| 'bank_account_number': '', |
| 'wallet_level': '' |
| } |
| |
| |
| if not wallet_attrs: |
| return wallet_info |
| |
| |
| if len(wallet_attrs) < 13: |
| return wallet_info |
| |
| |
| bank_account_value = wallet_attrs[9] if len(wallet_attrs) > 9 else '' |
| wallet_info['bank_account_number'] = bank_account_value if bank_account_value else '' |
| |
| |
| wallet_level_value = wallet_attrs[1] if len(wallet_attrs) > 1 else '' |
| wallet_info['wallet_level'] = wallet_level_value if wallet_level_value else '' |
| |
| return wallet_info |
|
|
| def generate_random_mac() -> str: |
| """生成随机MAC地址""" |
| return ":".join(f"{np.random.randint(0, 256):02X}" for _ in range(6)) |
|
|
| def generate_random_ip() -> str: |
| """生成随机IP地址""" |
| return f"{np.random.randint(1, 255)}.{np.random.randint(1, 255)}.{np.random.randint(1, 255)}.{np.random.randint(1, 254)}" |
|
|
| def build_account_device_ip_map(accounts_df: pd.DataFrame) -> dict: |
| """从账户数据构建设备/IP映射""" |
| mapping = {} |
| for _, row in accounts_df.iterrows(): |
| mapping[row["wallet_id"]] = { |
| "device": row.get("open_device", None), |
| "ip": row.get("open_ip", None), |
| } |
| return mapping |
|
|
| def add_device_ip_columns(transactions_df: pd.DataFrame, account_map: dict) -> pd.DataFrame: |
| """为交易数据添加设备/IP列(优化:使用向量化操作)""" |
| print(f" 开始添加设备/IP列,共 {len(transactions_df):,} 行...") |
| step_start = time.time() |
| |
| |
| if "src_device" not in transactions_df.columns: |
| transactions_df["src_device"] = None |
| if "src_ip" not in transactions_df.columns: |
| transactions_df["src_ip"] = None |
| if "dst_device" not in transactions_df.columns: |
| transactions_df["dst_device"] = None |
| if "dst_ip" not in transactions_df.columns: |
| transactions_df["dst_ip"] = None |
|
|
| |
| |
| device_map = {k: v.get("device") for k, v in account_map.items() if v.get("device") and not pd.isna(v.get("device"))} |
| ip_map = {k: v.get("ip") for k, v in account_map.items() if v.get("ip") and not pd.isna(v.get("ip"))} |
| |
| |
| transactions_df["src_device"] = transactions_df["src"].map(device_map) |
| transactions_df["src_ip"] = transactions_df["src"].map(ip_map) |
| transactions_df["dst_device"] = transactions_df["dst"].map(device_map) |
| transactions_df["dst_ip"] = transactions_df["dst"].map(ip_map) |
| |
| |
| missing_src_device_mask = transactions_df["src_device"].isna() |
| missing_src_ip_mask = transactions_df["src_ip"].isna() |
| missing_dst_device_mask = transactions_df["dst_device"].isna() |
| missing_dst_ip_mask = transactions_df["dst_ip"].isna() |
| |
| missing_src_device_count = missing_src_device_mask.sum() |
| missing_src_ip_count = missing_src_ip_mask.sum() |
| missing_dst_device_count = missing_dst_device_mask.sum() |
| missing_dst_ip_count = missing_dst_ip_mask.sum() |
| |
| if missing_src_device_count > 0: |
| transactions_df.loc[missing_src_device_mask, "src_device"] = [ |
| generate_random_mac() for _ in range(missing_src_device_count) |
| ] |
| if missing_src_ip_count > 0: |
| transactions_df.loc[missing_src_ip_mask, "src_ip"] = [ |
| generate_random_ip() for _ in range(missing_src_ip_count) |
| ] |
| if missing_dst_device_count > 0: |
| transactions_df.loc[missing_dst_device_mask, "dst_device"] = [ |
| generate_random_mac() for _ in range(missing_dst_device_count) |
| ] |
| if missing_dst_ip_count > 0: |
| transactions_df.loc[missing_dst_ip_mask, "dst_ip"] = [ |
| generate_random_ip() for _ in range(missing_dst_ip_count) |
| ] |
| |
| step_elapsed = time.time() - step_start |
| print(f" 设备/IP列添加完成,耗时 {step_elapsed:.2f} 秒") |
|
|
| return transactions_df |
|
|
| def apply_victim_pattern(transactions_df: pd.DataFrame) -> pd.DataFrame: |
| """应用受害者模式:在异常交易中随机选择上游账户作为受害者,新增 is_src_victim 列""" |
| import numpy as np |
| |
| |
| if "is_src_victim" not in transactions_df.columns: |
| transactions_df["is_src_victim"] = 0 |
| |
| |
| if transactions_df["is_risk"].dtype == 'object': |
| transactions_df["is_risk"] = transactions_df["is_risk"].astype(str).str.strip() |
| risk_df = transactions_df[(transactions_df["is_risk"] == '1') | (transactions_df["is_risk"] == 1)] |
| else: |
| risk_df = transactions_df[transactions_df["is_risk"] == 1] |
| print(f"Total risk transactions: {len(risk_df)}") |
| |
| |
| risk_df = risk_df[risk_df["transaction_motif"] != "merchant_laundering"] |
| print(f"Risk transactions after excluding merchant_laundering: {len(risk_df)}") |
| |
| |
| supported_modes = ['fan_out', 'one_to_many', 'many_to_many', 'many_to_one'] |
| risk_df = risk_df[risk_df['transaction_mode'].isin(supported_modes)] |
| print(f"Risk transactions with supported modes ({supported_modes}): {len(risk_df)}") |
| |
| |
| MIN_AMOUNT = 100 |
| large_risk = risk_df[risk_df["amount"] >= MIN_AMOUNT] |
| print(f"Risk transactions with amount >= {MIN_AMOUNT}: {len(large_risk)}") |
| |
| if len(large_risk) < 10: |
| print(f"Not enough large-amount risk transactions, using all risk transactions") |
| large_risk = risk_df |
| |
| |
| selected_txs = [] |
| selected_accounts_per_motif = {} |
| |
| |
| np.random.seed(1243) |
| |
| for motif_id in large_risk['motif_id'].unique(): |
| motif_txs = large_risk[large_risk['motif_id'] == motif_id] |
| |
| if len(motif_txs) == 0: |
| continue |
| |
| |
| transaction_mode = motif_txs['transaction_mode'].iloc[0] if len(motif_txs) > 0 else None |
| |
| if transaction_mode == 'many_to_many': |
| |
| |
| dst_counts = motif_txs['dst'].value_counts() |
| if len(dst_counts) > 0: |
| main_wallet = dst_counts.index[0] |
| |
| |
| incoming_txs = motif_txs[motif_txs['dst'] == main_wallet] |
| upstream_accounts = incoming_txs['src'].unique() |
| |
| |
| upstream_accounts = [acc for acc in upstream_accounts if acc != main_wallet] |
| else: |
| upstream_accounts = [] |
| else: |
| |
| upstream_accounts = motif_txs['src'].unique() |
| dst_counts = None |
| |
| if len(upstream_accounts) > 0: |
| |
| num_victims = min(2, len(upstream_accounts)) |
| if len(upstream_accounts) > 5: |
| num_victims = min(3, len(upstream_accounts)) |
| |
| selected_accounts = np.random.choice(upstream_accounts, size=num_victims, replace=False) |
| |
| |
| |
| if transaction_mode == 'many_to_many' and dst_counts is not None and len(dst_counts) > 0: |
| main_wallet = dst_counts.index[0] |
| incoming_txs = motif_txs[motif_txs['dst'] == main_wallet] |
| for account in selected_accounts: |
| account_txs = incoming_txs[incoming_txs['src'] == account] |
| if len(account_txs) > 0: |
| best_tx = account_txs.sort_values('amount', ascending=False).iloc[0] |
| selected_txs.append(best_tx.name) |
| else: |
| for account in selected_accounts: |
| account_txs = motif_txs[motif_txs['src'] == account] |
| if len(account_txs) > 0: |
| best_tx = account_txs.sort_values('amount', ascending=False).iloc[0] |
| selected_txs.append(best_tx.name) |
| |
| if len(selected_accounts) > 0: |
| selected_accounts_per_motif[motif_id] = selected_accounts.tolist() |
| |
| print(f"Found {len(selected_txs)} upstream victim transactions from {len(selected_accounts_per_motif)} unique motifs") |
| |
| |
| target_count = 50 |
| if len(selected_txs) < target_count: |
| processed_motifs = set(selected_accounts_per_motif.keys()) |
| remaining_motif_ids = [mid for mid in large_risk['motif_id'].unique() if mid not in processed_motifs] |
| np.random.shuffle(remaining_motif_ids) |
| |
| for motif_id in remaining_motif_ids: |
| if len(selected_txs) >= target_count: |
| break |
| |
| motif_txs = large_risk[large_risk['motif_id'] == motif_id] |
| |
| if len(motif_txs) == 0: |
| continue |
| |
| |
| transaction_mode = motif_txs['transaction_mode'].iloc[0] if len(motif_txs) > 0 else None |
| |
| if transaction_mode == 'many_to_many': |
| |
| dst_counts = motif_txs['dst'].value_counts() |
| if len(dst_counts) > 0: |
| main_wallet = dst_counts.index[0] |
| incoming_txs = motif_txs[motif_txs['dst'] == main_wallet] |
| upstream_accounts = [acc for acc in incoming_txs['src'].unique() if acc != main_wallet] |
| else: |
| upstream_accounts = [] |
| else: |
| upstream_accounts = motif_txs['src'].unique() |
| dst_counts = None |
| |
| if len(upstream_accounts) > 0: |
| num_victims = min(1, len(upstream_accounts)) |
| selected_accounts = np.random.choice(upstream_accounts, size=num_victims, replace=False) |
| |
| |
| if transaction_mode == 'many_to_many' and dst_counts is not None and len(dst_counts) > 0: |
| main_wallet = dst_counts.index[0] |
| incoming_txs = motif_txs[motif_txs['dst'] == main_wallet] |
| for account in selected_accounts: |
| account_txs = incoming_txs[incoming_txs['src'] == account] |
| if len(account_txs) > 0: |
| best_tx = account_txs.sort_values('amount', ascending=False).iloc[0] |
| selected_txs.append(best_tx.name) |
| else: |
| for account in selected_accounts: |
| account_txs = motif_txs[motif_txs['src'] == account] |
| if len(account_txs) > 0: |
| best_tx = account_txs.sort_values('amount', ascending=False).iloc[0] |
| selected_txs.append(best_tx.name) |
| |
| victim_idx = pd.Index(selected_txs) |
| print(f"Selected {len(victim_idx)} risk transactions as victims") |
| |
| |
| victim_accounts = set() |
| for idx in victim_idx: |
| victim_accounts.add(transactions_df.at[idx, 'src']) |
| |
| print(f"Victim accounts (src): {len(victim_accounts)}") |
| |
| |
| |
| |
| for account in victim_accounts: |
| |
| account_txs = transactions_df[ |
| (transactions_df['src'] == account) & |
| (transactions_df['is_risk'] == 1) & |
| (transactions_df['transaction_mode'].isin(supported_modes)) & |
| (transactions_df['transaction_motif'] != 'merchant_laundering') |
| ] |
| |
| if len(account_txs) > 0: |
| |
| many_to_many_txs = account_txs[account_txs['transaction_mode'] == 'many_to_many'] |
| other_txs = account_txs[account_txs['transaction_mode'] != 'many_to_many'] |
| |
| |
| if len(other_txs) > 0: |
| transactions_df.loc[other_txs.index, 'is_src_victim'] = 1 |
| |
| |
| if len(many_to_many_txs) > 0: |
| |
| for motif_id in many_to_many_txs['motif_id'].unique(): |
| motif_m2m_txs = many_to_many_txs[many_to_many_txs['motif_id'] == motif_id] |
| |
| |
| dst_counts = motif_m2m_txs['dst'].value_counts() |
| if len(dst_counts) > 0: |
| main_wallet = dst_counts.index[0] |
| |
| |
| incoming_tx_indices = motif_m2m_txs[motif_m2m_txs['dst'] == main_wallet].index |
| if len(incoming_tx_indices) > 0: |
| transactions_df.loc[incoming_tx_indices, 'is_src_victim'] = 1 |
| |
| |
| |
| np.random.seed(1243) |
| for account in victim_accounts: |
| |
| should_change = np.random.random() >= 0.2 |
| |
| if should_change: |
| |
| new_device = generate_random_mac() |
| new_ip = generate_random_ip() |
| |
| |
| account_victim_txs = transactions_df[ |
| (transactions_df['src'] == account) & |
| (transactions_df['is_src_victim'] == 1) |
| ] |
| transactions_df.loc[account_victim_txs.index, 'src_device'] = new_device |
| transactions_df.loc[account_victim_txs.index, 'src_ip'] = new_ip |
| |
| print(f"Victim statistics:") |
| print(f" Total transactions with is_src_victim=1: {(transactions_df['is_src_victim'] == 1).sum()}") |
| print(f" Unique victim accounts: {len(victim_accounts)}") |
|
|
| return transactions_df |
|
|
| def fix_duplicate_motif_ids(transactions_df: pd.DataFrame) -> pd.DataFrame: |
| """修复重复使用的motif_id,确保每个motif_id只对应一个transaction_motif""" |
| print("\n=== Fixing duplicate motif_id usage ===") |
| |
| |
| print("Step 1: Merging motif_id suffixes (e.g., '123-1', '123-2' -> '123')...") |
| |
| def merge_motif_id_suffix(motif_id): |
| """移除motif_id的后缀部分(如'-1', '-2'等)""" |
| if pd.isna(motif_id): |
| return motif_id |
| motif_str = str(motif_id) |
| |
| if '-' in motif_str: |
| |
| parts = motif_str.split('-') |
| |
| if len(parts) > 1 and parts[-1].isdigit(): |
| return '-'.join(parts[:-1]) |
| return motif_str |
| |
| transactions_df['motif_id_original'] = transactions_df['motif_id'].copy() |
| transactions_df['motif_id'] = transactions_df['motif_id'].apply(merge_motif_id_suffix) |
| |
| |
| merged_count = (transactions_df['motif_id_original'] != transactions_df['motif_id']).sum() |
| unique_original = transactions_df['motif_id_original'].nunique() |
| unique_merged = transactions_df['motif_id'].nunique() |
| print(f" Merged {merged_count} motif_id entries") |
| print(f" Unique motif_ids: {unique_original} -> {unique_merged}") |
| |
| |
| print("\nStep 2: Checking for duplicate motif_id usage across different transaction_motif...") |
| |
| |
| motif_motif_analysis = transactions_df.groupby(['motif_id', 'transaction_motif']).size().reset_index(name='count') |
| motif_id_motif_counts = motif_motif_analysis.groupby('motif_id')['transaction_motif'].nunique().reset_index(name='unique_motifs') |
| duplicate_motifs = motif_id_motif_counts[motif_id_motif_counts['unique_motifs'] > 1] |
| |
| print(f" Found {len(duplicate_motifs)} motif_ids used in multiple transaction_motif") |
| |
| if len(duplicate_motifs) > 0: |
| |
| new_motif_id_counter = int(transactions_df['motif_id'].max()) + 1 if transactions_df['motif_id'].dtype in [np.int64, np.float64] else 100000 |
| motif_id_mapping = {} |
| |
| |
| for old_motif_id in duplicate_motifs['motif_id'].values: |
| motif_transactions = transactions_df[transactions_df['motif_id'] == old_motif_id] |
| unique_motifs = motif_transactions['transaction_motif'].unique() |
| |
| |
| motif_counts = motif_transactions.groupby('transaction_motif').size() |
| main_motif = motif_counts.idxmax() |
| |
| |
| for motif_type in unique_motifs: |
| if motif_type == main_motif: |
| |
| continue |
| else: |
| |
| new_motif_id = new_motif_id_counter |
| motif_id_mapping[(old_motif_id, motif_type)] = new_motif_id |
| new_motif_id_counter += 1 |
| |
| |
| |
| def apply_motif_id_mapping(row): |
| old_motif_id = row['motif_id'] |
| transaction_motif = row['transaction_motif'] |
| key = (old_motif_id, transaction_motif) |
| if key in motif_id_mapping: |
| return motif_id_mapping[key] |
| return old_motif_id |
| |
| transactions_df['motif_id'] = transactions_df.apply(apply_motif_id_mapping, axis=1) |
| |
| |
| motif_id_motif_counts_after = transactions_df.groupby('motif_id')['transaction_motif'].nunique() |
| still_duplicate = motif_id_motif_counts_after[motif_id_motif_counts_after > 1] |
| if len(still_duplicate) > 0: |
| print(f" Warning: Still found {len(still_duplicate)} duplicate motif_ids after fix") |
| else: |
| print(f" ✅ All duplicate motif_ids have been fixed") |
| |
| print(f" Final unique motif_ids: {transactions_df['motif_id'].nunique()}") |
| else: |
| print(" ✅ No duplicate motif_ids found") |
| |
| |
| if 'motif_id_original' in transactions_df.columns: |
| transactions_df = transactions_df.drop(columns=['motif_id_original']) |
| |
| return transactions_df |
|
|
| def add_interval_and_hour_columns(transactions_df: pd.DataFrame) -> pd.DataFrame: |
| """添加interval和hour列(在motif_id修复之后)""" |
| print("\n=== Adding interval and hour columns ===") |
| |
| |
| transactions_df['timestamp'] = pd.to_datetime(transactions_df['timestamp']) |
| |
| |
| transactions_df['hour'] = transactions_df['timestamp'].dt.hour |
| print(f" Added hour column") |
| |
| |
| transactions_df = transactions_df.sort_values(['motif_id', 'timestamp']).reset_index(drop=True) |
| |
| |
| transactions_df['interval'] = 0.0 |
| |
| |
| motif_groups = transactions_df.groupby('motif_id') |
| |
| processed_groups = 0 |
| for motif_id, group in motif_groups: |
| if len(group) > 1: |
| |
| timestamps = group['timestamp'].values |
| intervals = [0.0] |
| |
| for i in range(1, len(timestamps)): |
| |
| time_diff = timestamps[i] - timestamps[i-1] |
| |
| if isinstance(time_diff, np.timedelta64): |
| time_diff_seconds = time_diff / np.timedelta64(1, 's') |
| elif hasattr(time_diff, 'total_seconds'): |
| time_diff_seconds = time_diff.total_seconds() |
| else: |
| time_diff_seconds = float(time_diff) / 1e9 |
| intervals.append(time_diff_seconds) |
| |
| |
| transactions_df.loc[group.index, 'interval'] = intervals |
| processed_groups += 1 |
| |
| print(f" Calculated intervals for {processed_groups} motif groups") |
| |
| return transactions_df |
|
|
| def main(): |
| """主函数""" |
| |
| total_start_time = time.time() |
| |
| print("=" * 70) |
| print("=== 交易生成程序 ===") |
| print("=" * 70) |
| print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
| print() |
| |
| |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 加载配置文件... {get_process_info()}") |
| config_start = time.time() |
| with open("conf_temporal_with_risk.json", 'r') as f: |
| config = json.load(f) |
| config_elapsed = time.time() - config_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 配置文件加载完成, 耗时 {config_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| g, balances, wallet_to_attrs, attr_headers, wallet_open_timestamps, abnormal_wallets = load_data( |
| config["input"]["edges"], |
| config["input"]["accounts"]) |
| |
| |
| print(f"\n=== 钱包开立时间统计 ===") |
| open_times = list(wallet_open_timestamps.values()) |
| if open_times: |
| earliest_open = min(open_times) |
| latest_open = max(open_times) |
| print(f"最早开立时间: {earliest_open}") |
| print(f"最晚开立时间: {latest_open}") |
| print(f"开立时间范围: {(latest_open - earliest_open).days} 天") |
| |
| |
| |
| sim_start_time = datetime.strptime(config["simulation"]["start_time"], "%Y-%m-%d %H:%M:%S") |
| original_wallet_count = len(wallet_open_timestamps) |
| allowed_wallets = {wid for wid, t in wallet_open_timestamps.items() if t <= sim_start_time} |
| removed_wallets = set(wallet_open_timestamps.keys()) - allowed_wallets |
| |
| if removed_wallets: |
| |
| for wid in list(g.nodes()): |
| if wid in removed_wallets: |
| g.remove_node(wid) |
| |
| |
| for wid in list(balances.keys()): |
| if wid in removed_wallets: |
| del balances[wid] |
| for wid in list(wallet_to_attrs.keys()): |
| if wid in removed_wallets: |
| del wallet_to_attrs[wid] |
| for wid in list(wallet_open_timestamps.keys()): |
| if wid in removed_wallets: |
| del wallet_open_timestamps[wid] |
| |
| abnormal_wallets -= removed_wallets |
| |
| print(f"\n=== 钱包过滤(开户时间晚于模拟开始时间) ===") |
| print(f"模拟开始时间: {sim_start_time}") |
| print(f"原始钱包数: {original_wallet_count}") |
| print(f"移除钱包数: {len(removed_wallets)}") |
| print(f"参与模拟的钱包数: {len(allowed_wallets)}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始生成交易... {get_process_info()}") |
| temp_output_file = config["output"]["transactions"].replace('.csv', '_temp.csv') |
| transactions = generate_transactions(g, balances, wallet_to_attrs, attr_headers, |
| wallet_open_timestamps, abnormal_wallets, config["simulation"], |
| output_file=temp_output_file) |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === 输出交易类型下 Transaction Mode 占比统计 ===") |
| from transaction_manager import TransactionManager |
| manager = TransactionManager("transaction_config.json") |
| manager.output_transaction_mode_distribution() |
|
|
| |
| safe_motifs = ['single_transaction', 'normal_small_high_freq', 'regular_large_low_freq'] |
| |
| |
| def filter_single_transactions(transactions): |
| """过滤单笔的forward和many_to_one交易,并验证many_to_one的完整性""" |
| |
| def is_many_to_one_complete(many_to_one_txs): |
| """检查many_to_one交易是否完整(有转入和转出)""" |
| if len(many_to_one_txs) < 3: |
| return False |
| |
| |
| dst_counts = {} |
| for tx in many_to_one_txs: |
| dst = tx.get("dst") |
| dst_counts[dst] = dst_counts.get(dst, 0) + 1 |
| |
| |
| main_wallet = max(dst_counts, key=dst_counts.get) |
| |
| |
| has_outgoing = any(tx.get("src") == main_wallet for tx in many_to_one_txs) |
| |
| |
| incoming_count = sum(1 for tx in many_to_one_txs if tx.get("dst") == main_wallet) |
| |
| return has_outgoing and incoming_count >= 2 |
|
|
| def is_one_to_many_complete(one_to_many_txs): |
| """检查one_to_many交易是否完整(有转入和转出)""" |
| if len(one_to_many_txs) < 3: |
| return False |
| dst_counts = {} |
| for tx in one_to_many_txs: |
| dst = tx.get("dst") |
| dst_counts[dst] = dst_counts.get(dst, 0) + 1 |
| |
| |
| main_wallet = max(dst_counts, key=dst_counts.get) |
| |
| |
| has_incoming = any(tx.get("src") != main_wallet and tx.get("dst") == main_wallet for tx in one_to_many_txs) |
| |
| |
| outgoing_count = sum(1 for tx in one_to_many_txs if tx.get("src") == main_wallet) |
| |
| return has_incoming and outgoing_count >= 2 |
|
|
| def is_many_to_many_complete(many_to_many_txs): |
| """检查many_to_many交易是否完整(有转入和转出)- 必须验证主钱包模式""" |
| if len(many_to_many_txs) < 4: |
| return False |
| |
| |
| dst_counts = {} |
| src_counts = {} |
| for tx in many_to_many_txs: |
| dst = tx.get("dst") |
| src = tx.get("src") |
| dst_counts[dst] = dst_counts.get(dst, 0) + 1 |
| src_counts[src] = src_counts.get(src, 0) + 1 |
| |
| |
| main_wallet_by_dst = max(dst_counts, key=dst_counts.get) |
| main_wallet_by_src = max(src_counts, key=src_counts.get) |
| |
| |
| if main_wallet_by_dst != main_wallet_by_src: |
| return False |
| |
| main_wallet = main_wallet_by_dst |
| |
| |
| incoming_count = sum(1 for tx in many_to_many_txs if tx.get("dst") == main_wallet) |
| outgoing_count = sum(1 for tx in many_to_many_txs if tx.get("src") == main_wallet) |
| |
| |
| first_tx = many_to_many_txs[0] |
| transaction_motif = first_tx.get("risk_type", "") |
| is_risk = transaction_motif in ["class4_laundering", "merchant_laundering", "online_laundering", "small_amount_testing"] or \ |
| first_tx.get("is_risk") == 1 or first_tx.get("is_risk") == '1' |
| |
| |
| if is_risk: |
| |
| if transaction_motif == "merchant_laundering": |
| |
| return incoming_count >= 2 and outgoing_count >= 2 |
| else: |
| |
| return incoming_count >= 3 and outgoing_count >= 4 |
| else: |
| |
| return incoming_count >= 2 and outgoing_count >= 2 |
| |
| |
| motif_groups = {} |
| for tx in transactions: |
| motif_id = tx.get("motif_id") |
| if motif_id not in motif_groups: |
| motif_groups[motif_id] = [] |
| motif_groups[motif_id].append(tx) |
| |
| filtered_transactions = [] |
| deleted_single_forward_count = 0 |
| deleted_incomplete_many_to_one_count = 0 |
| deleted_incomplete_one_to_many_count = 0 |
| deleted_incomplete_many_to_many_count = 0 |
| deleted_incomplete_fan_out_count = 0 |
| deleted_incomplete_fan_in_count = 0 |
| |
| for motif_id, group in motif_groups.items(): |
| |
| forward_txs = [tx for tx in group if tx.get("transaction_mode") == "forward"] |
| many_to_one_txs = [tx for tx in group if tx.get("transaction_mode") == "many_to_one"] |
| one_to_many_txs = [tx for tx in group if tx.get("transaction_mode") == "one_to_many"] |
| many_to_many_txs = [tx for tx in group if tx.get("transaction_mode") == "many_to_many"] |
| fan_out_txs = [tx for tx in group if tx.get("transaction_mode") == "fan_out"] |
| fan_in_txs = [tx for tx in group if tx.get("transaction_mode") == "fan_in"] |
| |
| |
| if forward_txs: |
| if len(forward_txs) == 2: |
| |
| filtered_transactions.extend(forward_txs) |
| else: |
| |
| deleted_single_forward_count += len(forward_txs) |
| |
| |
| if many_to_one_txs: |
| |
| if is_many_to_one_complete(many_to_one_txs): |
| |
| filtered_transactions.extend(many_to_one_txs) |
| else: |
| |
| deleted_incomplete_many_to_one_count += len(many_to_one_txs) |
| |
| |
| if one_to_many_txs: |
| |
| if is_one_to_many_complete(one_to_many_txs): |
| |
| filtered_transactions.extend(one_to_many_txs) |
| else: |
| |
| deleted_incomplete_one_to_many_count += len(one_to_many_txs) |
| |
| |
| if many_to_many_txs: |
| |
| if is_many_to_many_complete(many_to_many_txs): |
| |
| filtered_transactions.extend(many_to_many_txs) |
| else: |
| |
| deleted_incomplete_many_to_many_count += len(many_to_many_txs) |
| |
| |
| if fan_out_txs: |
| |
| if len(fan_out_txs) >= 2: |
| |
| filtered_transactions.extend(fan_out_txs) |
| else: |
| |
| deleted_incomplete_fan_out_count += len(fan_out_txs) |
| |
| |
| if fan_in_txs: |
| |
| if len(fan_in_txs) >= 2: |
| |
| filtered_transactions.extend(fan_in_txs) |
| else: |
| |
| deleted_incomplete_fan_in_count += len(fan_in_txs) |
| |
| |
| other_txs = [tx for tx in group if tx.get("transaction_mode") not in ["forward", "many_to_one", "one_to_many", "many_to_many", "fan_out", "fan_in"]] |
| filtered_transactions.extend(other_txs) |
| |
| return filtered_transactions, deleted_single_forward_count, deleted_incomplete_many_to_one_count, deleted_incomplete_one_to_many_count, deleted_incomplete_many_to_many_count, deleted_incomplete_fan_out_count, deleted_incomplete_fan_in_count |
|
|
|
|
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 保存过滤前的中间版本... {get_process_info()}") |
| intermediate_output_file = config["output"]["transactions"].replace('.csv', '_before_filter.csv') |
| intermediate_start = time.time() |
| with open(intermediate_output_file, 'w', newline='') as f: |
| writer = csv.writer(f) |
| writer.writerow(["tx_id", "timestamp", "src", "dst", "amount", "transaction_motif", "motif_id", "transaction_mode", "is_risk", "src_bank_account_number", "dst_bank_account_number", |
| "src_wallet_level", "dst_wallet_level"]) |
| for tx in transactions: |
| |
| transaction_motif = tx.get("risk_type", "unknown") |
| is_risk = '0' if transaction_motif in safe_motifs else '1' |
| src_info = get_wallet_info(tx["src"], wallet_to_attrs, attr_headers) |
| dst_info = get_wallet_info(tx["dst"], wallet_to_attrs, attr_headers) |
| writer.writerow([ |
| tx["tx_id"], |
| tx["timestamp"], |
| tx["src"], |
| tx["dst"], |
| tx["amount"], |
| transaction_motif, |
| tx["motif_id"], |
| tx.get("transaction_mode", ""), |
| is_risk, |
| src_info['bank_account_number'], |
| dst_info['bank_account_number'], |
| src_info['wallet_level'], |
| dst_info['wallet_level'] |
| ]) |
| intermediate_elapsed = time.time() - intermediate_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 中间版本保存完成, 耗时 {intermediate_elapsed:.2f} 秒 {get_process_info()}") |
| print(f"文件: {intermediate_output_file}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始过滤交易... {get_process_info()}") |
| filter_start = time.time() |
| filtered_transactions, deleted_forward, deleted_incomplete_many_to_one, deleted_incomplete_one_to_many, deleted_incomplete_many_to_many, deleted_incomplete_fan_out, deleted_incomplete_fan_in = filter_single_transactions(transactions) |
| filter_elapsed = time.time() - filter_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 交易过滤完成, 耗时 {filter_elapsed:.2f} 秒 {get_process_info()}") |
| |
| print(f"原始交易数: {len(transactions)}") |
| print(f"过滤后交易数: {len(filtered_transactions)}") |
| print(f"删除了 {deleted_forward} 笔单笔forward交易") |
| print(f"删除了 {deleted_incomplete_many_to_one} 笔不完整many_to_one交易") |
| print(f"删除了 {deleted_incomplete_one_to_many} 笔不完整one_to_many交易") |
| print(f"删除了 {deleted_incomplete_many_to_many} 笔不完整many_to_many交易") |
| print(f"删除了 {deleted_incomplete_fan_out} 笔不完整fan_out交易") |
| print(f"删除了 {deleted_incomplete_fan_in} 笔不完整fan_in交易") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 保存临时交易文件... {get_process_info()}") |
| temp_output_file = config["output"]["transactions"].replace('.csv', '_temp.csv') |
| temp_start = time.time() |
| with open(temp_output_file, 'w', newline='') as f: |
| writer = csv.writer(f) |
| writer.writerow(["tx_id", "timestamp", "src", "dst", "amount", "transaction_motif", "motif_id", "transaction_mode", "is_risk", "src_bank_account_number", "dst_bank_account_number", |
| "src_wallet_level", "dst_wallet_level"]) |
| for tx in filtered_transactions: |
| |
| transaction_motif = tx.get("risk_type", "unknown") |
| is_risk = '0' if transaction_motif in safe_motifs else '1' |
| src_info = get_wallet_info(tx["src"], wallet_to_attrs, attr_headers) |
| dst_info = get_wallet_info(tx["dst"], wallet_to_attrs, attr_headers) |
| writer.writerow([ |
| tx["tx_id"], |
| tx["timestamp"], |
| tx["src"], |
| tx["dst"], |
| tx["amount"], |
| transaction_motif, |
| tx["motif_id"], |
| tx.get("transaction_mode", ""), |
| is_risk, |
| src_info['bank_account_number'], |
| dst_info['bank_account_number'], |
| src_info['wallet_level'], |
| dst_info['wallet_level'] |
| ]) |
| temp_elapsed = time.time() - temp_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 临时文件保存完成, 耗时 {temp_elapsed:.2f} 秒 {get_process_info()}") |
| print(f"文件: {temp_output_file}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === Step 1: Adding device/IP columns === {get_process_info()}") |
| step1_start = time.time() |
| transactions_df = pd.read_csv(temp_output_file) |
| accounts_df = pd.read_csv(config["input"]["accounts"]) |
| account_map = build_account_device_ip_map(accounts_df) |
| transactions_df = add_device_ip_columns(transactions_df, account_map) |
| step1_elapsed = time.time() - step1_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Step 1 完成, 耗时 {step1_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === Step 2: Fixing duplicate motif_id usage === {get_process_info()}") |
| step2_start = time.time() |
| transactions_df = fix_duplicate_motif_ids(transactions_df) |
| step2_elapsed = time.time() - step2_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Step 2 完成, 耗时 {step2_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === Step 3: Adding interval and hour columns === {get_process_info()}") |
| step3_start = time.time() |
| transactions_df = add_interval_and_hour_columns(transactions_df) |
| step3_elapsed = time.time() - step3_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Step 3 完成, 耗时 {step3_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === Step 4: Applying victim pattern === {get_process_info()}") |
| step4_start = time.time() |
| transactions_df = apply_victim_pattern(transactions_df) |
| step4_elapsed = time.time() - step4_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Step 4 完成, 耗时 {step4_elapsed:.2f} 秒 {get_process_info()}") |
| |
| |
| print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] === Step 5: Saving final transactions === {get_process_info()}") |
| step5_start = time.time() |
| |
| final_columns = ["tx_id", "timestamp", "src", "dst", "amount", "transaction_motif", "motif_id", |
| "transaction_mode", "is_risk", "is_src_victim", "src_bank_account_number", "dst_bank_account_number", |
| "src_wallet_level", "dst_wallet_level", "src_device", "src_ip", "dst_device", "dst_ip", |
| "interval", "hour"] |
| |
| available_columns = [col for col in final_columns if col in transactions_df.columns] |
| transactions_df[available_columns].to_csv(config["output"]["transactions"], index=False) |
| step5_elapsed = time.time() - step5_start |
| print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Step 5 完成, 耗时 {step5_elapsed:.2f} 秒 {get_process_info()}") |
| print(f"最终文件: {config['output']['transactions']}") |
| print(f"总列数: {len(available_columns)}") |
| print(f"列: {', '.join(available_columns)}") |
| |
| |
| total_end_time = time.time() |
| total_elapsed_time = total_end_time - total_start_time |
| |
| |
| print("\n" + "=" * 70) |
| print("=== 程序执行完成 ===") |
| print("=" * 70) |
| print(f"结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
| print(f"总运行时间: {total_elapsed_time:.2f} 秒 ({total_elapsed_time/60:.2f} 分钟)") |
| print(f"进程信息: {get_process_info()}") |
| print("=" * 70) |
| |
|
|
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|