-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
298 lines (243 loc) · 8.15 KB
/
Copy pathmain.py
File metadata and controls
298 lines (243 loc) · 8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python3
"""
VAN Protocol Simulation — Точка входа.
Запуск сценариев:
python main.py sybil — Sybil-атака с варьированием CIDR
python main.py fraud — Fraud Proof: внедрение нечестного валидатора
python main.py drift — Медленный дрейф честности
python main.py censorship — Топологическая цензура + Delivery Receipt
python main.py all — Все сценарии
"""
import argparse
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from van_sim.simulation import SimulationEngine, ScenarioConfig
from van_sim.visualize import generate_all_plots
def run_sybil(output_dir="results/sybil"):
"""Sybil-атака: варьирование % злонамеренных + CIDR."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Sybil-атака с CIDR-защитой")
print("=" * 60)
config = ScenarioConfig(
total_nodes=60,
committee_size=10,
committee_threshold=7,
epochs=40,
honest_ratio=0.5,
malicious_ratio=0.1,
sybil_ratio=0.3,
drifting_ratio=0.1,
sybil_subnet_8=10,
sybil_subnet_16=1,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_fraud(output_dir="results/fraud"):
"""Fraud Proof: внедрение нечестного валидатора."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Fraud Proof — фальшивый токен")
print("=" * 60)
config = ScenarioConfig(
total_nodes=50,
committee_size=10,
committee_threshold=7,
epochs=30,
honest_ratio=0.7,
malicious_ratio=0.15,
sybil_ratio=0.1,
drifting_ratio=0.05,
fraud_epoch=15,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_drift(output_dir="results/drift"):
"""Медленный дрейф: ловит ли ротация?"""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Медленный дрейф честности")
print("=" * 60)
config = ScenarioConfig(
total_nodes=40,
committee_size=8,
committee_threshold=5,
epochs=60,
honest_ratio=0.6,
malicious_ratio=0.05,
sybil_ratio=0.05,
drifting_ratio=0.3,
drift_start_epoch=15,
drift_rate=0.04,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_censorship(output_dir="results/censorship"):
"""Топологическая цензура + Delivery Receipt."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Топологическая цензура")
print("=" * 60)
config = ScenarioConfig(
total_nodes=40,
committee_size=8,
committee_threshold=5,
epochs=30,
honest_ratio=0.7,
malicious_ratio=0.1,
sybil_ratio=0.1,
drifting_ratio=0.1,
censorship_epoch=15,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_churn(output_dir="results/churn"):
"""Массовый отвал узлов (Churn)."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Массовый отвал узлов (Блэкаут)")
print("=" * 60)
config = ScenarioConfig(
total_nodes=100,
committee_size=10,
committee_threshold=7,
epochs=30,
honest_ratio=0.8,
malicious_ratio=0.1,
sybil_ratio=0.0,
drifting_ratio=0.1,
churn_epoch=15,
churn_ratio=0.5,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_false_acc(output_dir="results/false_acc"):
"""DDoS ложными жалобами."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: DDoS ложными жалобами (False Accusation)")
print("=" * 60)
config = ScenarioConfig(
total_nodes=40,
committee_size=8,
committee_threshold=5,
epochs=20,
honest_ratio=0.8,
malicious_ratio=0.2,
sybil_ratio=0.0,
drifting_ratio=0.0,
false_acc_epoch=10,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_dda(output_dir="results/dda"):
"""Атака на алгоритм сложности (DDA Griefing)."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Атака на алгоритм сложности (DDA Griefing)")
print("=" * 60)
config = ScenarioConfig(
total_nodes=40,
committee_size=8,
committee_threshold=5,
epochs=30,
honest_ratio=1.0,
malicious_ratio=0.0,
sybil_ratio=0.0,
drifting_ratio=0.0,
dda_attack_epoch=10,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
def run_eclipse(output_dir="results/eclipse"):
"""Eclipse Attack."""
print("\n" + "=" * 60)
print("СЦЕНАРИЙ: Атака Затмения (Eclipse Attack)")
print("=" * 60)
config = ScenarioConfig(
total_nodes=100,
committee_size=10,
committee_threshold=7,
epochs=15,
honest_ratio=0.5,
malicious_ratio=0.0,
sybil_ratio=0.5,
drifting_ratio=0.0,
eclipse_attack=True,
random_seed=42,
)
engine = SimulationEngine(config)
engine.initialize()
# Диагностика Eclipse: проверяем соседей жертвы
target_id = engine.nodes[0].node_id
neighbors = engine.topology._find_k_closest(target_id, engine.topology.k)
sybil_count = sum(1 for n in neighbors if engine._node_map[n].behavior.name == "SYBIL")
print(f" [Диагностика Eclipse] Жертва окружена {sybil_count}/{engine.topology.k} Sybil-узлами.")
if sybil_count < engine.topology.k:
print(" => Eclipse Attack ПРОВАЛИЛАСЬ благодаря k-bucket алгоритму Kademlia!")
engine.run(verbose=True)
files = generate_all_plots(engine, output_dir)
print(f"\nГрафики: {files}")
return engine
SCENARIOS = {
"sybil": run_sybil,
"fraud": run_fraud,
"drift": run_drift,
"censorship": run_censorship,
"churn": run_churn,
"false_acc": run_false_acc,
"dda": run_dda,
"eclipse": run_eclipse,
}
def main():
parser = argparse.ArgumentParser(
description="VAN Protocol Simulation — proof-of-concept"
)
parser.add_argument(
"scenario",
choices=list(SCENARIOS.keys()) + ["all"],
help="Сценарий для запуска",
)
parser.add_argument(
"--output", "-o",
default="results",
help="Директория для результатов",
)
args = parser.parse_args()
if args.scenario == "all":
for name, fn in SCENARIOS.items():
fn(output_dir=f"{args.output}/{name}")
else:
SCENARIOS[args.scenario](output_dir=f"{args.output}/{args.scenario}")
print("\n✅ Готово!")
if __name__ == "__main__":
main()