0% found this document useful (0 votes)
3 views629 pages

NADS Complete Reference

The NADS Complete Technical Reference provides an in-depth guide to the Network Anomaly Detection System, detailing its architecture, processing stages, and codebase. It includes a changelog of critical bug fixes, enterprise upgrades, and configuration references for optimal system performance. The document also outlines backend modules, threading models, and various detection algorithms used to monitor network traffic and identify anomalies.

Uploaded by

u7474905
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views629 pages

NADS Complete Reference

The NADS Complete Technical Reference provides an in-depth guide to the Network Anomaly Detection System, detailing its architecture, processing stages, and codebase. It includes a changelog of critical bug fixes, enterprise upgrades, and configuration references for optimal system performance. The document also outlines backend modules, threading models, and various detection algorithms used to monitor network traffic and identify anomalies.

Uploaded by

u7474905
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

NADS Complete Technical Reference

NADS — Network Anomaly Detection


System
Complete Technical Reference
Codebase Guide | Line-by-Line Source Reference

Version: 2.1.0 | Backend: C++17 (libpcap) | Frontend: React 18 / TypeScript / Vite

Project: NADS + WebWireshark | 91 Source Files Documented

Page 1 of 629
NADS Complete Technical Reference

PART A — NADS COMPLETE CODEBASE GUIDE

Document: NADS_CODEBASE_GUIDE.md
Network Anomaly Detection System (NADS) + WebWireshark — single reference covering
architecture, all changes made, and per-module explanations.

Part 1 — Overview
1.1 What Is This Project?
Component Easy Explanation Technical Role
NADS (nads/) A C++ program that watches network traffic Real-time IDS: libpcap capture → flow
like a security camera, spots strange reconstruction → multi-detector scoring →
behaviour, and writes alerts. fusion → JSON/log alerts.
WebWireshark A browser dashboard (React) that shows Vite + React UI; REST polling + WebSocket
(webwireshark/) live packets, flows, alerts, and stats from push from NADS HTTP server on port
NADS. 8080.

1.2 High-Level Pipeline


The system operates across five processing stages:
1. Capture Thread — libpcap reads raw frames from the network interface and pushes PacketInfo
objects into ConcurrentQueue.
2. Analysis Thread — Reads each packet, parses headers, updates flow records, counts per-second
rates.
3. Sweeper Thread — Every ~5 seconds, closes idle flows and runs the full detector chain plus fusion.
4. Sampler Thread — Once per second, updates speed gauges, checks flood thresholds, exports
Prometheus metrics.
5. HTTP Thread — Serves REST endpoints and WebSocket push to the WebWireshark browser
frontend.

1.3 Thread Model


Thread File Easy Technical
Capture [Link] Grabs packets from the pcap_loop callback; only copies bytes into
network card as fast as PacketInfo and pushes queue.
possible.
Analysis [Link] Reads each packet, Parses 5-tuple, flow_table_->touch,
analysis_loop updates flows, counts volume_det_->on_packet, optional WS
rates. broadcast.
Sweeper [Link] Every ~5s, closes idle sweep_expired →
sweeper_loop conversations and runs full process_completed_flow → all detectors +
detection. fusion + alert.

Page 2 of 629
NADS Complete Technical Reference

Thread File Easy Technical


Sampler [Link] Once per second, updates PPS/BPS gauges, volume_det_->detect(),
rate_sampler_loop speed graphs and flood Prometheus metrics, volume alerts.
checks.
HTTP http_server.cpp Serves API and WebSocket select() loop, static files, /api/*, /metrics,
to the browser. RFC 6455 WS.
Dashboard console_display.cpp Terminal UI with colours ANSI truecolour refresh thread.
and live stats.

1.4 Directory Tree


nads-fixed/
├── NADS_CODEBASE_GUIDE.md
├── [Link]
├── nads/
│ ├── include/ headers (types, detectors, orchestrator)
│ ├── src/ implementations
│ ├── tests/ unit tests (custom runner)
│ ├── benchmarks/ bench_capture
│ ├── tools/ train_fusion.py
│ ├── [Link] runtime settings
│ ├── fusion_weights.txt logistic fusion weights
│ └── [Link]
└── webwireshark/
└── src/
├── lib/[Link] WebSocket client
├── store/[Link]
└── pages/ Capture, Alerts, Flows, Stats, Settings

Part 2 — Changelog (All Changes)


A. Critical Bug Fixes
# Area Files Easy Fix Technical Fix
1 Use-after- types.h, [Link], Storing a pointer into packet Replaced payload_ptr with
free flow_table.cpp memory broke when the payload_offset; access via
packet was moved in the raw_bytes.data() + offset.
queue.
2 Data race orchestrator.h, Two threads updated/read Added second_counts_mutex_
[Link] packet counts per second around second_pkt_counts_ and
without locking — last_second_.
crash/corruption.
3 Out-of- [Link] L56-59 IP header said 1500 bytes total = min(ntohs(total_length),
bounds read but capture only had 100. cap_len).
4 Baseline baseline_engine.cpp Only the smaller IP in a flow Loop both src_ip and dst_ip; use
one-sided got a profile. correct peer_ip per side.
5 Frontend [Link] Browser RAM grew forever addPacket / setPackets trim to
memory with every packet. maxPackets (default 100k).
6 Volume false volume_detector.cpp, 50 SYN/s triggered critical Configurable
positives [Link] alerts on busy hosts. syn_flood_threshold_pps (500) and
packet_flood_threshold_pps (2000).

Page 3 of 629
NADS Complete Technical Reference

# Area Files Easy Fix Technical Fix


7 WebSocket [Link] Frontend hardcoded Relative ws(s)://{host}/ws (Vite
URL localhost:8080 — failed in proxies /ws).
production.
8 Pause flag orchestrator.h Pause/resume from HTTP std::atomic<bool> capture_paused_.
race API could race with capture
thread.

B. Enterprise Upgrades (12 Phases)


Phase Feature Key Files
1 EWMA + percentile adaptive running_stats.h, stat_detector, volume_detector, baseline_engine
stats
2 Per-service baselines baseline_engine.h/cpp
(ServiceProfile)
3 Multi-detector correlation boost correlation_engine.h/cpp, [Link]
4 Logistic regression fusion logistic_fusion.h/cpp, fusion_engine.h/cpp, tools/train_fusion.py
(optional)
5 Prometheus /metrics metrics_registry.h/cpp, http_server.cpp
6 L7 hints (HTTP/TLS/DNS) l7_parser.h/cpp, types.h L7Hints, [Link]
7 Performance helpers object_pool.h, flow_table reserve, benchmarks/bench_capture.cpp
8 Advanced detectors advanced_detectors.h/cpp (slow scan, burst, DNS tunnel, SYN ratio,
long-lived)
9 Config loader + validation config_loader.h/cpp, [Link], extended [Link]
10 New unit tests test_adaptive_stats.cpp, test_correlation.cpp
11 Enterprise alerts (MITRE, types.h AnomalyEvent, threat_classifier.cpp, alert_system.cpp
evidence)
12 Shared scoring utilities scoring_utils.h, detector_interface.h

C. Build Fixes Applied


The following build-level corrections were applied during the enterprise upgrade process:
- Added #include <cmath> in logistic_fusion.cpp and correlation_engine.cpp to resolve std::exp and
std::fabs symbol errors.
- Added EwmaStats() default constructor and hosts_.try_emplace(host_ip) in baseline_engine.cpp.
- Updated fusion_engine.h to include logistic_fusion.h, resolving incomplete type with
std::unique_ptr<LogisticFusion>.
- Removed unused ANSI constants in console_display.cpp (DIM, LM, RM, HM).

Part 3 — Configuration Reference


File: nads/[Link]

Page 4 of 629
NADS Complete Technical Reference

Key Default Easy Technical


interface lo Which network card to sniff. Passed to pcap_open_live.
bpf_filter empty Berkeley filter, e.g. tcp port 80. pcap_compile + pcap_setfilter.
alert_threshold 0.75 Score above this triggers an Compared in FusionResult /
alert. orchestrator.
flow_timeout_sec 30 How long before a quiet flow is FlowTable::timeout_us_.
analysed.
syn_flood_threshold_pps 500 SYN/s above this triggers flood Hard floor in VolumeDetector::detect.
alert tier.
packet_flood_threshold_pps 2000 Total packets/s flood tier. Same.
ewma_alpha 0.05 How fast baselines adapt EWMA smoothing factor in (0,1].
(higher = faster).
percentile_window 256 Samples kept for percentile RingBufferPercentile capacity.
bands.
adaptive_thresholds true Use smart stats vs old Welford- Toggles AdaptiveBaseline in
only. detectors.
fusion_type weighted How scores are combined. weighted or logistic (sets logistic
flag).
use_logistic_fusion false ML-style fusion from weights LogisticFusion::fuse sigmoid.
file.
correlation_window_sec 30 Time window for multi-detector CorrelationEngine deque prune.
boost.
use_per_service_baseline true Track behaviour per destination ServiceProfile map per host.
port.
metrics_enabled true Expose Prometheus endpoint. GET /metrics in http_server.
enable_* detectors true Turn advanced detectors on/off. AdvancedDetectors gates.
w_* weights see file Importance of each detector in Normalised weighted sum in
fusion. FusionEngine.

CLI Flags ([Link])


Flag Meaning
-i Interface
-f BPF filter
-t Alert threshold
-w Flow timeout seconds
-o / -j Log / JSON output paths
-c Load [Link]
-p Web server port
-q No terminal dashboard
-r Read-only (no capture side effects)

Part 4 — Backend Modules (Line-by-Line)

Page 5 of 629
NADS Complete Technical Reference

Each section covers: Easy explanation (plain English) → Technical explanation → Line walkthrough
grouped by logical blocks with file:line references.

4.1 include/types.h — Shared Data Model


Easy: The dictionary every module uses — packet shape, flow shape, alert shape, settings.
Technical: Packed wire headers (#pragma pack), FlowKey canonicalisation support, atomics in
LiveStats, enterprise fields on AnomalyEvent.

Lines Section Easy Technical


19-59 Wire headers Binary layouts matching real #pragma pack(push, 1) prevents compiler
Ethernet/IP/TCP/UDP on the padding; used with reinterpret_cast on
network. raw_bytes.
78-81 PacketInfo — Raw packet bytes and sizes. raw_bytes owns copy from pcap; cap_length <=
raw data wire length.
84-92 PacketInfo — Who talked to whom (IPs, ports, Network byte order for IPs; ports host order
addressing protocol). after ntohs.
91 payload_offset Where payload starts inside Bug fix: payload_offset not pointer (survives
raw_bytes. std::move).
94-104 L7 hints HTTP/TLS/DNS hints. Filled by parse_l7_hints() after L4 parse.
110- FlowKey + hash Unique ID for a conversation (both Smaller IP always src_ip in key; FNV-style
138 directions merged). FlowKeyHash for unordered_map.
143- FlowRecord Counters for TCP flags, timing Derived pps/bps at flow end.
193 deque, byte histogram for entropy.
198- Results and Per-module score and combined DetectorResult: score 0-1 + flags.
241 alerts score. FusionResult: combined score. AnomalyEvent:
MITRE tags, evidence, correlation metadata.
267- Config All tunables for capture, adaptive Feature flags and detector weights.
317 stats, fusion, correlation.

4.2 include/running_stats.h — Statistics Engine


Easy: Math that learns normal traffic and flags spikes.
Technical: Welford O(1) variance; EWMA for drifting baselines; ring buffer + nth_element for
percentiles; AdaptiveBaseline::score = max(z-score, percentile exceedance).

Class Lines Easy Technical


RunningStats 11-46 Classic Welford: mean, Used where legacy behaviour is needed.
sample variance, z-score.
EwmaStats 48-97 Smoothly tracks average Exponentially weighted; O(1) per sample. Default +
traffic over time. explicit alpha constructor fixes HostProfile map
emplace.
RingBufferPercentile 99-133 Fixed-size ring buffer for On percentile() copies snapshot and runs
percentile calculations. std::nth_element — O(n) only when scoring.
AdaptiveBaseline 141- Combines EWMA and score(x): compare x to EWMA z and to 95th
166 percentile scoring. percentile band (scale=1.15). observe(x) updates
both after scoring.

Page 6 of 629
NADS Complete Technical Reference

Class Lines Easy Technical


normalize_z 135- Maps absolute z-score to |z| to [0,1] with cap at threshold (usually 3.0).
139 0-1 range.

4.3 include/concurrent_queue.h + src/[Link]


ConcurrentQueue
Lines Easy Technical
16-24 Add packet; wait if full. Mutex + condition_variable; drops when size >= max_size_.
27-36 Analysis thread takes packets. wait_for timeout 200 ms — orchestrator polls running_.
39-42 Shutdown signal. stopped_ wakes all waiters.

[Link]
Lines Easy Technical
24-53 Open network interface + optional BPF pcap_open_live, pcap_compile/setfilter.
filter.
80-97 For each packet: copy bytes, push queue. packet_callback; updates atomics; drop counter on full
queue.
100+ Loop until stopped. pcap_loop in dedicated thread.

4.4 src/[Link] + src/l7_parser.cpp


[Link]
Lines Easy Technical
8-10 Too small — reject. Minimum IPv4 header check.
20-41 Skip Ethernet / loopback / SLL header. link_type_ from pcap datalink.
45-53 Read IPv4 addresses and protocol. Version/IHL check.
56-60 Bug fix: do not read past capture. Clamp total_length to cap_len.
62-81 TCP ports, flags, payload offset/size. pl_off = l4 + tcp_hdr_len; clamp payload to avail.
79, 98 Detect HTTP/TLS/DNS patterns. Calls parse_l7_hints(pkt).

l7_parser.cpp Summary
HTTP detection: GET / POST / HTTP/ on ports 80 and 8080.
TLS detection: byte 0x16, version 0x03; placeholder JA3 string on ClientHello.
DNS detection: entropy on UDP/53 payload; flag tunnel if entropy high and packet is large.

4.5 src/flow_table.cpp
Lines Easy Technical
8-11 Pre-allocate hash table. flows_.reserve(16384) — performance optimisation.

Page 7 of 629
NADS Complete Technical Reference

Lines Easy Technical


13-28 A to B and B to A are the same Canonical key: smaller IP is src.
flow.
31-89 Update counters per packet. SYN/ACK/FIN counts, NULL/XMAS scan flags, IAT/size deques.
79-87 Bug fix: histogram uses offset into Max 100 bytes per packet for CPU bound.
raw_bytes.
92-105 Remove idle flows; compute sweep_expired → compute_features.
features.
108- Flow statistics. PPS, BPS, entropy, mean/stddev IAT and size. Shannon entropy
159 over 256-bin histogram.

4.6 Detectors
stat_detector.cpp
configure(cfg): builds AdaptiveBaseline per metric with ewma_alpha and window.
detect: scores bps, pps, mean_pkt_size, duration before observe() — anomaly vs history.
Fallback: legacy RunningStats if adaptive_thresholds=false.

volume_detector.cpp
Maintains 60 one-second buckets; on_packet increments packets/bytes/SYN.
detect: adaptive z on pps/syn_pps plus hard thresholds from config (floods always caught). Updates
histograms after scoring.

baseline_engine.cpp
For each endpoint (src_ip, dst_ip):
- Host-level EWMA/Welford deviation, new peer/port detection, lateral movement on admin ports (445,
3389, 22).
- Optional ServiceProfile per dst_port with per-service bps/size spikes.
try_emplace(host_ip) avoids invalid HostProfile{} with explicit-only EwmaStats.

protocol_analyzer.cpp
Rule-based: SYN without ACK, NULL/XMAS scan, half-open scan, RST/ICMP/DNS floods, DNS high
entropy.

graph_detector.cpp
Tracks peer graph per host; degree spike signals port scan or worm spread.

temporal_detector.cpp
Inter-arrival regularity detection signals beaconing (C2 check-in pattern).

Page 8 of 629
NADS Complete Technical Reference

entropy_profiler.cpp
Shannon H from flow histogram; unexpected high/low entropy on known ports (e.g. HTTP vs TLS).

advanced_detectors.cpp
Detector Easy Description Trigger Condition
slow_scan Many ports touched slowly. Novel ports + low packet count.
burst Traffic explosion. High PPS over short flow.
long_lived Connection open for hours. Duration > 3600s, large bytes.
dns_tunnel Hidden data in DNS. UDP/53, high entropy, large mean size.
syn_ratio SYN flood per host. Many SYN packets, no ACK responses.

4.7 Fusion and Correlation


correlation_engine.cpp
Lines Easy Technical
15-28 Remember recent alerts per source Deque of DetectorHit; duplicate suppression within 1s.
IP.
30-38 Store detector name, score, time. Only if score >= 0.5.
40-62 Boost score if multiple detector types +0.10 for 2+ types, +0.08 for 3+, +0.07 temporal+protocol, +0.05
fired. for repeats.

fusion_engine.cpp
Weighted mode: sum(w_i * score_i) / sum(w_i) plus optional legacy corroboration boost.
Logistic mode: sigmoid(bias + sum of w_i * score_i) from fusion_weights.txt.
Single-detector score >= 0.85 can lift final score (volume floods).

logistic_fusion.cpp
fuse: dot product + sigmoid to produce probability.
online_update: SGD step on label (for future feedback loops).
load_weights / save_weights: line-oriented name-value file format.

4.8 Classification, Alerts, Orchestrator


threat_classifier.cpp
Rule chain: SYN flood, scans, beacon, brute-force, lateral movement, tunnelling.
fill_mitre: maps attack name to MITRE technique/tactic IDs.
finish(): attaches detector evidence strings.

alert_system.cpp

Page 9 of 629
NADS Complete Technical Reference

Cooldown per (src_ip, attack_type) prevents alert spam.


Console colour by severity; appends [Link] and [Link].
JSON output includes MITRE, evidence, correlation_id, and flow_summary.

[Link] Critical Paths


Function Easy Technical
Constructor L17-38 Wire all modules together. unique_ptrs; stat_det_->configure;
correlation/advanced engines.
analysis_loop Per-packet processing path. parse → mutex second_counts → volume → flow touch
→ graph on new flow.
process_completed_flow Full analysis on idle flow. All detectors → correlation record → fusion → boost →
classify → alert.
rate_sampler_loop Every 1s: speeds, metrics, update_metrics, volume_det_->detect(), top talker IP
volume alerts. from mutex map.

4.9 HTTP Server, Main, Config, Metrics, Console


src/http_server.cpp Summary
Routes: /api/packets, /api/alerts, /api/flows, /api/summary, capture control, config.
GET /metrics: Prometheus text from MetricsRegistry.
WebSocket: SHA-1 handshake, framed JSON packet / nads_alert / stats messages.
build_alert_json: adds correlationId, flowSummary, finalScore for UI consumption.

src/[Link]
Parse CLI arguments → optional load_config_file → validate_config → Orchestrator::start → wait for
signal.

src/config_loader.cpp
Parses key = value pairs; boolean via true/yes/on; validates alpha, weights sum, thresholds.

src/metrics_registry.cpp
Singleton counters/gauges; render() emits Prometheus text format.

src/console_display.cpp
Full-screen ANSI dashboard: stats, sparkline, top talkers, recent alerts. Not line-documented (UI layout
code).

Part 5 — Tests, Build, and Tools

Page 10 of 629
NADS Complete Technical Reference

5.1 Unit Tests (nads/tests/)


File What It Validates
test_parser.cpp TCP parse, payload offset after move, truncated IP length clamp.
test_flow_table.cpp Bidirectional keys, expiry, feature rates.
test_running_stats.cpp Welford mean/variance, z-score.
test_adaptive_stats.cpp EWMA, percentile p95, adaptive spike.
test_correlation.cpp Multi-detector correlation boost.
test_stat_detector.cpp Normal traffic low score; outlier high score.
test_protocol_analyzer.cpp SYN scan, NULL/XMAS, DNS, ICMP.
test_graph_detector.cpp Degree spike.
test_temporal_detector.cpp Beacon vs human timing.
test_entropy.cpp Shannon H bounds.
test_fusion.cpp Weighted fusion, corroboration, clamp.
test_classifier.cpp Attack naming and severity.

Run all tests: ./run_tests from the build directory.

5.2 CMake Targets


Target Output
nads_lib Static library of all modules.
nads Main executable binary.
run_tests Test runner.
bench_capture Parse throughput benchmark.

5.3 Tools
tools/train_fusion.py: Reads [Link], trains sklearn logistic regression, writes fusion_weights.txt.

Part 6 — Frontend Summary


Note: No line-by-line documentation for webwireshark/src/components/ui/* (shadcn boilerplate).

6.1 Key Files


webwireshark/src/lib/[Link]
Easy: Keeps a live connection to NADS; pushes packets and alerts into the store.
Technical: WebSocketClient with reconnect, heartbeat, parses {type, payload} messages.
Change: [Link] or wss:// — works behind Vite proxy and in production.

Page 11 of 629
NADS Complete Technical Reference

webwireshark/src/store/[Link]
Zustand store: packets, alerts, stats, settings.
Lines 93-108: Ring buffer — drops oldest when length exceeds maxPackets (100,000 default).

6.2 Pages
Page Role
[Link] Live packet list with filter.
[Link] Anomaly list from API/WS.
[Link] Active flow table.
[Link] PPS/BPS charts.
[Link] maxPackets, interface, filter configuration.

6.3 Dev Proxy ([Link])


/api proxied to [Link]
/ws proxied to [Link]

Part 7 — How to Run and Verify


7.1 Build (Linux / WSL)
cd nads
mkdir -p build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
./run_tests

7.2 Run Capture


sudo ./nads -i lo -c ../[Link]
# or eth0 with filter:
sudo ./nads -i eth0 -f "tcp" -c ../[Link] -q

7.3 Verify Backend


curl [Link]
curl [Link]
curl [Link]

7.4 Run Frontend


cd webwireshark
npm install
npm run dev

Page 12 of 629
NADS Complete Technical Reference

# Open browser URL shown, e.g. localhost:5173

7.5 [Link] Fields (Enterprise)


Field Meaning
mitre_techniques e.g. T1498, T1046
mitre_tactics e.g. Impact, Discovery
evidence detector=score strings
correlation_id Links related hits.
correlation_boost Added to fused score.
flow_summary pkt/byte/duration summary.

7.6 Prometheus Metrics (Grafana-Ready)


nads_capture_pps
nads_capture_bps
nads_flows_active
nads_alerts_total
nads_packets_captured_total
nads_packets_dropped_total
nads_queue_depth
nads_detector_score{detector="volume"} (labelled gauges)

7.7 Module to File Map


Module Name Header Source
1 Capture capture.h [Link]
2 Parser parser.h [Link], l7_parser.cpp
3 Flow Table flow_table.h flow_table.cpp
4 Statistical stat_detector.h stat_detector.cpp
5 Volume volume_detector.h volume_detector.cpp
6 Protocol protocol_analyzer.h protocol_analyzer.cpp
7 Baseline baseline_engine.h baseline_engine.cpp
8 Graph graph_detector.h graph_detector.cpp
9 Temporal temporal_detector.h temporal_detector.cpp
10 Entropy entropy_profiler.h entropy_profiler.cpp
11 Classifier threat_classifier.h threat_classifier.cpp
12 Fusion fusion_engine.h fusion_engine.cpp, logistic_fusion.cpp
— Correlation correlation_engine.h correlation_engine.cpp
— Advanced advanced_detectors.h advanced_detectors.cpp
13 Alerts alert_system.h alert_system.cpp
14 Console console_display.h console_display.cpp
15 Orchestrator orchestrator.h [Link]

Page 13 of 629
NADS Complete Technical Reference

Module Name Header Source


— HTTP API http_server.h http_server.cpp
— Metrics metrics_registry.h metrics_registry.cpp
— Config config_loader.h config_loader.cpp
— Entry — [Link]
— Types types.h —
— Stats running_stats.h running_stats.cpp

Page 14 of 629
NADS Complete Technical Reference

— END OF PART A: NADS CODEBASE GUIDE —

PART B — NADS LINE-BY-LINE COMPLETE REFERENCE

Document: NADS_LINE_BY_LINE_COMPLETE.md
Every line of every core source file in the NADS backend and WebWireshark application. Excludes
webwireshark/src/components/ui/* (shadcn boilerplate) and nads/build/*.

Reading guide:
Easy = plain English description of what the line does.
Technical = developer / security engineer terminology.
Files documented: 91

File Index
# File Path
1 nads/include/advanced_detectors.h
2 nads/include/alert_system.h
3 nads/include/baseline_engine.h
4 nads/include/capture.h
5 nads/include/concurrent_queue.h
6 nads/include/config_loader.h
7 nads/include/console_display.h
8 nads/include/correlation_engine.h
9 nads/include/detector_interface.h
10 nads/include/entropy_profiler.h
11 nads/include/flow_table.h
12 nads/include/fusion_engine.h
13 nads/include/graph_detector.h
14 nads/include/http_server.h
15 nads/include/l7_parser.h
16 nads/include/logistic_fusion.h
17 nads/include/metrics_registry.h
18 nads/include/object_pool.h
19 nads/include/orchestrator.h
20 nads/include/parser.h

Page 15 of 629
NADS Complete Technical Reference

# File Path
21 nads/include/protocol_analyzer.h
22 nads/include/running_stats.h
23 nads/include/scoring_utils.h
24 nads/include/stat_detector.h
25 nads/include/temporal_detector.h
26 nads/include/threat_classifier.h
27 nads/include/types.h
28 nads/include/volume_detector.h
29 nads/src/advanced_detectors.cpp
30 nads/src/alert_system.cpp
31 nads/src/baseline_engine.cpp
32 nads/src/[Link]
33 nads/src/config_loader.cpp
34 nads/src/console_display.cpp
35 nads/src/correlation_engine.cpp
36 nads/src/entropy_profiler.cpp
37 nads/src/flow_table.cpp
38 nads/src/fusion_engine.cpp
39 nads/src/graph_detector.cpp
40 nads/src/http_server.cpp
41 nads/src/l7_parser.cpp
42 nads/src/logistic_fusion.cpp
43 nads/src/[Link]
44 nads/src/metrics_registry.cpp
45 nads/src/[Link]
46 nads/src/[Link]
47 nads/src/protocol_analyzer.cpp
48 nads/src/running_stats.cpp
49 nads/src/stat_detector.cpp
50 nads/src/temporal_detector.cpp

# File Path
51 nads/src/threat_classifier.cpp
52 nads/src/[Link]
53 nads/src/volume_detector.cpp
54 nads/tests/run_tests.cpp
55 nads/tests/test_adaptive_stats.cpp
56 nads/tests/test_classifier.cpp
57 nads/tests/test_correlation.cpp
58 nads/tests/test_entropy.cpp

Page 16 of 629
NADS Complete Technical Reference

# File Path
59 nads/tests/test_flow_table.cpp
60 nads/tests/test_fusion.cpp
61 nads/tests/test_graph_detector.cpp
62 nads/tests/test_parser.cpp
63 nads/tests/test_protocol_analyzer.cpp
64 nads/tests/test_runner.h
65 nads/tests/test_running_stats.cpp
66 nads/tests/test_stat_detector.cpp
67 nads/tests/test_temporal_detector.cpp
68 nads/benchmarks/bench_capture.cpp
69 nads/tools/train_fusion.py
70 nads/[Link]
71 nads/fusion_weights.txt
72 nads/[Link]
73 webwireshark/src/lib/[Link]
74 webwireshark/src/lib/[Link]
75 webwireshark/src/lib/[Link]
76 webwireshark/src/lib/[Link]
77 webwireshark/src/store/[Link]
78 webwireshark/src/pages/[Link]
79 webwireshark/src/pages/[Link]
80 webwireshark/src/pages/[Link]
81 webwireshark/src/pages/[Link]
82 webwireshark/src/pages/[Link]
83 webwireshark/src/pages/[Link]
84 webwireshark/src/pages/[Link]
85 webwireshark/src/pages/[Link]
86 webwireshark/src/components/layout/[Link]
87 webwireshark/src/components/layout/[Link]
88 webwireshark/src/components/layout/[Link]
89 webwireshark/src/components/layout/[Link]
90 webwireshark/src/[Link]
91 webwireshark/src/[Link]

File: nads/include/advanced_detectors.h
Total lines: 33

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).

Page 17 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


2 `` Blank line for Separator between code blocks.
readability.
3 `#include "detector_interface.h"` Import another header #include "detector_interface.h"
file into this
compilation unit.
4 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
5 `#include <deque>` Import another header #include <deque>
file into this
compilation unit.
6 `#include <mutex>` Import another header #include <mutex>
file into this
compilation unit.
7 `#include <unordered_map>` Import another header #include <unordered_map>
file into this
compilation unit.
8 `#include <unordered_set>` Import another header #include <unordered_set>
file into this
compilation unit.
9 `` Blank line for Separator between code blocks.
readability.
10 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
11 `` Blank line for Separator between code blocks.
readability.
12 `class AdvancedDetectors {` Source code line. class AdvancedDetectors {
13 `public:` Source code line. public:
14 ` explicit AdvancedDetectors(const Named constant — explicit AdvancedDetectors(const
Config& cfg);` value should not Config& cfg);
change.
15 `` Blank line for Separator between code blocks.
readability.
16 ` std::vector<DetectorResult> Build or return a score 0-1, flags, detail string.
analyze_flow(const FlowRecord& detector score result.
flow);`
17 ` DetectorResult on_packet(const Build or return a score 0-1, flags, detail string.
PacketInfo& pkt);` detector score result.
18 `` Blank line for Separator between code blocks.
readability.
19 `private:` Source code line. private:
20 ` const Config& cfg_;` Named constant — const Config& cfg_;
value should not
change.
21 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
22 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
std::unordered_set<uint16_t>> std::unordered_set<uint16_t>>
host_ports_seen_;` host_ports_seen_;
23 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
uint64_t> host_syn_;` uint64_t> host_syn_;

Page 18 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


24 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
uint64_t> host_ack_;` uint64_t> host_ack_;
25 `` Blank line for Separator between code blocks.
readability.
26 ` DetectorResult slow_scan(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow);` detector score result.
27 ` DetectorResult burst(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow);` detector score result.
28 ` DetectorResult long_lived(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow);` detector score result.
29 ` DetectorResult dns_tunnel(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow, const PacketInfo* detector score result.
pkt_hint);`
30 ` DetectorResult syn_ratio(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow);` detector score result.
31 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
32 `` Blank line for Separator between code blocks.
readability.
33 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/alert_system.h
Total lines: 40

Line Source Easy Explanation Technical Explanation


1 `// alert_system.h - Module 13: Alert Comment alert_system.h - Module 13: Alert
output (console + log + JSON), with documenting intent. output (console + log + JSON), with
cooldown.` cooldown.
2 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
3 `` Blank line for Separator between code blocks.
readability.
4 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
5 `#include <unordered_map>` Import another header #include <unordered_map>
file into this
compilation unit.
6 `#include <mutex>` Import another header #include <mutex>
file into this
compilation unit.
7 `#include <fstream>` Import another header #include <fstream>
file into this
compilation unit.

Page 19 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


8 `#include <deque>` Import another header #include <deque>
file into this
compilation unit.
9 `` Blank line for Separator between code blocks.
readability.
10 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
11 `` Blank line for Separator between code blocks.
readability.
12 `class AlertSystem {` Source code line. class AlertSystem {
13 `public:` Source code line. public:
14 ` AlertSystem(const std::string& Named constant — AlertSystem(const std::string&
log_path, const std::string& json_path);` value should not log_path, const std::string&
change. json_path);
15 ` ~AlertSystem();` Executable statement. ~AlertSystem();
16 `` Blank line for Separator between code blocks.
readability.
17 ` // Returns true if alert was emitted Comment Returns true if alert was emitted (false
(false = suppressed by cooldown)` documenting intent. = suppressed by cooldown)
18 ` bool send(const AnomalyEvent& Final alert record sent Enterprise alert struct.
ev);` to logs and UI.
19 `` Blank line for Separator between code blocks.
readability.
20 ` // For dashboard` Comment For dashboard
documenting intent.
21 ` std::deque<AnomalyEvent> Final alert record sent Enterprise alert struct.
recent(size_t n = 10) const;` to logs and UI.
22 `` Blank line for Separator between code blocks.
readability.
23 ` void shutdown();` Executable statement. void shutdown();
24 `` Blank line for Separator between code blocks.
readability.
25 `private:` Source code line. private:
26 ` bool should_alert(uint32_t src_ip, Named constant — bool should_alert(uint32_t src_ip,
const std::string& attack_type, int64_t value should not const std::string& attack_type, int64_t
now_us);` change. now_u
27 ` int cooldown_for(const std::string& Named constant — int cooldown_for(const std::string&
attack_type) const;` value should not attack_type) const;
change.
28 ` void write_log(const Final alert record sent Enterprise alert struct.
AnomalyEvent& ev);` to logs and UI.
29 ` void write_json(const Final alert record sent Enterprise alert struct.
AnomalyEvent& ev);` to logs and UI.
30 `` Blank line for Separator between code blocks.
readability.
31 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
32 ` std::unordered_map<uint64_t, Executable statement. std::unordered_map<uint64_t, int64_t>
int64_t> last_alert_us_;` last_alert_us_;

Page 20 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


33 ` std::ofstream log_out_;` Executable statement. std::ofstream log_out_;
34 ` std::ofstream json_out_;` Executable statement. std::ofstream json_out_;
35 ` bool first_json_ = true;` Executable statement. bool first_json_ = true;
36 ` std::deque<AnomalyEvent> Final alert record sent Enterprise alert struct.
recent_;` to logs and UI.
37 ` static constexpr size_t Named constant — static constexpr size_t MAX_RECENT
MAX_RECENT = 50;` value should not = 50;
change.
38 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
39 `` Blank line for Separator between code blocks.
readability.
40 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/baseline_engine.h
Total lines: 73

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
2 `` Blank line for Separator between code blocks.
readability.
3 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
4 `#include "running_stats.h"` Import another header #include "running_stats.h"
file into this compilation
unit.
5 `#include <unordered_map>` Import another header #include <unordered_map>
file into this compilation
unit.
6 `#include <unordered_set>` Import another header #include <unordered_set>
file into this compilation
unit.
7 `#include <mutex>` Import another header #include <mutex>
file into this compilation
unit.
8 `` Blank line for Separator between code blocks.
readability.
9 `namespace nads {` Start a named code namespace nads {
region so names do not
clash globally.
10 `` Blank line for Separator between code blocks.
readability.

Page 21 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


11 `struct ServiceProfile {` Source code line. struct ServiceProfile {
12 ` uint16_t port = 0;` Executable statement. uint16_t port = 0;
13 ` uint8_t protocol = 0;` Executable statement. uint8_t protocol = 0;
14 ` EwmaStats bps;` Executable statement. EwmaStats bps;
15 ` EwmaStats mean_pkt_size;` Executable statement. EwmaStats mean_pkt_size;
16 ` RingBufferPercentile pkt_size_ring;` Executable statement. RingBufferPercentile pkt_size_ring;
17 ` uint64_t flow_count = 0;` Executable statement. uint64_t flow_count = 0;
18 ` int64_t first_seen_us = 0;` Executable statement. int64_t first_seen_us = 0;
19 ` int64_t last_seen_us = 0;` Executable statement. int64_t last_seen_us = 0;
20 `` Blank line for Separator between code blocks.
readability.
21 ` ServiceProfile(double alpha, size_t Source code line. ServiceProfile(double alpha, size_t
window)` window)
22 ` : bps(alpha), Source code line. : bps(alpha), mean_pkt_size(alpha),
mean_pkt_size(alpha), pkt_size_ring(window) {}
pkt_size_ring(window) {}`
23 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
24 `` Blank line for Separator between code blocks.
readability.
25 `struct HostProfile {` Source code line. struct HostProfile {
26 ` uint32_t ip = 0;` Executable statement. uint32_t ip = 0;
27 ` int64_t first_seen_us = 0;` Executable statement. int64_t first_seen_us = 0;
28 ` int64_t last_seen_us = 0;` Executable statement. int64_t last_seen_us = 0;
29 `` Blank line for Separator between code blocks.
readability.
30 ` RunningStats outbound_bps;` Executable statement. RunningStats outbound_bps;
31 ` RunningStats inbound_bps;` Executable statement. RunningStats inbound_bps;
32 ` RunningStats mean_flow_duration;` Executable statement. RunningStats mean_flow_duration;
33 ` RunningStats mean_pkt_size;` Executable statement. RunningStats mean_pkt_size;
34 `` Blank line for Separator between code blocks.
readability.
35 ` EwmaStats ewma_bps;` Executable statement. EwmaStats ewma_bps;
36 ` EwmaStats ewma_pkt_size;` Executable statement. EwmaStats ewma_pkt_size;
37 `` Blank line for Separator between code blocks.
readability.
38 ` std::unordered_set<uint16_t> Executable statement. std::unordered_set<uint16_t>
known_dst_ports;` known_dst_ports;
39 ` std::unordered_set<uint32_t> Executable statement. std::unordered_set<uint32_t>
known_peers;` known_peers;
40 ` std::unordered_map<uint16_t, Executable statement. std::unordered_map<uint16_t,
ServiceProfile> services;` ServiceProfile> services;
41 `` Blank line for Separator between code blocks.
readability.

Page 22 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


42 ` uint32_t connections_total = 0;` Executable statement. uint32_t connections_total = 0;
43 ` uint32_t new_peers_this_hour = 0;` Executable statement. uint32_t new_peers_this_hour = 0;
44 ` int64_t hour_window_start_us = 0;` Executable statement. int64_t hour_window_start_us = 0;
45 `` Blank line for Separator between code blocks.
readability.
46 ` uint64_t observations() const { Named constant — uint64_t observations() const { return
return outbound_bps.count(); }` value should not outbound_bps.count(); }
change.
47 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
48 `` Blank line for Separator between code blocks.
readability.
49 `class BaselineEngine {` Source code line. class BaselineEngine {
50 `public:` Source code line. public:
51 ` explicit BaselineEngine(const Named constant — explicit BaselineEngine(const Config&
Config& cfg = Config{});` value should not cfg = Config{});
change.
52 `` Blank line for Separator between code blocks.
readability.
53 ` DetectorResult analyze(const Build or return a score 0-1, flags, detail string.
FlowRecord& flow);` detector score result.
54 `` Blank line for Separator between code blocks.
readability.
55 ` size_t hosts() const {` Named constant — size_t hosts() const {
value should not
change.
56 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lock(mtx_);` one thread uses shared
data at a time.
57 ` return hosts_.size();` Exit function and give return hosts_.size();
back a value.
58 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
59 `` Blank line for Separator between code blocks.
readability.
60 ` static constexpr uint64_t MIN_OBS Named constant — static constexpr uint64_t MIN_OBS =
= 30;` value should not 30;
change.
61 `` Blank line for Separator between code blocks.
readability.
62 `private:` Source code line. private:
63 ` Config cfg_;` Executable statement. Config cfg_;
64 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
65 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
HostProfile> hosts_;` HostProfile> hosts_;
66 `` Blank line for Separator between code blocks.
readability.

Page 23 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


67 ` double score_host(HostProfile& p, Named constant — double score_host(HostProfile& p,
const FlowRecord& flow, uint32_t value should not const FlowRecord& flow, uint32_t
peer_ip,` change. peer_ip,
68 ` std::vector<std::string>& Executable statement. std::vector<std::string>& flags);
flags);`
69 ` double Named constant — double score_service(ServiceProfile&
score_service(ServiceProfile& sp, value should not sp, const FlowRecord& flow,
const FlowRecord& flow,` change.
70 ` Executable statement. std::vector<std::string>& flags);
std::vector<std::string>& flags);`
71 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
72 `` Blank line for Separator between code blocks.
readability.
73 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/capture.h
Total lines: 61

Line Source Easy Explanation Technical Explanation


1 `// capture.h - Module 1: Packet Comment capture.h - Module 1: Packet Capture
Capture Layer` documenting intent. Layer
2 `// Wraps libpcap with a clean callback Comment Wraps libpcap with a clean callback
that pushes PacketInfo onto a queue.` documenting intent. that pushes PacketInfo onto a queue.
3 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
4 `` Blank line for Separator between code blocks.
readability.
5 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
6 `#include "concurrent_queue.h"` Import another header #include "concurrent_queue.h"
file into this
compilation unit.
7 `#include <atomic>` Import another header #include <atomic>
file into this
compilation unit.
8 `#include <thread>` Import another header #include <thread>
file into this
compilation unit.
9 `#include <string>` Import another header #include <string>
file into this
compilation unit.
10 `` Blank line for Separator between code blocks.
readability.

Page 24 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


11 `// Forward declarations to avoid pulling Comment Forward declarations to avoid pulling
pcap.h into every TU` documenting intent. pcap.h into every TU
12 `struct pcap;` Executable statement. struct pcap;
13 `typedef struct pcap pcap_t;` libpcap network typedef struct pcap pcap_t;
capture API call.
14 `struct pcap_pkthdr;` libpcap network struct pcap_pkthdr;
capture API call.
15 `` Blank line for Separator between code blocks.
readability.
16 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
17 `` Blank line for Separator between code blocks.
readability.
18 `class PacketCapture {` Source code line. class PacketCapture {
19 `public:` Source code line. public:
20 ` PacketCapture(const std::string& Named constant — PacketCapture(const std::string&
interface,` value should not interface,
change.
21 ` const std::string& Named constant — const std::string& bpf_filter,
bpf_filter,` value should not
change.
22 ` Source code line. ConcurrentQueue<PacketInfo>&
ConcurrentQueue<PacketInfo>& out_queue,
out_queue,`
23 ` LiveStats& stats);` Executable statement. LiveStats& stats);
24 ` ~PacketCapture();` Executable statement. ~PacketCapture();
25 `` Blank line for Separator between code blocks.
readability.
26 ` // Open device and apply filter. Comment Open device and apply filter. Returns
Returns false on failure (errmsg filled).` documenting intent. false on failure (errmsg filled).
27 ` bool open();` Executable statement. bool open();
28 `` Blank line for Separator between code blocks.
readability.
29 ` // Run capture loop in a background Comment Run capture loop in a background
thread. Non-blocking.` documenting intent. thread. Non-blocking.
30 ` void start();` Executable statement. void start();
31 `` Blank line for Separator between code blocks.
readability.
32 ` // Signal loop to stop and join Comment Signal loop to stop and join thread.
thread.` documenting intent.
33 ` void stop();` Executable statement. void stop();
34 `` Blank line for Separator between code blocks.
readability.
35 ` // Replay a PCAP file instead of live Comment Replay a PCAP file instead of live
capture (for testing)` documenting intent. capture (for testing)
36 ` bool open_pcap_file(const libpcap network bool open_pcap_file(const std::string&
std::string& path);` capture API call. path);

Page 25 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


37 `` Blank line for Separator between code blocks.
readability.
38 ` const std::string& last_error() const { Named constant — const std::string& last_error() const {
return last_error_; }` value should not return last_error_; }
change.
39 `` Blank line for Separator between code blocks.
readability.
40 ` bool is_running() const { return Thread-safe update or std::memory_order relaxed typical.
running_.load(); }` read of a statistic.
41 `` Blank line for Separator between code blocks.
readability.
42 `private:` Source code line. private:
43 ` static void packet_callback(unsigned Source code line. static void packet_callback(unsigned
char* user,` char* user,
44 ` const libpcap network const pcap_pkthdr* hdr,
pcap_pkthdr* hdr,` capture API call.
45 ` const unsigned Named constant — const unsigned char* bytes);
char* bytes);` value should not
change.
46 `` Blank line for Separator between code blocks.
readability.
47 ` void capture_loop();` Executable statement. void capture_loop();
48 `` Blank line for Separator between code blocks.
readability.
49 ` std::string interface_;` Executable statement. std::string interface_;
50 ` std::string bpf_filter_;` Executable statement. std::string bpf_filter_;
51 ` ConcurrentQueue<PacketInfo>& Executable statement. ConcurrentQueue<PacketInfo>&
queue_;` queue_;
52 ` LiveStats& stats_;` Executable statement. LiveStats& stats_;
53 `` Blank line for Separator between code blocks.
readability.
54 ` pcap_t* handle_ = nullptr;` libpcap network pcap_t* handle_ = nullptr;
capture API call.
55 ` std::atomic<bool> running_{false};` Counter safe to Lock-free atomic variable.
read/write from
multiple threads.
56 ` std::thread thread_;` Executable statement. std::thread thread_;
57 ` std::string last_error_;` Executable statement. std::string last_error_;
58 ` int link_type_ = 0;` Executable statement. int link_type_ = 0;
59 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
60 `` Blank line for Separator between code blocks.
readability.
61 `} // namespace nads` End of nads } // namespace nads
namespace.

Page 26 of 629
NADS Complete Technical Reference

File: nads/include/concurrent_queue.h
Total lines: 61

Line Source Easy Technical Explanation


Explanation
1 `// concurrent_queue.h - Simple thread- Comment concurrent_queue.h - Simple thread-safe
safe bounded queue (MPSC-friendly)` documenting bounded queue (MPSC-friendly)
intent.
2 `#pragma once` Compiler directive #pragma once
(packing, once,
etc.).
3 `` Blank line for Separator between code blocks.
readability.
4 `#include <queue>` Import another #include <queue>
header file into
this compilation
unit.
5 `#include <mutex>` Import another #include <mutex>
header file into
this compilation
unit.
6 `#include <condition_variable>` Import another #include <condition_variable>
header file into
this compilation
unit.
7 `#include <atomic>` Import another #include <atomic>
header file into
this compilation
unit.
8 `` Blank line for Separator between code blocks.
readability.
9 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
10 `` Blank line for Separator between code blocks.
readability.
11 `template <typename T>` Source code line. template <typename T>
12 `class ConcurrentQueue {` Source code line. class ConcurrentQueue {
13 `public:` Source code line. public:
14 ` explicit ConcurrentQueue(size_t Source code line. explicit ConcurrentQueue(size_t
max_size = 100000) : max_size = 100000) :
max_size_(max_size) {}` max_size_(max_size) {}
15 `` Blank line for Separator between code blocks.
readability.
16 ` bool push(T&& item) {` Source code line. bool push(T&& item) {
17 ` std::unique_lock<std::mutex> Executable std::unique_lock<std::mutex> lock(mtx_);
lock(mtx_);` statement.
18 ` if (q_.size() >= max_size_) {` Conditional if (q_.size() >= max_size_) {
branch — run

Page 27 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
code only when
condition true.
19 ` ++dropped_;` Executable ++dropped_;
statement.
20 ` return false;` Exit function and return false;
give back a value.
21 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
22 ` q_.push(std::move(item));` Executable q_.push(std::move(item));
statement.
23 ` cv_.notify_one();` Executable cv_.notify_one();
statement.
24 ` return true;` Exit function and return true;
give back a value.
25 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
26 `` Blank line for Separator between code blocks.
readability.
27 ` bool pop(T& out, int timeout_ms = Source code line. bool pop(T& out, int timeout_ms = 100) {
100) {`
28 ` std::unique_lock<std::mutex> Executable std::unique_lock<std::mutex> lock(mtx_);
lock(mtx_);` statement.
29 ` if (!cv_.wait_for(lock, Conditional if (!cv_.wait_for(lock,
std::chrono::milliseconds(timeout_ms),` branch — run std::chrono::milliseconds(timeout_ms),
code only when
condition true.
30 ` [this] { return !q_.empty() \ stopped_; })) {`
\
31 ` return false;` Exit function and return false;
give back a value.
32 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
33 ` if (q_.empty()) return false;` Conditional if (q_.empty()) return false;
branch — run
code only when
condition true.
34 ` out = std::move(q_.front());` Executable out = std::move(q_.front());
statement.
35 ` q_.pop();` Executable q_.pop();
statement.
36 ` return true;` Exit function and return true;
give back a value.
37 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 28 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
38 `` Blank line for Separator between code blocks.
readability.
39 ` void stop() {` Source code line. void stop() {
40 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared data
at a time.
41 ` stopped_ = true;` Executable stopped_ = true;
statement.
42 ` cv_.notify_all();` Executable cv_.notify_all();
statement.
43 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
44 `` Blank line for Separator between code blocks.
readability.
45 ` size_t size() const {` Named constant size_t size() const {
— value should
not change.
46 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared data
at a time.
47 ` return q_.size();` Exit function and return q_.size();
give back a value.
48 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
49 `` Blank line for Separator between code blocks.
readability.
50 ` uint64_t dropped() const { return Thread-safe std::memory_order relaxed typical.
dropped_.load(); }` update or read of
a statistic.
51 `` Blank line for Separator between code blocks.
readability.
52 `private:` Source code line. private:
53 ` mutable std::mutex mtx_;` Executable mutable std::mutex mtx_;
statement.
54 ` std::condition_variable cv_;` Executable std::condition_variable cv_;
statement.
55 ` std::queue<T> q_;` Executable std::queue<T> q_;
statement.
56 ` size_t max_size_;` Executable size_t max_size_;
statement.
57 ` bool stopped_ = false;` Executable bool stopped_ = false;
statement.

Page 29 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
58 ` std::atomic<uint64_t> dropped_{0};` Counter safe to Lock-free atomic variable.
read/write from
multiple threads.
59 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
60 `` Blank line for Separator between code blocks.
readability.
61 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/config_loader.h
Total lines: 11

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
2 `` Blank line for readability. Separator between code blocks.
3 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
4 `#include <string>` Import another header file #include <string>
into this compilation unit.
5 `` Blank line for readability. Separator between code blocks.
6 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
7 `` Blank line for readability. Separator between code blocks.
8 `bool load_config_file(Config& cfg, Named constant — value bool load_config_file(Config& cfg,
const std::string& path);` should not change. const std::string& path);
9 `bool validate_config(const Config& Named constant — value bool validate_config(const Config&
cfg, std::string* err = nullptr);` should not change. cfg, std::string* err = nullptr);
10 `` Blank line for readability. Separator between code blocks.
11 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/console_display.h
Total lines: 45

Page 30 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `// console_display.h - Module 14: Live Comment console_display.h - Module 14: Live
ANSI terminal dashboard.` documenting intent. ANSI terminal dashboard.
2 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
3 `` Blank line for Separator between code blocks.
readability.
4 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
5 `#include "alert_system.h"` Import another header #include "alert_system.h"
file into this
compilation unit.
6 `#include <atomic>` Import another header #include <atomic>
file into this
compilation unit.
7 `#include <thread>` Import another header #include <thread>
file into this
compilation unit.
8 `#include <deque>` Import another header #include <deque>
file into this
compilation unit.
9 `#include <mutex>` Import another header #include <mutex>
file into this
compilation unit.
10 `` Blank line for Separator between code blocks.
readability.
11 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
12 `` Blank line for Separator between code blocks.
readability.
13 `class ConsoleDisplay {` Source code line. class ConsoleDisplay {
14 `public:` Source code line. public:
15 ` ConsoleDisplay(LiveStats& stats, Named constant — ConsoleDisplay(LiveStats& stats,
AlertSystem& alerts, const Config& value should not AlertSystem& alerts, const Config&
cfg);` change. cfg);
16 ` ~ConsoleDisplay();` Executable statement. ~ConsoleDisplay();
17 `` Blank line for Separator between code blocks.
readability.
18 ` void start();` Executable statement. void start();
19 ` void stop();` Executable statement. void stop();
20 `` Blank line for Separator between code blocks.
readability.
21 ` // Push a sample for the bandwidth Comment Push a sample for the bandwidth
sparkline (called once per second from documenting intent. sparkline (called once per second from
orchestrator).` orchestrator).
22 ` void push_bps_sample(double Executable statement. void push_bps_sample(double bps);
bps);`
23 `` Blank line for Separator between code blocks.
readability.

Page 31 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


24 ` // Update top-talkers map (src_ip -> Comment Update top-talkers map (src_ip -> total
total bytes)` documenting intent. bytes)
25 ` void update_top_talker(uint32_t Executable statement. void update_top_talker(uint32_t src_ip,
src_ip, uint64_t bytes_added);` uint64_t bytes_added);
26 `` Blank line for Separator between code blocks.
readability.
27 `private:` Source code line. private:
28 ` void run();` Executable statement. void run();
29 ` void clear_screen();` Executable statement. void clear_screen();
30 ` void move_cursor(int row, int col);` Executable statement. void move_cursor(int row, int col);
31 ` void render_frame();` Executable statement. void render_frame();
32 `` Blank line for Separator between code blocks.
readability.
33 ` LiveStats& stats_;` Executable statement. LiveStats& stats_;
34 ` AlertSystem& alerts_;` Executable statement. AlertSystem& alerts_;
35 ` const Config& cfg_;` Named constant — const Config& cfg_;
value should not
change.
36 ` std::atomic<bool> running_{false};` Counter safe to Lock-free atomic variable.
read/write from
multiple threads.
37 ` std::thread thread_;` Executable statement. std::thread thread_;
38 `` Blank line for Separator between code blocks.
readability.
39 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
40 ` std::deque<double> bps_samples_;` Executable statement. std::deque<double> bps_samples_;
41 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
uint64_t> top_talkers_;` uint64_t> top_talkers_;
42 ` static constexpr size_t SPARK_LEN Named constant — static constexpr size_t SPARK_LEN =
= 60;` value should not 60;
change.
43 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
44 `` Blank line for Separator between code blocks.
readability.
45 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/correlation_engine.h
Total lines: 36

Page 32 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
2 `` Blank line for Separator between code blocks.
readability.
3 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
4 `#include <deque>` Import another header #include <deque>
file into this compilation
unit.
5 `#include <mutex>` Import another header #include <mutex>
file into this compilation
unit.
6 `#include <string>` Import another header #include <string>
file into this compilation
unit.
7 `#include <unordered_map>` Import another header #include <unordered_map>
file into this compilation
unit.
8 `#include <unordered_set>` Import another header #include <unordered_set>
file into this compilation
unit.
9 `` Blank line for Separator between code blocks.
readability.
10 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
11 `` Blank line for Separator between code blocks.
readability.
12 `struct DetectorHit {` Source code line. struct DetectorHit {
13 ` std::string detector;` Executable statement. std::string detector;
14 ` double score = 0.0;` Executable statement. double score = 0.0;
15 ` int64_t timestamp_us = 0;` Executable statement. int64_t timestamp_us = 0;
16 ` uint32_t src_ip = 0;` Executable statement. uint32_t src_ip = 0;
17 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
18 `` Blank line for Separator between code blocks.
readability.
19 `class CorrelationEngine {` Source code line. class CorrelationEngine {
20 `public:` Source code line. public:
21 ` explicit CorrelationEngine(int Executable statement. explicit CorrelationEngine(int
window_sec = 30);` window_sec = 30);
22 `` Blank line for Separator between code blocks.
readability.
23 ` void record(uint32_t src_ip, const Build or return a score 0-1, flags, detail string.
DetectorResult& r, int64_t now_us);` detector score result.
24 ` double correlation_boost(uint32_t Executable statement. double correlation_boost(uint32_t
src_ip, int64_t now_us) const;` src_ip, int64_t now_us) const;

Page 33 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


25 ` std::string Executable statement. std::string last_correlation_id(uint32_t
last_correlation_id(uint32_t src_ip) src_ip) const;
const;`
26 `` Blank line for Separator between code blocks.
readability.
27 `private:` Source code line. private:
28 ` int window_us_;` Executable statement. int window_us_;
29 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
30 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
std::deque<DetectorHit>> by_src_;` std::deque<DetectorHit>> by_src_;
31 ` mutable Executable statement. mutable std::unordered_map<uint32_t,
std::unordered_map<uint32_t, std::string> correlation_ids_;
std::string> correlation_ids_;`
32 `` Blank line for Separator between code blocks.
readability.
33 ` void Executable statement. void prune(std::deque<DetectorHit>&
prune(std::deque<DetectorHit>& q, q, int64_t now_us) const;
int64_t now_us) const;`
34 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
35 `` Blank line for Separator between code blocks.
readability.
36 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/detector_interface.h
Total lines: 15

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive (packing, once, #pragma once
etc.).
2 `` Blank line for readability. Separator between code
blocks.
3 `#include "types.h"` Import another header file into this #include "types.h"
compilation unit.
4 `` Blank line for readability. Separator between code
blocks.
5 `namespace nads {` Start a named code region so namespace nads {
names do not clash globally.
6 `` Blank line for readability. Separator between code
blocks.
7 `class IDetector {` Source code line. class IDetector {
8 `public:` Source code line. public:
9 ` virtual ~IDetector() = default;` Executable statement. virtual ~IDetector() = default;

Page 34 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


10 ` virtual std::string name() const = Named constant — value should virtual std::string name()
0;` not change. const = 0;
11 ` virtual DetectorResult Build or return a detector score score 0-1, flags, detail string.
on_flow(const FlowRecord& flow) = result.
0;`
12 ` virtual bool enabled(const Named constant — value should virtual bool enabled(const
Config& cfg) const = 0;` not change. Config& cfg) const = 0;
13 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
14 `` Blank line for readability. Separator between code
blocks.
15 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/entropy_profiler.h
Total lines: 17

Line Source Easy Explanation Technical Explanation


1 `// entropy_profiler.h - Module 10: Comment documenting entropy_profiler.h - Module 10:
Shannon Entropy of payload bytes.` intent. Shannon Entropy of payload bytes.
2 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
3 `` Blank line for readability. Separator between code blocks.
4 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
5 `` Blank line for readability. Separator between code blocks.
6 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
7 `` Blank line for readability. Separator between code blocks.
8 `class EntropyProfiler {` Source code line. class EntropyProfiler {
9 `public:` Source code line. public:
10 ` // Compute Shannon entropy from Comment documenting Compute Shannon entropy from a
a byte histogram.` intent. byte histogram.
11 ` static double shannon(const Named constant — value static double shannon(const
std::array<uint64_t, 256>& hist, should not change. std::array<uint64_t, 256>& hist,
uint64_t total);` uint64_t total);
12 `` Blank line for readability. Separator between code blocks.
13 ` // Score a flow's entropy: high Comment documenting Score a flow's entropy: high entropy
entropy on plaintext ports = intent. on plaintext ports = suspicious.
suspicious.`
14 ` DetectorResult score(const Build or return a detector score 0-1, flags, detail string.
FlowRecord& flow);` score result.
15 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.

Page 35 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


16 `` Blank line for readability. Separator between code blocks.
17 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/flow_table.h
Total lines: 49

Line Source Easy Explanation Technical Explanation


1 `// flow_table.h - Module 3: Flow Table Comment flow_table.h - Module 3: Flow Table &
& Aggregator` documenting intent. Aggregator
2 `// Groups packets by 5-tuple, tracks Comment Groups packets by 5-tuple, tracks flow
flow features, expires old flows.` documenting intent. features, expires old flows.
3 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
4 `` Blank line for Separator between code blocks.
readability.
5 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
6 `#include <unordered_map>` Import another header #include <unordered_map>
file into this
compilation unit.
7 `#include <mutex>` Import another header #include <mutex>
file into this
compilation unit.
8 `#include <vector>` Import another header #include <vector>
file into this
compilation unit.
9 `` Blank line for Separator between code blocks.
readability.
10 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
11 `` Blank line for Separator between code blocks.
readability.
12 `class FlowTable {` Source code line. class FlowTable {
13 `public:` Source code line. public:
14 ` FlowTable(int flow_timeout_sec = Executable statement. FlowTable(int flow_timeout_sec = 60);
60);`
15 `` Blank line for Separator between code blocks.
readability.
16 ` // Update or create flow record for a Comment Update or create flow record for a
packet. Returns reference for caller documenting intent. packet. Returns reference for caller
use.` use.
17 ` // Also detects "new edge" for graph Comment Also detects "new edge" for graph
detector by setting *is_new_flow.` documenting intent. detector by setting *is_new_flow.

Page 36 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


18 ` FlowRecord& touch(const Named constant — FlowRecord& touch(const PacketInfo&
PacketInfo& pkt, bool* is_new_flow = value should not pkt, bool* is_new_flow = nullptr);
nullptr);` change.
19 `` Blank line for Separator between code blocks.
readability.
20 ` // Sweep flows that haven't seen Comment Sweep flows that haven't seen traffic in
traffic in flow_timeout. Returns expired documenting intent. flow_timeout. Returns expired flows.
flows.`
21 ` std::vector<FlowRecord> Executable statement. std::vector<FlowRecord>
sweep_expired(int64_t now_us);` sweep_expired(int64_t now_us);
22 `` Blank line for Separator between code blocks.
readability.
23 ` // Compute features (rates, mean, Comment Compute features (rates, mean,
stddev, entropy) for a flow.` documenting intent. stddev, entropy) for a flow.
24 ` static void Executable statement. static void
compute_features(FlowRecord& r);` compute_features(FlowRecord& r);
25 `` Blank line for Separator between code blocks.
readability.
26 ` size_t size() const {` Named constant — size_t size() const {
value should not
change.
27 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lock(mtx_);` one thread uses
shared data at a time.
28 ` return flows_.size();` Exit function and give return flows_.size();
back a value.
29 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
30 `` Blank line for Separator between code blocks.
readability.
31 ` // Returns a thread-safe snapshot of Comment Returns a thread-safe snapshot of all
all current flows` documenting intent. current flows
32 ` std::vector<FlowRecord> Named constant — std::vector<FlowRecord>
get_all_flows() const {` value should not get_all_flows() const {
change.
33 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lock(mtx_);` one thread uses
shared data at a time.
34 ` std::vector<FlowRecord> snap;` Executable statement. std::vector<FlowRecord> snap;
35 ` [Link](flows_.size());` Executable statement. [Link](flows_.size());
36 ` for (auto& [k, v] : flows_) Loop over items or for (auto& [k, v] : flows_)
snap.push_back(v);` until condition snap.push_back(v);
changes.
37 ` return snap;` Exit function and give return snap;
back a value.
38 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
39 `` Blank line for Separator between code blocks.
readability.

Page 37 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


40 `private:` Source code line. private:
41 ` // Normalize key so A->B == B->A Comment Normalize key so A->B == B->A
(always store smaller IP as src)` documenting intent. (always store smaller IP as src)
42 ` static FlowKey normalize_key(const Named constant — static FlowKey normalize_key(const
PacketInfo& pkt);` value should not PacketInfo& pkt);
change.
43 `` Blank line for Separator between code blocks.
readability.
44 ` std::unordered_map<FlowKey, Executable statement. std::unordered_map<FlowKey,
FlowRecord, FlowKeyHash> flows_;` FlowRecord, FlowKeyHash> flows_;
45 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
46 ` int64_t timeout_us_;` Executable statement. int64_t timeout_us_;
47 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
48 `` Blank line for Separator between code blocks.
readability.
49 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/fusion_engine.h
Total lines: 23

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
2 `` Blank line for readability. Separator between code
blocks.
3 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
4 `#include "logistic_fusion.h"` Import another header file #include "logistic_fusion.h"
into this compilation unit.
5 `#include <memory>` Import another header file #include <memory>
into this compilation unit.
6 `#include <vector>` Import another header file #include <vector>
into this compilation unit.
7 `` Blank line for readability. Separator between code
blocks.
8 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
9 `` Blank line for readability. Separator between code
blocks.
10 `class FusionEngine {` Source code line. class FusionEngine {
11 `public:` Source code line. public:

Page 38 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


12 ` explicit FusionEngine(const Config& Named constant — value explicit FusionEngine(const
cfg);` should not change. Config& cfg);
13 ` ~FusionEngine() = default;` Executable statement. ~FusionEngine() = default;
14 `` Blank line for readability. Separator between code
blocks.
15 ` FusionResult fuse(const Build or return a detector score 0-1, flags, detail string.
std::vector<DetectorResult>& results);` score result.
16 `` Blank line for readability. Separator between code
blocks.
17 `private:` Source code line. private:
18 ` Config cfg_;` Executable statement. Config cfg_;
19 ` std::unique_ptr<LogisticFusion> Own a module object; auto- Heap object with unique
logistic_;` deleted when done. ownership.
20 ` double weight_for(const std::string& Named constant — value double weight_for(const
name) const;` should not change. std::string& name) const;
21 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
22 `` Blank line for readability. Separator between code
blocks.
23 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/graph_detector.h
Total lines: 37

Line Source Easy Explanation Technical Explanation


1 `// graph_detector.h - Module 8: Graph Comment documenting graph_detector.h - Module 8: Graph
Anomaly Detector` intent. Anomaly Detector
2 `// Tracks per-host degree (unique Comment documenting Tracks per-host degree (unique peers)
peers) and detects sudden spikes.` intent. and detects sudden spikes.
3 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
4 `` Blank line for Separator between code blocks.
readability.
5 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
6 `#include "running_stats.h"` Import another header #include "running_stats.h"
file into this compilation
unit.
7 `#include <unordered_map>` Import another header #include <unordered_map>
file into this compilation
unit.
8 `#include <unordered_set>` Import another header #include <unordered_set>
file into this compilation
unit.

Page 39 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


9 `#include <deque>` Import another header #include <deque>
file into this compilation
unit.
10 `#include <mutex>` Import another header #include <mutex>
file into this compilation
unit.
11 `` Blank line for Separator between code blocks.
readability.
12 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
13 `` Blank line for Separator between code blocks.
readability.
14 `struct GraphNode {` Source code line. struct GraphNode {
15 ` uint32_t ip = 0;` Executable statement. uint32_t ip = 0;
16 ` std::unordered_set<uint32_t> Executable statement. std::unordered_set<uint32_t>
neighbors;` neighbors;
17 ` RunningStats degree_velocity; // Source code line. RunningStats degree_velocity; // per-
per-minute new-peer rate` minute new-peer rate
18 ` std::deque<int64_t> Source code line. std::deque<int64_t>
recent_new_edges_us; // timestamps recent_new_edges_us; // timestamps
of new edges` of new edges
19 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
20 `` Blank line for Separator between code blocks.
readability.
21 `class GraphDetector {` Source code line. class GraphDetector {
22 `public:` Source code line. public:
23 ` // Returns DetectorResult; if dst is a Comment documenting Returns DetectorResult; if dst is a
brand-new peer for src, sets fields intent. brand-new peer for src, sets fields
accordingly.` accordingly.
24 ` DetectorResult Build or return a score 0-1, flags, detail string.
on_new_flow(uint32_t src_ip, uint32_t detector score result.
dst_ip, int64_t ts_us);`
25 `` Blank line for Separator between code blocks.
readability.
26 ` size_t nodes() const {` Named constant — size_t nodes() const {
value should not
change.
27 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lock(mtx_);` one thread uses
shared data at a time.
28 ` return nodes_.size();` Exit function and give return nodes_.size();
back a value.
29 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
30 `` Blank line for Separator between code blocks.
readability.

Page 40 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


31 `private:` Source code line. private:
32 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
33 ` std::unordered_map<uint32_t, Executable statement. std::unordered_map<uint32_t,
GraphNode> nodes_;` GraphNode> nodes_;
34 ` static constexpr int64_t Named constant — static constexpr int64_t WINDOW_US
WINDOW_US = 600 * 1000000LL; // value should not = 600 * 1000000LL; // 10 minutes
10 minutes` change.
35 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
36 `` Blank line for Separator between code blocks.
readability.
37 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/http_server.h
Total lines: 166

Li Source Easy Technical Explanation


n Explan
e ation
1 `#pragma once` Compile #pragma once
r
directiv
e
(packin
g, once,
etc.).
2 `` Blank Separator between code blocks.
line for
readabil
ity.
3 `#include "types.h"` Import #include "types.h"
another
header
file into
this
compila
tion
unit.
4 `#include <memory>` Import #include <memory>
another
header
file into
this
compila
tion
unit.
5 `#include <thread>` Import #include <thread>
another

Page 41 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
header
file into
this
compila
tion
unit.
6 `#include <atomic>` Import #include <atomic>
another
header
file into
this
compila
tion
unit.
7 `#include <vector>` Import #include <vector>
another
header
file into
this
compila
tion
unit.
8 `#include <deque>` Import #include <deque>
another
header
file into
this
compila
tion
unit.
9 `#include <mutex>` Import #include <mutex>
another
header
file into
this
compila
tion
unit.
10 `#include <string>` Import #include <string>
another
header
file into
this
compila
tion
unit.
11 `#include <unordered_map>` Import #include <unordered_map>
another
header
file into
this
compila
tion
unit.
12 `#include <functional>` Import #include <functional>
another
header

Page 42 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
file into
this
compila
tion
unit.
13 `#include <cstdint>` Import #include <cstdint>
another
header
file into
this
compila
tion
unit.
14 `` Blank Separator between code blocks.
line for
readabil
ity.
15 `namespace nads {` Start a namespace nads {
named
code
region
so
names
do not
clash
globally.
16 `` Blank Separator between code blocks.
line for
readabil
ity.
17 `class Orchestrator;` Executa class Orchestrator;
ble
stateme
nt.
18 `` Blank Separator between code blocks.
line for
readabil
ity.
19 `/**` Block /**
comme
nt.
20 ` * HttpServer — REST API + proper WebSocket Block * HttpServer — REST API + proper WebSocket
server for NADS.` comme server for NADS.
nt.
21 ` * Serves the frontend dashboard and pushes real- Block * Serves the frontend dashboard and pushes real-
time data via WS.` comme time data via WS.
nt.
22 ` */` Block */
comme
nt.
23 `class HttpServer {` Source class HttpServer {
code
line.

Page 43 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
24 `public:` Source public:
code
line.
25 ` explicit HttpServer(int port, Orchestrator* orch);` Executa explicit HttpServer(int port, Orchestrator* orch);
ble
stateme
nt.
26 ` ~HttpServer();` Executa ~HttpServer();
ble
stateme
nt.
27 `` Blank Separator between code blocks.
line for
readabil
ity.
28 ` bool start();` Executa bool start();
ble
stateme
nt.
29 ` void stop();` Executa void stop();
ble
stateme
nt.
30 ` bool is_running() const { return running_.load(); }` Thread- std::memory_order relaxed typical.
safe
update
or read
of a
statistic.
31 `` Blank Separator between code blocks.
line for
readabil
ity.
32 ` // Set path to built frontend dist/ folder (for static Comme Set path to built frontend dist/ folder (for static file
file serving)` nt serving)
docume
nting
intent.
33 ` void set_static_dir(const std::string& dir) { Named void set_static_dir(const std::string& dir) { static_dir_
static_dir_ = dir; }` constan = dir; }
t—
value
should
not
change.
34 `` Blank Separator between code blocks.
line for
readabil
ity.
35 ` // Called by orchestrator to push real-time data` Comme Called by orchestrator to push real-time data
nt
docume
nting
intent.

Page 44 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
36 ` void push_packet(const PacketInfo& pkt);` Named void push_packet(const PacketInfo& pkt);
constan
t—
value
should
not
change.
37 ` void push_alert(const AnomalyEvent& alert);` Final Enterprise alert struct.
alert
record
sent to
logs
and UI.
38 ` void push_stats(double pps, double bps, uint64_t Executa void push_stats(double pps, double bps, uint64_t
total);` ble total);
stateme
nt.
39 `` Blank Separator between code blocks.
line for
readabil
ity.
40 ` // Legacy compat` Comme Legacy compat
nt
docume
nting
intent.
41 ` void broadcast_packet(const PacketInfo& pkt) { Named void broadcast_packet(const PacketInfo& pkt) {
push_packet(pkt); }` constan push_packet(pkt); }
t—
value
should
not
change.
42 ` void broadcast_alert(const AnomalyEvent& alert) Final Enterprise alert struct.
{ push_alert(alert); }` alert
record
sent to
logs
and UI.
43 ` void on_stats_update() {}` Source void on_stats_update() {}
code
line.
44 `` Blank Separator between code blocks.
line for
readabil
ity.
45 `private:` Source private:
code
line.
46 ` // ── Connection state Comme ── Connection state
───────────────────────────────── nt ────────────────────────────────
───────────────────` docume ────────────────────
nting
intent.

Page 45 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
47 ` struct Client {` Source struct Client {
code
line.
48 ` int fd = -1;` Executa int fd = -1;
ble
stateme
nt.
49 ` bool upgraded = false; // WebSocket upgrade Source bool upgraded = false; // WebSocket upgrade done
done` code
line.
50 ` bool closing = false;` Executa bool closing = false;
ble
stateme
nt.
51 ` std::string rbuf; // raw read buffer` Source std::string rbuf; // raw read buffer
code
line.
52 ` };` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
53 `` Blank Separator between code blocks.
line for
readabil
ity.
54 ` // ── Data stored for REST queries Comme ── Data stored for REST queries
───────────────────────────────── nt ────────────────────────────────
────────` docume ─────────
nting
intent.
55 ` struct ThreatIpData {` Source struct ThreatIpData {
code
line.
56 ` std::string ip;` Executa std::string ip;
ble
stateme
nt.
57 ` int alertCount = 0;` Executa int alertCount = 0;
ble
stateme
nt.
58 ` double threatScore = 0.0;` Executa double threatScore = 0.0;
ble
stateme
nt.
59 ` };` Brace C/C++ syntax structure.
or
parenth
esis
closing/

Page 46 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
opening
a block.
60 `` Blank Separator between code blocks.
line for
readabil
ity.
61 ` struct TimelineBucket {` Source struct TimelineBucket {
code
line.
62 ` std::string time;` Executa std::string time;
ble
stateme
nt.
63 ` int critical = 0, high = 0, medium = 0, low = 0;` Executa int critical = 0, high = 0, medium = 0, low = 0;
ble
stateme
nt.
64 ` };` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
65 `` Blank Separator between code blocks.
line for
readabil
ity.
66 ` // ── Members Comme ── Members
───────────────────────────────── nt ────────────────────────────────
─────────────────────────────` docume ──────────────────────────────
nting
intent.
67 ` int port_;` Executa int port_;
ble
stateme
nt.
68 ` Orchestrator* orch_;` Executa Orchestrator* orch_;
ble
stateme
nt.
69 ` std::string static_dir_;` Executa std::string static_dir_;
ble
stateme
nt.
70 `` Blank Separator between code blocks.
line for
readabil
ity.
71 ` std::atomic<bool> running_{false};` Counter Lock-free atomic variable.
safe to
read/wri
te from

Page 47 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
multiple
threads.
72 ` std::unique_ptr<std::thread> server_thread_;` Own a Heap object with unique ownership.
module
object;
auto-
deleted
when
done.
73 ` int listen_fd_ = -1;` Executa int listen_fd_ = -1;
ble
stateme
nt.
74 `` Blank Separator between code blocks.
line for
readabil
ity.
75 ` // All live client connections (HTTP and WS)` Comme All live client connections (HTTP and WS)
nt
docume
nting
intent.
76 ` std::vector<std::unique_ptr<Client>> clients_;` Own a Heap object with unique ownership.
module
object;
auto-
deleted
when
done.
77 ` std::mutex clients_mtx_;` Executa std::mutex clients_mtx_;
ble
stateme
nt.
78 `` Blank Separator between code blocks.
line for
readabil
ity.
79 ` // Buffered data for REST` Comme Buffered data for REST
nt
docume
nting
intent.
80 ` std::atomic<uint64_t> pkt_counter_{0};` Counter Lock-free atomic variable.
safe to
read/wri
te from
multiple
threads.

Page 48 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
81 ` std::deque<std::string> recent_pkts_; // JSON Source std::deque<std::string> recent_pkts_; // JSON
strings` code strings
line.
82 ` std::deque<std::string> recent_alerts_; // JSON Source std::deque<std::string> recent_alerts_; // JSON
strings` code strings
line.
83 `` Blank Separator between code blocks.
line for
readabil
ity.
84 ` // Aggregated data` Comme Aggregated data
nt
docume
nting
intent.
85 ` std::unordered_map<std::string, ThreatIpData> Executa std::unordered_map<std::string, ThreatIpData>
threat_ips_;` ble threat_ips_;
stateme
nt.
86 ` std::deque<TimelineBucket> Source std::deque<TimelineBucket> timeline_;
timeline_; // last ~20 buckets` code // last ~20 buckets
line.
87 ` int64_t last_bucket_us_ = 0;` Executa int64_t last_bucket_us_ = 0;
ble
stateme
nt.
88 `` Blank Separator between code blocks.
line for
readabil
ity.
89 ` std::unordered_map<std::string, uint64_t> Executa std::unordered_map<std::string, uint64_t>
proto_pkts_;` ble proto_pkts_;
stateme
nt.
90 ` std::unordered_map<std::string, uint64_t> Executa std::unordered_map<std::string, uint64_t>
proto_bytes_;` ble proto_bytes_;
stateme
nt.
91 `` Blank Separator between code blocks.
line for
readabil
ity.
92 ` // Latest stats for WS broadcast` Comme Latest stats for WS broadcast
nt
docume
nting
intent.
93 ` double cur_pps_ = 0;` Executa double cur_pps_ = 0;
ble
stateme
nt.
94 ` double cur_bps_ = 0;` Executa double cur_bps_ = 0;
ble

Page 49 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
stateme
nt.
95 ` uint64_t total_pkts_ = 0;` Executa uint64_t total_pkts_ = 0;
ble
stateme
nt.
96 `` Blank Separator between code blocks.
line for
readabil
ity.
97 ` // I/O graph — rolling 60-second window` Comme I/O graph — rolling 60-second window
nt
docume
nting
intent.
98 ` struct IoPoint {` Source struct IoPoint {
code
line.
99 ` std::string time;` Executa std::string time;
ble
stateme
nt.
10 ` uint64_t bytes_in = 0;` Executa uint64_t bytes_in = 0;
0 ble
stateme
nt.
10 ` uint64_t bytes_out = 0;` Executa uint64_t bytes_out = 0;
1 ble
stateme
nt.
10 ` };` Brace C/C++ syntax structure.
2 or
parenth
esis
closing/
opening
a block.
10 ` std::deque<IoPoint> io_graph_; // max 60 Source std::deque<IoPoint> io_graph_; // max 60 points
3 points` code
line.
10 ` int64_t last_io_bucket_us_ = 0;` Executa int64_t last_io_bucket_us_ = 0;
4 ble
stateme
nt.
10 `` Blank Separator between code blocks.
5 line for
readabil
ity.
10 ` mutable std::mutex data_mtx_;` Executa mutable std::mutex data_mtx_;
6 ble
stateme
nt.

Page 50 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
10 ` static constexpr size_t MAX_PKTS = 500;` Named static constexpr size_t MAX_PKTS = 500;
7 constan
t—
value
should
not
change.
10 ` static constexpr size_t MAX_ALERTS = 200;` Named static constexpr size_t MAX_ALERTS = 200;
8 constan
t—
value
should
not
change.
10 `` Blank Separator between code blocks.
9 line for
readabil
ity.
11 ` // ── Server loop Comme ── Server loop
0 ───────────────────────────────── nt ────────────────────────────────
─────────────────────────` docume ──────────────────────────
nting
intent.
11 ` void server_loop();` Executa void server_loop();
1 ble
stateme
nt.
11 `` Blank Separator between code blocks.
2 line for
readabil
ity.
11 ` // ── HTTP handling Comme ── HTTP handling
3 ───────────────────────────────── nt ────────────────────────────────
────────────────────────` docume ─────────────────────────
nting
intent.
11 ` bool try_handle_http(Client& c);` Executa bool try_handle_http(Client& c);
4 ble
stateme
nt.
11 ` std::string dispatch(const std::string& method,` Named std::string dispatch(const std::string& method,
5 constan
t—
value
should
not
change.
11 ` const std::string& path,` Named const std::string& path,
6 constan
t—
value
should
not
change.

Page 51 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
11 ` const std::string& body,` Named const std::string& body,
7 constan
t—
value
should
not
change.
11 ` const std::string& full_request);` Named const std::string& full_request);
8 constan
t—
value
should
not
change.
11 ` std::string serve_static(const std::string& path);` Named std::string serve_static(const std::string& path);
9 constan
t—
value
should
not
change.
12 ` std::string make_http(int status, const std::string& Named std::string make_http(int status, const std::string&
0 ctype, const std::string& body);` constan ctype, const std::string& b
t—
value
should
not
change.
12 `` Blank Separator between code blocks.
1 line for
readabil
ity.
12 ` // API routes` Comme API routes
2 nt
docume
nting
intent.
12 ` std::string api_packets();` Executa std::string api_packets();
3 ble
stateme
nt.
12 ` std::string api_alerts();` Executa std::string api_alerts();
4 ble
stateme
nt.
12 ` std::string api_summary();` Executa std::string api_summary();
5 ble
stateme
nt.
12 ` std::string api_flows();` Executa std::string api_flows();
6 ble
stateme
nt.
12 ` std::string api_threat_timeline();` Executa std::string api_threat_timeline();
7 ble

Page 52 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
stateme
nt.
12 ` std::string api_threat_ips();` Executa std::string api_threat_ips();
8 ble
stateme
nt.
12 ` std::string api_protocol_stats();` Executa std::string api_protocol_stats();
9 ble
stateme
nt.
13 ` std::string api_capture_start();` Executa std::string api_capture_start();
0 ble
stateme
nt.
13 ` std::string api_capture_stop();` Executa std::string api_capture_stop();
1 ble
stateme
nt.
13 ` std::string api_capture_pause();` Executa std::string api_capture_pause();
2 ble
stateme
nt.
13 ` std::string api_capture_resume();` Executa std::string api_capture_resume();
3 ble
stateme
nt.
13 ` std::string api_capture_status();` Executa std::string api_capture_status();
4 ble
stateme
nt.
13 ` std::string api_interfaces();` Executa std::string api_interfaces();
5 ble
stateme
nt.
13 ` std::string api_config_get();` Executa std::string api_config_get();
6 ble
stateme
nt.
13 ` std::string api_config_save();` Executa std::string api_config_save();
7 ble
stateme
nt.
13 ` std::string api_baseline_recalc();` Executa std::string api_baseline_recalc();
8 ble
stateme
nt.
13 ` std::string api_baseline_reset();` Executa std::string api_baseline_reset();
9 ble
stateme
nt.
14 ` std::string api_io_graph();` Executa std::string api_io_graph();
0 ble

Page 53 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
stateme
nt.
14 ` std::string api_metrics();` Executa std::string api_metrics();
1 ble
stateme
nt.
14 `` Blank Separator between code blocks.
2 line for
readabil
ity.
14 ` // ── WebSocket handling Comme ── WebSocket handling
3 ───────────────────────────────── nt ────────────────────────────────
───────────────────` docume ────────────────────
nting
intent.
14 ` bool try_ws_upgrade(Client& c, const std::string& Named bool try_ws_upgrade(Client& c, const std::string&
4 request);` constan request);
t—
value
should
not
change.
14 ` void ws_send_text(Client& c, const std::string& Named void ws_send_text(Client& c, const std::string&
5 payload);` constan payload);
t—
value
should
not
change.
14 ` void ws_broadcast(const std::string& payload);` Named void ws_broadcast(const std::string& payload);
6 constan
t—
value
should
not
change.
14 ` void ws_handle_frames(Client& c);` Executa void ws_handle_frames(Client& c);
7 ble
stateme
nt.
14 `` Blank Separator between code blocks.
8 line for
readabil
ity.
14 ` // ── Helpers Comme ── Helpers
9 ───────────────────────────────── nt ────────────────────────────────
──────────────────────────────` docume ───────────────────────────────
nting
intent.
15 ` std::string build_packet_json(const PacketInfo& Named std::string build_packet_json(const PacketInfo& pkt,
0 pkt, uint64_t no);` constan uint64_t no);
t—
value
should

Page 54 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
not
change.
15 ` std::string build_alert_json(const AnomalyEvent& Final Enterprise alert struct.
1 ev);` alert
record
sent to
logs
and UI.
15 ` std::string proto_name(uint8_t proto) const;` Executa std::string proto_name(uint8_t proto) const;
2 ble
stateme
nt.
15 ` std::string format_ip(uint32_t ip_be) const;` Executa std::string format_ip(uint32_t ip_be) const;
3 ble
stateme
nt.
15 ` std::string iso_now(int64_t wall_us) const;` Executa std::string iso_now(int64_t wall_us) const;
4 ble
stateme
nt.
15 ` void update_timeline_bucket(const Final Enterprise alert struct.
5 AnomalyEvent& ev);` alert
record
sent to
logs
and UI.
15 `` Blank Separator between code blocks.
6 line for
readabil
ity.
15 ` // Crypto for WebSocket handshake` Comme Crypto for WebSocket handshake
7 nt
docume
nting
intent.
15 ` static std::string ws_accept_key(const Named static std::string ws_accept_key(const std::string&
8 std::string& client_key);` constan client_key);
t—
value
should
not
change.
15 ` static void sha1(const uint8_t* data, size_t Named static void sha1(const uint8_t* data, size_t len,
9 len, uint8_t out[20]);` constan uint8_t out[20]);
t—
value
should
not
change.
16 ` static std::string base64_encode(const uint8_t* Named static std::string base64_encode(const uint8_t* data,
0 data, size_t len);` constan size_t len);
t—
value
should

Page 55 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
not
change.

Line Source Easy Explanation Technical Explanation


161 `` Blank line for readability. Separator between code blocks.
162 ` // JSON escape` Comment documenting intent. JSON escape
163 ` static std::string json_esc(const Named constant — value should static std::string json_esc(const
std::string& s);` not change. std::string& s);
164 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
165 `` Blank line for readability. Separator between code blocks.
166 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/l7_parser.h
Total lines: 12

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
2 `` Blank line for readability. Separator between code blocks.
3 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
4 `` Blank line for readability. Separator between code blocks.
5 `namespace nads {` Start a named code namespace nads {
region so names do not
clash globally.
6 `` Blank line for readability. Separator between code blocks.
7 `// Lightweight L7 heuristics — max Comment documenting Lightweight L7 heuristics — max
inspect bytes bounded for streaming` intent. inspect bytes bounded for streaming
8 `void parse_l7_hints(PacketInfo& pkt, Executable statement. void parse_l7_hints(PacketInfo& pkt,
size_t max_inspect = 128);` size_t max_inspect = 128);
9 `` Blank line for readability. Separator between code blocks.
10 `double dns_name_entropy(const Named constant — double dns_name_entropy(const
uint8_t* data, size_t len);` value should not change. uint8_t* data, size_t len);
11 `` Blank line for readability. Separator between code blocks.
12 `} // namespace nads` End of nads namespace. } // namespace nads

Page 56 of 629
NADS Complete Technical Reference

File: nads/include/logistic_fusion.h
Total lines: 28

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
2 `` Blank line for Separator between code blocks.
readability.
3 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
4 `#include <string>` Import another header #include <string>
file into this compilation
unit.
5 `#include <unordered_map>` Import another header #include <unordered_map>
file into this compilation
unit.
6 `#include <vector>` Import another header #include <vector>
file into this compilation
unit.
7 `` Blank line for Separator between code blocks.
readability.
8 `namespace nads {` Start a named code namespace nads {
region so names do not
clash globally.
9 `` Blank line for Separator between code blocks.
readability.
10 `class LogisticFusion {` Source code line. class LogisticFusion {
11 `public:` Source code line. public:
12 ` explicit LogisticFusion(const Config& Named constant — explicit LogisticFusion(const
cfg);` value should not Config& cfg);
change.
13 `` Blank line for Separator between code blocks.
readability.
14 ` FusionResult fuse(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results);` detector score result.
15 ` void online_update(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results, bool detector score result.
label_alert);`
16 ` bool load_weights(const std::string& Named constant — bool load_weights(const
path);` value should not std::string& path);
change.
17 ` bool save_weights(const std::string& Named constant — bool save_weights(const
path) const;` value should not std::string& path) const;
change.
18 `` Blank line for Separator between code blocks.
readability.
19 `private:` Source code line. private:
20 ` double bias_ = -0.8;` Executable statement. double bias_ = -0.8;

Page 57 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


21 ` std::unordered_map<std::string, Executable statement. std::unordered_map<std::string,
double> weights_;` double> weights_;
22 ` double lr_;` Executable statement. double lr_;
23 `` Blank line for Separator between code blocks.
readability.
24 ` double sigmoid(double z) const Named constant — double sigmoid(double z) const
noexcept;` value should not noexcept;
change.
25 ` double dot(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results) detector score result.
const;`
26 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
27 `` Blank line for Separator between code blocks.
readability.
28 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/metrics_registry.h
Total lines: 27

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
2 `` Blank line for Separator between code blocks.
readability.
3 `#include <mutex>` Import another header #include <mutex>
file into this
compilation unit.
4 `#include <string>` Import another header #include <string>
file into this
compilation unit.
5 `#include <unordered_map>` Import another header #include <unordered_map>
file into this
compilation unit.
6 `` Blank line for Separator between code blocks.
readability.
7 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
8 `` Blank line for Separator between code blocks.
readability.
9 `class MetricsRegistry {` Source code line. class MetricsRegistry {
10 `public:` Source code line. public:
11 ` static MetricsRegistry& instance();` Executable statement. static MetricsRegistry& instance();

Page 58 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


12 `` Blank line for Separator between code blocks.
readability.
13 ` void inc(const std::string& name, Named constant — void inc(const std::string& name,
double by = 1.0);` value should not double by = 1.0);
change.
14 ` void set_gauge(const std::string& Named constant — void set_gauge(const std::string&
name, double value);` value should not name, double value);
change.
15 ` void set_labeled_gauge(const Named constant — void set_labeled_gauge(const
std::string& name, const std::string& value should not std::string& name, const std::string&
label_key,` change. label_key,
16 ` const std::string& Named constant — const std::string& label_val, double
label_val, double value);` value should not value);
change.
17 ` std::string render() const;` Executable statement. std::string render() const;
18 `` Blank line for Separator between code blocks.
readability.
19 `private:` Source code line. private:
20 ` MetricsRegistry() = default;` Executable statement. MetricsRegistry() = default;
21 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
22 ` std::unordered_map<std::string, Executable statement. std::unordered_map<std::string,
double> counters_;` double> counters_;
23 ` std::unordered_map<std::string, Executable statement. std::unordered_map<std::string,
double> gauges_;` double> gauges_;
24 ` std::unordered_map<std::string, Executable statement. std::unordered_map<std::string,
double> labeled_gauges_;` double> labeled_gauges_;
25 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
26 `` Blank line for Separator between code blocks.
readability.
27 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/object_pool.h
Total lines: 36

Line Source Easy Technical Explanation


Explanation
1 `#pragma once` Compiler directive #pragma once
(packing, once,
etc.).
2 `` Blank line for Separator between code blocks.
readability.
3 `#include <vector>` Import another #include <vector>
header file into

Page 59 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
this compilation
unit.
4 `#include <mutex>` Import another #include <mutex>
header file into
this compilation
unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `// Simple thread-safe object pool for hot-path Comment Simple thread-safe object pool for
reuse` documenting hot-path reuse
intent.
9 `template<typename T>` Source code line. template<typename T>
10 `class ObjectPool {` Source code line. class ObjectPool {
11 `public:` Source code line. public:
12 ` explicit ObjectPool(size_t prealloc = 64) {` Source code line. explicit ObjectPool(size_t prealloc
= 64) {
13 ` pool_.reserve(prealloc);` Executable pool_.reserve(prealloc);
statement.
14 ` for (size_t i = 0; i < prealloc; ++i) Own a module Heap object with unique
pool_.emplace_back(std::make_unique<T>());` object; auto- ownership.
deleted when
done.
15 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
16 `` Blank line for Separator between code blocks.
readability.
17 ` std::unique_ptr<T> acquire() {` Own a module Heap object with unique
object; auto- ownership.
deleted when
done.
18 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex so RAII mutex lock.
only one thread
uses shared data
at a time.
19 ` if (pool_.empty()) return Own a module Heap object with unique
std::make_unique<T>();` object; auto- ownership.
deleted when
done.
20 ` auto obj = std::move(pool_.back());` Executable auto obj =
statement. std::move(pool_.back());
21 ` pool_.pop_back();` Executable pool_.pop_back();
statement.

Page 60 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
22 ` return obj;` Exit function and return obj;
give back a value.
23 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
24 `` Blank line for Separator between code blocks.
readability.
25 ` void release(std::unique_ptr<T> obj) {` Own a module Heap object with unique
object; auto- ownership.
deleted when
done.
26 ` if (!obj) return;` Conditional if (!obj) return;
branch — run
code only when
condition true.
27 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex so RAII mutex lock.
only one thread
uses shared data
at a time.
28 ` pool_.push_back(std::move(obj));` Executable pool_.push_back(std::move(obj));
statement.
29 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
30 `` Blank line for Separator between code blocks.
readability.
31 `private:` Source code line. private:
32 ` std::mutex mtx_;` Executable std::mutex mtx_;
statement.
33 ` std::vector<std::unique_ptr<T>> pool_;` Own a module Heap object with unique
object; auto- ownership.
deleted when
done.
34 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
35 `` Blank line for Separator between code blocks.
readability.
36 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/orchestrator.h
Total lines: 103

Page 61 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
1 `// orchestrator.h - Module 15: Master Comment orchestrator.h - Module 15: Master
controller. Wires everything together.` documenting controller. Wires everything together.
intent.
2 `#pragma once` Compiler directive #pragma once
(packing, once,
etc.).
3 `` Blank line for Separator between code blocks.
readability.
4 `#include "types.h"` Import another #include "types.h"
header file into this
compilation unit.
5 `#include "concurrent_queue.h"` Import another #include "concurrent_queue.h"
header file into this
compilation unit.
6 `#include "capture.h"` Import another #include "capture.h"
header file into this
compilation unit.
7 `#include "parser.h"` Import another #include "parser.h"
header file into this
compilation unit.
8 `#include "flow_table.h"` Import another #include "flow_table.h"
header file into this
compilation unit.
9 `#include "stat_detector.h"` Import another #include "stat_detector.h"
header file into this
compilation unit.
10 `#include "volume_detector.h"` Import another #include "volume_detector.h"
header file into this
compilation unit.
11 `#include "protocol_analyzer.h"` Import another #include "protocol_analyzer.h"
header file into this
compilation unit.
12 `#include "baseline_engine.h"` Import another #include "baseline_engine.h"
header file into this
compilation unit.
13 `#include "graph_detector.h"` Import another #include "graph_detector.h"
header file into this
compilation unit.
14 `#include "temporal_detector.h"` Import another #include "temporal_detector.h"
header file into this
compilation unit.
15 `#include "entropy_profiler.h"` Import another #include "entropy_profiler.h"
header file into this
compilation unit.
16 `#include "threat_classifier.h"` Import another #include "threat_classifier.h"
header file into this
compilation unit.
17 `#include "fusion_engine.h"` Import another #include "fusion_engine.h"
header file into this
compilation unit.

Page 62 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
18 `#include "correlation_engine.h"` Import another #include "correlation_engine.h"
header file into this
compilation unit.
19 `#include "advanced_detectors.h"` Import another #include "advanced_detectors.h"
header file into this
compilation unit.
20 `#include "alert_system.h"` Import another #include "alert_system.h"
header file into this
compilation unit.
21 `#include "console_display.h"` Import another #include "console_display.h"
header file into this
compilation unit.
22 `#include "http_server.h"` Import another #include "http_server.h"
header file into this
compilation unit.
23 `` Blank line for Separator between code blocks.
readability.
24 `#include <atomic>` Import another #include <atomic>
header file into this
compilation unit.
25 `#include <thread>` Import another #include <thread>
header file into this
compilation unit.
26 `#include <memory>` Import another #include <memory>
header file into this
compilation unit.
27 `#include <unordered_map>` Import another #include <unordered_map>
header file into this
compilation unit.
28 `#include <mutex>` Import another #include <mutex>
header file into this
compilation unit.
29 `` Blank line for Separator between code blocks.
readability.
30 `namespace nads` Start a named namespace nads
code region so
names do not
clash globally.
31 `{` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
32 `` Blank line for Separator between code blocks.
readability.
33 ` class Orchestrator` Source code line. class Orchestrator
34 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
35 ` public:` Source code line. public:

Page 63 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
36 ` explicit Orchestrator(const Config Named constant — explicit Orchestrator(const Config &cfg);
&cfg);` value should not
change.
37 ` ~Orchestrator();` Executable ~Orchestrator();
statement.
38 `` Blank line for Separator between code blocks.
readability.
39 ` bool start();` Executable bool start();
statement.
40 ` void stop();` Executable void stop();
statement.
41 ` void wait();` Executable void wait();
statement.
42 ` void print_summary();` Executable void print_summary();
statement.
43 `` Blank line for Separator between code blocks.
readability.
44 ` const std::string &last_error() const Named constant — const std::string &last_error() const {
{ return last_error_; }` value should not return last_error_; }
change.
45 ` const Config &config() const { return Named constant — const Config &config() const { return
cfg_; }` value should not cfg_; }
change.
46 ` const LiveStats &live_stats() const { Named constant — const LiveStats &live_stats() const {
return stats_; }` value should not return stats_; }
change.
47 `` Blank line for Separator between code blocks.
readability.
48 ` uint64_t stats_active_flows() const { Thread-safe std::memory_order relaxed typical.
return stats_.active_flows.load(); }` update or read of a
statistic.
49 ` uint64_t stats_alerts_total() const { Thread-safe std::memory_order relaxed typical.
return stats_.alerts_total.load(); }` update or read of a
statistic.
50 ` uint64_t stats_completed_flows() Thread-safe std::memory_order relaxed typical.
const { return update or read of a
stats_.completed_flows.load(); }` statistic.
51 ` double stats_pps() const { return Thread-safe std::memory_order relaxed typical.
stats_.current_pps.load(); }` update or read of a
statistic.
52 ` double stats_bps() const { return Thread-safe std::memory_order relaxed typical.
stats_.current_bps.load(); }` update or read of a
statistic.
53 ` uint64_t stats_total_packets() const Thread-safe std::memory_order relaxed typical.
{ return update or read of a
stats_.total_packets_captured.load(); }` statistic.
54 `` Blank line for Separator between code blocks.
readability.
55 ` std::vector<FlowRecord> Executable std::vector<FlowRecord>
get_flow_snapshot() const;` statement. get_flow_snapshot() const;

Page 64 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
56 `` Blank line for Separator between code blocks.
readability.
57 ` bool is_capturing() const { return Named constant — bool is_capturing() const { return
!capture_paused_; }` value should not !capture_paused_; }
change.
58 ` void pause_capture() { Source code line. void pause_capture() {
capture_paused_ = true; }` capture_paused_ = true; }
59 ` void resume_capture() { Source code line. void resume_capture() {
capture_paused_ = false; }` capture_paused_ = false; }
60 `` Blank line for Separator between code blocks.
readability.
61 ` private:` Source code line. private:
62 ` void analysis_loop();` Executable void analysis_loop();
statement.
63 ` void sweeper_loop();` Executable void sweeper_loop();
statement.
64 ` void rate_sampler_loop();` Executable void rate_sampler_loop();
statement.
65 ` void Executable void
process_completed_flow(FlowRecord statement. process_completed_flow(FlowRecord
flow);` flow);
66 ` void update_metrics(double pps, Executable void update_metrics(double pps, double
double bps);` statement. bps);
67 `` Blank line for Separator between code blocks.
readability.
68 ` Config cfg_;` Executable Config cfg_;
statement.
69 ` LiveStats stats_;` Executable LiveStats stats_;
statement.
70 ` ConcurrentQueue<PacketInfo> Executable ConcurrentQueue<PacketInfo> queue_;
queue_;` statement.
71 `` Blank line for Separator between code blocks.
readability.
72 ` std::unique_ptr<PacketCapture> Own a module Heap object with unique ownership.
capture_;` object; auto-
deleted when
done.
73 ` std::unique_ptr<PacketParser> Own a module Heap object with unique ownership.
parser_;` object; auto-
deleted when
done.
74 ` std::unique_ptr<FlowTable> Own a module Heap object with unique ownership.
flow_table_;` object; auto-
deleted when
done.
75 ` std::unique_ptr<StatisticalDetector> Own a module Heap object with unique ownership.
stat_det_;` object; auto-
deleted when
done.

Page 65 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
76 ` std::unique_ptr<VolumeDetector> Own a module Heap object with unique ownership.
volume_det_;` object; auto-
deleted when
done.
77 ` std::unique_ptr<ProtocolAnalyzer> Own a module Heap object with unique ownership.
proto_det_;` object; auto-
deleted when
done.
78 ` std::unique_ptr<BaselineEngine> Own a module Heap object with unique ownership.
baseline_;` object; auto-
deleted when
done.
79 ` std::unique_ptr<GraphDetector> Own a module Heap object with unique ownership.
graph_det_;` object; auto-
deleted when
done.
80 ` std::unique_ptr<TemporalDetector> Own a module Heap object with unique ownership.
temporal_det_;` object; auto-
deleted when
done.

Line Source Easy Explanation Technical Explanation


81 ` std::unique_ptr<EntropyProfiler> Own a module object; Heap object with unique ownership.
entropy_det_;` auto-deleted when
done.
82 ` std::unique_ptr<ThreatClassifier> Own a module object; Heap object with unique ownership.
classifier_;` auto-deleted when
done.
83 ` std::unique_ptr<FusionEngine> Own a module object; Heap object with unique ownership.
fusion_;` auto-deleted when
done.
84 ` std::unique_ptr<CorrelationEngine> Own a module object; Heap object with unique ownership.
correlation_;` auto-deleted when
done.
85 ` std::unique_ptr<AdvancedDetectors> Own a module object; Heap object with unique ownership.
advanced_;` auto-deleted when
done.
86 ` std::unique_ptr<AlertSystem> Own a module object; Heap object with unique ownership.
alerts_;` auto-deleted when
done.
87 ` std::unique_ptr<ConsoleDisplay> Own a module object; Heap object with unique ownership.
display_;` auto-deleted when
done.
88 ` std::unique_ptr<HttpServer> Own a module object; Heap object with unique ownership.
http_server_;` auto-deleted when
done.
89 `` Blank line for Separator between code blocks.
readability.
90 ` std::atomic<bool> running_{false};` Counter safe to Lock-free atomic variable.
read/write from
multiple threads.

Page 66 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


91 ` std::atomic<bool> Counter safe to Lock-free atomic variable.
capture_paused_{false};` read/write from
multiple threads.
92 ` uint64_t pkt_broadcast_counter_ = Executable uint64_t pkt_broadcast_counter_ =
0;` statement. 0;
93 ` int64_t last_volume_alert_us_ = 0;` Executable int64_t last_volume_alert_us_ = 0;
statement.
94 ` std::unordered_map<uint32_t, Executable std::unordered_map<uint32_t,
uint64_t> second_pkt_counts_;` statement. uint64_t> second_pkt_counts_;
95 ` int64_t last_second_ = 0;` Executable int64_t last_second_ = 0;
statement.
96 ` mutable std::mutex Executable mutable std::mutex
second_counts_mutex_;` statement. second_counts_mutex_;
97 ` std::thread analysis_thread_;` Executable std::thread analysis_thread_;
statement.
98 ` std::thread sweeper_thread_;` Executable std::thread sweeper_thread_;
statement.
99 ` std::thread sampler_thread_;` Executable std::thread sampler_thread_;
statement.
100 ` std::string last_error_;` Executable std::string last_error_;
statement.
101 ` };` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
102 `` Blank line for Separator between code blocks.
readability.
103 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/parser.h
Total lines: 24

Line Source Easy Explanation Technical Explanation


1 `// parser.h - Module 2: Packet Parser` Comment documenting parser.h - Module 2: Packet Parser
intent.
2 `// Zero-copy parsing of Ethernet / IP / Comment documenting Zero-copy parsing of Ethernet / IP /
TCP / UDP headers.` intent. TCP / UDP headers.
3 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
4 `` Blank line for readability. Separator between code blocks.
5 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
6 `` Blank line for readability. Separator between code blocks.

Page 67 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


7 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
8 `` Blank line for readability. Separator between code blocks.
9 `class PacketParser {` Source code line. class PacketParser {
10 `public:` Source code line. public:
11 ` explicit PacketParser(int link_type Source code line. explicit PacketParser(int link_type =
= 1 /*DLT_EN10MB*/) : 1 /*DLT_EN10MB*/) :
link_type_(link_type) {}` link_type_(link_type) {}
12 `` Blank line for readability. Separator between code blocks.
13 ` // Returns true if packet is a valid Comment documenting Returns true if packet is a valid IPv4
IPv4 TCP/UDP/ICMP that we can intent. TCP/UDP/ICMP that we can
process.` process.
14 ` // Fills pkt.src_ip, dst_ip, ports, Comment documenting Fills pkt.src_ip, dst_ip, ports,
protocol, tcp_flags, payload_size, intent. protocol, tcp_flags, payload_size,
payload_offset, valid.` payload_offset, valid.
15 ` bool parse(PacketInfo& pkt);` Executable statement. bool parse(PacketInfo& pkt);
16 `` Blank line for readability. Separator between code blocks.
17 ` // Set link type (1 = Ethernet, 0 = Comment documenting Set link type (1 = Ethernet, 0 =
Loopback / null)` intent. Loopback / null)
18 ` void set_link_type(int lt) { Source code line. void set_link_type(int lt) { link_type_
link_type_ = lt; }` = lt; }
19 `` Blank line for readability. Separator between code blocks.
20 `private:` Source code line. private:
21 ` int link_type_;` Executable statement. int link_type_;
22 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
23 `` Blank line for readability. Separator between code blocks.
24 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/protocol_analyzer.h
Total lines: 15

Line Source Easy Explanation Technical Explanation


1 `// protocol_analyzer.h - Module 6: Comment documenting protocol_analyzer.h - Module 6:
Protocol Behavior Analyzer` intent. Protocol Behavior Analyzer
2 `// Detects: SYN flood pattern, NULL Comment documenting Detects: SYN flood pattern, NULL
scan, XMAS scan, port scan, RST intent. scan, XMAS scan, port scan, RST
flood,` flood,
3 `// DNS abnormalities.` Comment documenting DNS abnormalities.
intent.
4 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).

Page 68 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


5 `` Blank line for readability. Separator between code blocks.
6 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
7 `` Blank line for readability. Separator between code blocks.
8 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
9 `` Blank line for readability. Separator between code blocks.
10 `class ProtocolAnalyzer {` Source code line. class ProtocolAnalyzer {
11 `public:` Source code line. public:
12 ` DetectorResult analyze(const Build or return a detector score 0-1, flags, detail string.
FlowRecord& flow);` score result.
13 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
14 `` Blank line for readability. Separator between code blocks.
15 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/running_stats.h
Total lines: 168

Line Source Easy Explanation Technical Explanation


1 `// running_stats.h - Welford, EWMA, Comment documenting running_stats.h - Welford, EWMA,
rolling percentiles, adaptive baselines` intent. rolling percentiles, adaptive baselines
2 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
3 `` Blank line for readability. Separator between code blocks.
4 `#include <algorithm>` Import another header #include <algorithm>
file into this compilation
unit.
5 `#include <cmath>` Import another header #include <cmath>
file into this compilation
unit.
6 `#include <cstdint>` Import another header #include <cstdint>
file into this compilation
unit.
7 `#include <vector>` Import another header #include <vector>
file into this compilation
unit.
8 `` Blank line for readability. Separator between code blocks.
9 `namespace nads {` Start a named code namespace nads {
region so names do not
clash globally.
10 `` Blank line for readability. Separator between code blocks.
11 `class RunningStats {` Source code line. class RunningStats {

Page 69 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


12 `public:` Source code line. public:
13 ` void update(double x) {` Source code line. void update(double x) {
14 ` ++count_;` Executable statement. ++count_;
15 ` double delta = x - mean_;` Executable statement. double delta = x - mean_;
16 ` mean_ += delta / Executable statement. mean_ += delta /
static_cast<double>(count_);` static_cast<double>(count_);
17 ` double delta2 = x - mean_;` Executable statement. double delta2 = x - mean_;
18 ` m2_ += delta * delta2;` Executable statement. m2_ += delta * delta2;
19 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
20 `` Blank line for readability. Separator between code blocks.
21 ` void reset() {` Source code line. void reset() {
22 ` count_ = 0;` Executable statement. count_ = 0;
23 ` mean_ = 0.0;` Executable statement. mean_ = 0.0;
24 ` m2_ = 0.0;` Executable statement. m2_ = 0.0;
25 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
26 `` Blank line for readability. Separator between code blocks.
27 ` uint64_t count() const { return Named constant — uint64_t count() const { return count_;
count_; }` value should not }
change.
28 ` double mean() const { return Named constant — double mean() const { return
mean_; }` value should not mean_; }
change.
29 ` double variance() const {` Named constant — double variance() const {
value should not
change.
30 ` return count_ > 1 ? m2_ / Exit function and give return count_ > 1 ? m2_ /
static_cast<double>(count_ - 1) : 0.0;` back a value. static_cast<double>(count_ - 1) : 0.0;
31 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
32 ` double stddev() const { return Named constant — double stddev() const { return
std::sqrt(variance()); }` value should not std::sqrt(variance()); }
change.
33 `` Blank line for readability. Separator between code blocks.
34 ` double zscore(double x) const {` Compare value to Z-score or normalized score.
learned baseline
statistically.
35 ` double sd = stddev();` Executable statement. double sd = stddev();
36 ` if (sd < 1e-9) return 0.0;` Conditional branch — if (sd < 1e-9) return 0.0;
run code only when
condition true.
37 ` return (x - mean_) / sd;` Exit function and give return (x - mean_) / sd;
back a value.
38 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
39 `` Blank line for readability. Separator between code blocks.

Page 70 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


40 ` bool ready(uint64_t min_n = 30) Named constant — bool ready(uint64_t min_n = 30) const
const { return count_ >= min_n; }` value should not { return count_ >= min_n; }
change.
41 `` Blank line for readability. Separator between code blocks.
42 `private:` Source code line. private:
43 ` uint64_t count_ = 0;` Executable statement. uint64_t count_ = 0;
44 ` double mean_ = 0.0;` Executable statement. double mean_ = 0.0;
45 ` double m2_ = 0.0;` Executable statement. double m2_ = 0.0;
46 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
47 `` Blank line for readability. Separator between code blocks.
48 `// EWMA mean/variance — O(1) per Comment documenting EWMA mean/variance — O(1) per
update, suited to non-stationary traffic` intent. update, suited to non-stationary traffic
49 `class EwmaStats {` Source code line. class EwmaStats {
50 `public:` Source code line. public:
51 ` EwmaStats() noexcept : Source code line. EwmaStats() noexcept : alpha_(0.05)
alpha_(0.05) {}` {}
52 ` explicit EwmaStats(double alpha) : Source code line. explicit EwmaStats(double alpha) :
alpha_(alpha) {}` alpha_(alpha) {}
53 `` Blank line for readability. Separator between code blocks.
54 ` void set_alpha(double a) noexcept Source code line. void set_alpha(double a) noexcept {
{`
55 ` alpha_ = std::clamp(a, 0.001, Executable statement. alpha_ = std::clamp(a, 0.001, 1.0);
1.0);`
56 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
57 `` Blank line for readability. Separator between code blocks.
58 ` void update(double x) noexcept {` Source code line. void update(double x) noexcept {
59 ` if (!init_) {` Conditional branch — if (!init_) {
run code only when
condition true.
60 ` mean_ = x;` Executable statement. mean_ = x;
61 ` var_ = 0.0;` Executable statement. var_ = 0.0;
62 ` init_ = true;` Executable statement. init_ = true;
63 ` ++n_;` Executable statement. ++n_;
64 ` return;` Exit function and give return;
back a value.
65 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
66 ` double d = x - mean_;` Executable statement. double d = x - mean_;
67 ` mean_ += alpha_ * d;` Executable statement. mean_ += alpha_ * d;
68 ` var_ = (1.0 - alpha_) * (var_ + Executable statement. var_ = (1.0 - alpha_) * (var_ + alpha_
alpha_ * d * d);` * d * d);
69 ` ++n_;` Executable statement. ++n_;
70 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.

Page 71 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


71 `` Blank line for readability. Separator between code blocks.
72 ` void reset() noexcept {` Source code line. void reset() noexcept {
73 ` init_ = false;` Executable statement. init_ = false;
74 ` n_ = 0;` Executable statement. n_ = 0;
75 ` mean_ = var_ = 0.0;` Executable statement. mean_ = var_ = 0.0;
76 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
77 `` Blank line for readability. Separator between code blocks.
78 ` uint64_t count() const noexcept { Named constant — uint64_t count() const noexcept {
return n_; }` value should not return n_; }
change.
79 ` double mean() const noexcept { Named constant — double mean() const noexcept {
return mean_; }` value should not return mean_; }
change.
80 ` double variance() const noexcept { Named constant — double variance() const noexcept {
return var_; }` value should not return var_; }
change.

Line Source Easy Technical Explanation


Explanation
81 ` double stddev() const noexcept { Named constant double stddev() const noexcept { return
return std::sqrt(std::max(0.0, var_)); }` — value should std::sqrt(std::max(0.0, var_)); }
not change.
82 `` Blank line for Separator between code blocks.
readability.
83 ` double zscore(double x) const Compare value to Z-score or normalized score.
noexcept {` learned baseline
statistically.
84 ` double sd = stddev();` Executable double sd = stddev();
statement.
85 ` if (sd < 1e-9) return 0.0;` Conditional branch if (sd < 1e-9) return 0.0;
— run code only
when condition
true.
86 ` return (x - mean_) / sd;` Exit function and return (x - mean_) / sd;
give back a value.
87 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
88 `` Blank line for Separator between code blocks.
readability.
89 ` bool ready(uint64_t min_n = 10) const Named constant bool ready(uint64_t min_n = 10) const
noexcept { return n_ >= min_n; }` — value should noexcept { return n_ >= min_n; }
not change.
90 `` Blank line for Separator between code blocks.
readability.
91 `private:` Source code line. private:
92 ` double alpha_;` Executable double alpha_;
statement.

Page 72 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
93 ` bool init_ = false;` Executable bool init_ = false;
statement.
94 ` uint64_t n_ = 0;` Executable uint64_t n_ = 0;
statement.
95 ` double mean_ = 0.0;` Executable double mean_ = 0.0;
statement.
96 ` double var_ = 0.0;` Executable double var_ = 0.0;
statement.
97 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
98 `` Blank line for Separator between code blocks.
readability.
99 `// Fixed ring buffer; percentile via Comment Fixed ring buffer; percentile via
nth_element on snapshot (O(n) on score documenting nth_element on snapshot (O(n) on score
only)` intent. only)
100 `class RingBufferPercentile {` Source code line. class RingBufferPercentile {
101 `public:` Source code line. public:
102 ` explicit RingBufferPercentile(size_t Source code line. explicit RingBufferPercentile(size_t
capacity = 256)` capacity = 256)
103 ` : cap_(capacity ? capacity : 256), Source code line. : cap_(capacity ? capacity : 256),
buf_(cap_, 0.0) {}` buf_(cap_, 0.0) {}
104 `` Blank line for Separator between code blocks.
readability.
105 ` void update(double x) noexcept {` Source code line. void update(double x) noexcept {
106 ` buf_[head_] = x;` Executable buf_[head_] = x;
statement.
107 ` head_ = (head_ + 1) % cap_;` Executable head_ = (head_ + 1) % cap_;
statement.
108 ` if (size_ < cap_) ++size_;` Conditional branch if (size_ < cap_) ++size_;
— run code only
when condition
true.
109 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
110 `` Blank line for Separator between code blocks.
readability.
111 ` double percentile(double p) const {` Named constant double percentile(double p) const {
— value should
not change.
112 ` if (size_ == 0) return 0.0;` Conditional branch if (size_ == 0) return 0.0;
— run code only
when condition
true.
113 ` p = std::clamp(p, 0.0, 1.0);` Executable p = std::clamp(p, 0.0, 1.0);
statement.

Page 73 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
114 ` std::vector<double> snap;` Executable std::vector<double> snap;
statement.
115 ` [Link](size_);` Executable [Link](size_);
statement.
116 ` for (size_t i = 0; i < size_; ++i) {` Loop over items or for (size_t i = 0; i < size_; ++i) {
until condition
changes.
117 ` size_t idx = (head_ + cap_ - size_ Executable size_t idx = (head_ + cap_ - size_ + i) %
+ i) % cap_;` statement. cap_;
118 ` snap.push_back(buf_[idx]);` Executable snap.push_back(buf_[idx]);
statement.
119 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
120 ` size_t k = static_cast<size_t>(p * Executable size_t k = static_cast<size_t>(p *
static_cast<double>([Link]() - 1));` statement. static_cast<double>([Link]() - 1));
121 ` std::nth_element([Link](), Executable std::nth_element([Link](),
[Link]() + statement. [Link]() +
static_cast<std::ptrdiff_t>(k), [Link]());` static_cast<std::ptrdiff_t>(k),
[Link]());
122 ` return snap[k];` Exit function and return snap[k];
give back a value.
123 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
124 `` Blank line for Separator between code blocks.
readability.
125 ` size_t size() const noexcept { return Named constant size_t size() const noexcept { return
size_; }` — value should size_; }
not change.
126 ` void reset() noexcept { head_ = size_ Source code line. void reset() noexcept { head_ = size_ =
= 0; }` 0; }
127 `` Blank line for Separator between code blocks.
readability.
128 `private:` Source code line. private:
129 ` size_t cap_;` Executable size_t cap_;
statement.
130 ` size_t head_ = 0;` Executable size_t head_ = 0;
statement.
131 ` size_t size_ = 0;` Executable size_t size_ = 0;
statement.
132 ` std::vector<double> buf_;` Executable std::vector<double> buf_;
statement.
133 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 74 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
134 `` Blank line for Separator between code blocks.
readability.
135 `inline double normalize_z(double z, Compare value to Z-score or normalized score.
double threshold = 3.0) {` learned baseline
statistically.
136 ` double absz = std::fabs(z);` Executable double absz = std::fabs(z);
statement.
137 ` if (absz <= 0.0) return 0.0;` Conditional branch if (absz <= 0.0) return 0.0;
— run code only
when condition
true.
138 ` return std::min(1.0, absz / threshold);` Exit function and return std::min(1.0, absz / threshold);
give back a value.
139 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
140 `` Blank line for Separator between code blocks.
readability.
141 `// Combines EWMA z-score with Comment Combines EWMA z-score with
exceedance above rolling percentile documenting exceedance above rolling percentile
band` intent. band
142 `struct AdaptiveBaseline {` Source code line. struct AdaptiveBaseline {
143 ` EwmaStats ewma;` Executable EwmaStats ewma;
statement.
144 ` RingBufferPercentile ring;` Executable RingBufferPercentile ring;
statement.
145 ` double percentile_threshold = 0.95;` Executable double percentile_threshold = 0.95;
statement.
146 ` double scale = 1.15;` Executable double scale = 1.15;
statement.
147 `` Blank line for Separator between code blocks.
readability.
148 ` AdaptiveBaseline(double alpha, size_t Source code line. AdaptiveBaseline(double alpha, size_t
window)` window)
149 ` : ewma(alpha), ring(window) {}` Source code line. : ewma(alpha), ring(window) {}
150 `` Blank line for Separator between code blocks.
readability.
151 ` double score(double x, uint64_t Named constant double score(double x, uint64_t min_obs
min_obs = 10) const {` — value should = 10) const {
not change.
152 ` if ([Link]() < min_obs) return Conditional branch if ([Link]() < min_obs) return 0.0;
0.0;` — run code only
when condition
true.
153 ` double z = Compare value to Z-score or normalized score.
normalize_z([Link](x), 3.0);` learned baseline
statistically.
154 ` double p = Executable double p =
[Link](percentile_threshold);` statement. [Link](percentile_threshold);

Page 75 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
155 ` double hard = 0.0;` Executable double hard = 0.0;
statement.
156 ` if (p > 1e-9 && x > p * scale) {` Conditional branch if (p > 1e-9 && x > p * scale) {
— run code only
when condition
true.
157 ` hard = std::min(1.0, (x - p) / (p * Executable hard = std::min(1.0, (x - p) / (p * scale));
scale));` statement.
158 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
159 ` return std::max(z, hard);` Exit function and return std::max(z, hard);
give back a value.
160 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Line Source Easy Explanation Technical Explanation


161 `` Blank line for readability. Separator between code
blocks.
162 ` void observe(double x) Source code line. void observe(double x) {
{`
163 ` [Link](x);` Executable statement. [Link](x);
164 ` [Link](x);` Executable statement. [Link](x);
165 ` }` Brace or parenthesis closing/opening a C/C++ syntax structure.
block.
166 `};` Brace or parenthesis closing/opening a C/C++ syntax structure.
block.
167 `` Blank line for readability. Separator between code
blocks.
168 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/scoring_utils.h
Total lines: 29

Line Source Easy Technical Explanation


Explanation
1 `#pragma once` Compiler #pragma once
directive
(packing, once,
etc.).
2 `` Blank line for Separator between code blocks.
readability.

Page 76 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
3 `#include "running_stats.h"` Import another #include "running_stats.h"
header file into
this compilation
unit.
4 `#include "types.h"` Import another #include "types.h"
header file into
this compilation
unit.
5 `#include <algorithm>` Import another #include <algorithm>
header file into
this compilation
unit.
6 `#include <string>` Import another #include <string>
header file into
this compilation
unit.
7 `#include <vector>` Import another #include <vector>
header file into
this compilation
unit.
8 `` Blank line for Separator between code blocks.
readability.
9 `namespace nads::scoring {` Start a named namespace nads::scoring {
code region so
names do not
clash globally.
10 `` Blank line for Separator between code blocks.
readability.
11 `inline double clamp01(double v) noexcept {` Source code inline double clamp01(double v) noexcept {
line.
12 ` return std::max(0.0, std::min(1.0, v));` Exit function return std::max(0.0, std::min(1.0, v));
and give back
a value.
13 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
14 `` Blank line for Separator between code blocks.
readability.
15 `inline bool is_admin_port(uint16_t port) Source code inline bool is_admin_port(uint16_t port)
noexcept {` line. noexcept {
16 ` switch (port) {` Source code switch (port) {
line.
17 ` case 22: case 135: case 445: case Executable case 22: case 135: case 445: case 3389:
3389: case 5985: case 5986: return true;` statement. case 5985: case 5986: return true;
18 ` default: return false;` Executable default: return false;
statement.
19 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Page 77 of 629
NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
20 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
21 `` Blank line for Separator between code blocks.
readability.
22 `inline void Named inline void
append_unique_flag(std::vector<std::string>& constant — append_unique_flag(std::vector<std::string>&
flags, const std::string& f) {` value should flags, const std::strin
not change.
23 ` for (const auto& x : flags) {` Loop over for (const auto& x : flags) {
items or until
condition
changes.
24 ` if (x == f) return;` Conditional if (x == f) return;
branch — run
code only when
condition true.
25 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
26 ` flags.push_back(f);` Executable flags.push_back(f);
statement.
27 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
28 `` Blank line for Separator between code blocks.
readability.
29 `} // namespace nads::scoring` Source code } // namespace nads::scoring
line.

File: nads/include/stat_detector.h
Total lines: 32

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
2 `` Blank line for readability. Separator between code blocks.
3 `#include "types.h"` Import another header file into #include "types.h"
this compilation unit.
4 `#include "running_stats.h"` Import another header file into #include "running_stats.h"
this compilation unit.
5 `` Blank line for readability. Separator between code blocks.

Page 78 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


6 `namespace nads {` Start a named code region so namespace nads {
names do not clash globally.
7 `` Blank line for readability. Separator between code blocks.
8 `class StatisticalDetector {` Source code line. class StatisticalDetector {
9 `public:` Source code line. public:
10 ` void configure(const Config& Named constant — value void configure(const Config& cfg);
cfg);` should not change.
11 `` Blank line for readability. Separator between code blocks.
12 ` DetectorResult detect(const Build or return a detector score score 0-1, flags, detail string.
FlowRecord& flow);` result.
13 `` Blank line for readability. Separator between code blocks.
14 ` const RunningStats& bps_stats() Named constant — value const RunningStats& bps_stats()
const { return bps_legacy_; }` should not change. const { return bps_legacy_; }
15 ` const RunningStats& pps_stats() Named constant — value const RunningStats& pps_stats()
const { return pps_legacy_; }` should not change. const { return pps_legacy_; }
16 `` Blank line for readability. Separator between code blocks.
17 `private:` Source code line. private:
18 ` bool use_adaptive_ = true;` Executable statement. bool use_adaptive_ = true;
19 ` AdaptiveBaseline bps_{0.05, Executable statement. AdaptiveBaseline bps_{0.05,
256};` 256};
20 ` AdaptiveBaseline pps_{0.05, Executable statement. AdaptiveBaseline pps_{0.05,
256};` 256};
21 ` AdaptiveBaseline size_{0.05, Executable statement. AdaptiveBaseline size_{0.05,
256};` 256};
22 ` AdaptiveBaseline Executable statement. AdaptiveBaseline duration_{0.05,
duration_{0.05, 256};` 256};
23 `` Blank line for readability. Separator between code blocks.
24 ` RunningStats bps_legacy_;` Executable statement. RunningStats bps_legacy_;
25 ` RunningStats pps_legacy_;` Executable statement. RunningStats pps_legacy_;
26 ` RunningStats duration_legacy_;` Executable statement. RunningStats duration_legacy_;
27 ` RunningStats size_legacy_;` Executable statement. RunningStats size_legacy_;
28 `` Blank line for readability. Separator between code blocks.
29 ` static constexpr double Named constant — value static constexpr double
THRESHOLD = 3.0;` should not change. THRESHOLD = 3.0;
30 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
31 `` Blank line for readability. Separator between code blocks.
32 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/temporal_detector.h
Total lines: 14

Page 79 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `// temporal_detector.h - Module 9: Comment documenting intent. temporal_detector.h - Module 9:
Temporal Rhythm Detector` Temporal Rhythm Detector
2 `// Catches malware beacons - Comment documenting intent. Catches malware beacons -
perfectly regular IAT.` perfectly regular IAT.
3 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
4 `` Blank line for readability. Separator between code blocks.
5 `#include "types.h"` Import another header file into #include "types.h"
this compilation unit.
6 `` Blank line for readability. Separator between code blocks.
7 `namespace nads {` Start a named code region so namespace nads {
names do not clash globally.
8 `` Blank line for readability. Separator between code blocks.
9 `class TemporalDetector {` Source code line. class TemporalDetector {
10 `public:` Source code line. public:
11 ` DetectorResult detect(const Build or return a detector score score 0-1, flags, detail string.
FlowRecord& flow);` result.
12 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
13 `` Blank line for readability. Separator between code blocks.
14 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/threat_classifier.h
Total lines: 27

Line Source Easy Explanation Technical Explanation


1 `// threat_classifier.h - Module 11: Rule- Comment documenting threat_classifier.h - Module 11:
based attack naming.` intent. Rule-based attack naming.
2 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
3 `` Blank line for readability. Separator between code blocks.
4 `#include "types.h"` Import another header file #include "types.h"
into this compilation unit.
5 `#include <vector>` Import another header file #include <vector>
into this compilation unit.
6 `` Blank line for readability. Separator between code blocks.
7 `namespace nads {` Start a named code region namespace nads {
so names do not clash
globally.
8 `` Blank line for readability. Separator between code blocks.
9 `struct ThreatClassification {` Source code line. struct ThreatClassification {
10 ` std::string attack_type = "Unknown Executable statement. std::string attack_type =
Anomaly";` "Unknown Anomaly";

Page 80 of 629
NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


11 ` Severity severity = Severity::LOW;` Executable statement. Severity severity =
Severity::LOW;
12 ` double confidence = 0.0;` Executable statement. double confidence = 0.0;
13 ` std::string description;` Executable statement. std::string description;
14 ` std::string recommendation;` Executable statement. std::string recommendation;
15 ` std::vector<std::string> Executable statement. std::vector<std::string>
mitre_techniques;` mitre_techniques;
16 ` std::vector<std::string> Executable statement. std::vector<std::string>
mitre_tactics;` mitre_tactics;
17 ` std::vector<std::string> evidence;` Executable statement. std::vector<std::string> evidence;
18 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
19 `` Blank line for readability. Separator between code blocks.
20 `class ThreatClassifier {` Source code line. class ThreatClassifier {
21 `public:` Source code line. public:
22 ` ThreatClassification classify(const Named constant — value ThreatClassification
FlowRecord& flow,` should not change. classify(const FlowRecord& flow,
23 ` const Build or return a detector score 0-1, flags, detail string.
std::vector<DetectorResult>& results,` score result.
24 ` double Executable statement. double final_score);
final_score);`
25 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
26 `` Blank line for readability. Separator between code blocks.
27 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/include/types.h
Total lines: 336

Li Source Easy Technical Explanation


ne Explana
tion
1 `// types.h - Shared structs for the NADS system` Comment types.h - Shared structs for the NADS system
document
ing intent.
2 `// All modules include this header for common data Comment All modules include this header for common data
types` document types
ing intent.
3 `#pragma once` Compiler #pragma once
directive
(packing,
once,
etc.).

Page 81 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
4 `` Blank line Separator between code blocks.
for
readabilit
y.
5 `#include <cstdint>` Import #include <cstdint>
another
header
file into
this
compilati
on unit.
6 `#include <string>` Import #include <string>
another
header
file into
this
compilati
on unit.
7 `#include <vector>` Import #include <vector>
another
header
file into
this
compilati
on unit.
8 `#include <deque>` Import #include <deque>
another
header
file into
this
compilati
on unit.
9 `#include <unordered_set>` Import #include <unordered_set>
another
header
file into
this
compilati
on unit.
10 `#include <chrono>` Import #include <chrono>
another
header
file into
this
compilati
on unit.
11 `#include <array>` Import #include <array>
another
header
file into
this
compilati
on unit.
12 `#include <atomic>` Import #include <atomic>
another
header

Page 82 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
file into
this
compilati
on unit.
13 `` Blank line Separator between code blocks.
for
readabilit
y.
14 `namespace nads {` Start a namespace nads {
named
code
region so
names do
not clash
globally.
15 `` Blank line Separator between code blocks.
for
readabilit
y.
16 `// Comment ======================================
======================================= document ======================
=====================` ing intent.
17 `// Network Header Structures (packed to match Comment Network Header Structures (packed to match wire
wire format)` document format)
ing intent.
18 `// Comment ======================================
======================================= document ======================
=====================` ing intent.
19 `#pragma pack(push, 1)` Compiler #pragma pack(push, 1)
directive
(packing,
once,
etc.).
20 `` Blank line Separator between code blocks.
for
readabilit
y.
21 `struct EthernetHeader {` Source struct EthernetHeader {
code line.
22 ` uint8_t dest_mac[6];` Executabl uint8_t dest_mac[6];
e
statement
.
23 ` uint8_t src_mac[6];` Executabl uint8_t src_mac[6];
e
statement
.
24 ` uint16_t ether_type; // 0x0800 = IPv4, 0x86DD Source uint16_t ether_type; // 0x0800 = IPv4, 0x86DD =
= IPv6` code line. IPv6
25 `};` Brace or C/C++ syntax structure.
parenthes
is
closing/o

Page 83 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
pening a
block.
26 `` Blank line Separator between code blocks.
for
readabilit
y.
27 `struct IPHeader {` Source struct IPHeader {
code line.
28 ` uint8_t version_ihl; // 4 bits version + 4 bits Source uint8_t version_ihl; // 4 bits version + 4 bits IHL
IHL` code line.
29 ` uint8_t tos;` Executabl uint8_t tos;
e
statement
.
30 ` uint16_t total_length;` Executabl uint16_t total_length;
e
statement
.
31 ` uint16_t identification;` Executabl uint16_t identification;
e
statement
.
32 ` uint16_t flags_fragment;` Executabl uint16_t flags_fragment;
e
statement
.
33 ` uint8_t ttl;` Executabl uint8_t ttl;
e
statement
.
34 ` uint8_t protocol; // 6 = TCP, 17 = UDP, 1 = Source uint8_t protocol; // 6 = TCP, 17 = UDP, 1 =
ICMP` code line. ICMP
35 ` uint16_t checksum;` Executabl uint16_t checksum;
e
statement
.
36 ` uint32_t src_ip;` Executabl uint32_t src_ip;
e
statement
.
37 ` uint32_t dst_ip;` Executabl uint32_t dst_ip;
e
statement
.
38 `};` Brace or C/C++ syntax structure.
parenthes
is
closing/o
pening a
block.
39 `` Blank line Separator between code blocks.
for

Page 84 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
readabilit
y.
40 `struct TCPHeader {` Source struct TCPHeader {
code line.
41 ` uint16_t src_port;` Executabl uint16_t src_port;
e
statement
.
42 ` uint16_t dst_port;` Executabl uint16_t dst_port;
e
statement
.
43 ` uint32_t seq_num;` Executabl uint32_t seq_num;
e
statement
.
44 ` uint32_t ack_num;` Executabl uint32_t ack_num;
e
statement
.
45 ` uint8_t data_offset; // upper 4 bits` Source uint8_t data_offset; // upper 4 bits
code line.
46 ` uint8_t flags;` Executabl uint8_t flags;
e
statement
.
47 ` uint16_t window;` Executabl uint16_t window;
e
statement
.
48 ` uint16_t checksum;` Executabl uint16_t checksum;
e
statement
.
49 ` uint16_t urgent_ptr;` Executabl uint16_t urgent_ptr;
e
statement
.
50 `};` Brace or C/C++ syntax structure.
parenthes
is
closing/o
pening a
block.
51 `` Blank line Separator between code blocks.
for
readabilit
y.
52 `struct UDPHeader {` Source struct UDPHeader {
code line.
53 ` uint16_t src_port;` Executabl uint16_t src_port;
e

Page 85 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
statement
.
54 ` uint16_t dst_port;` Executabl uint16_t dst_port;
e
statement
.
55 ` uint16_t length;` Executabl uint16_t length;
e
statement
.
56 ` uint16_t checksum;` Executabl uint16_t checksum;
e
statement
.
57 `};` Brace or C/C++ syntax structure.
parenthes
is
closing/o
pening a
block.
58 `` Blank line Separator between code blocks.
for
readabilit
y.
59 `#pragma pack(pop)` Compiler #pragma pack(pop)
directive
(packing,
once,
etc.).
60 `` Blank line Separator between code blocks.
for
readabilit
y.
61 `// TCP flag masks` Comment TCP flag masks
document
ing intent.
62 `constexpr uint8_t TCP_FIN = 0x01;` Named constexpr uint8_t TCP_FIN = 0x01;
constant
— value
should
not
change.
63 `constexpr uint8_t TCP_SYN = 0x02;` Named constexpr uint8_t TCP_SYN = 0x02;
constant
— value
should
not
change.
64 `constexpr uint8_t TCP_RST = 0x04;` Named constexpr uint8_t TCP_RST = 0x04;
constant
— value
should
not
change.

Page 86 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
65 `constexpr uint8_t TCP_PSH = 0x08;` Named constexpr uint8_t TCP_PSH = 0x08;
constant
— value
should
not
change.
66 `constexpr uint8_t TCP_ACK = 0x10;` Named constexpr uint8_t TCP_ACK = 0x10;
constant
— value
should
not
change.
67 `constexpr uint8_t TCP_URG = 0x20;` Named constexpr uint8_t TCP_URG = 0x20;
constant
— value
should
not
change.
68 `` Blank line Separator between code blocks.
for
readabilit
y.
69 `// Protocol numbers` Comment Protocol numbers
document
ing intent.
70 `constexpr uint8_t PROTO_ICMP = 1;` Named constexpr uint8_t PROTO_ICMP = 1;
constant
— value
should
not
change.
71 `constexpr uint8_t PROTO_TCP = 6;` Named constexpr uint8_t PROTO_TCP = 6;
constant
— value
should
not
change.
72 `constexpr uint8_t PROTO_UDP = 17;` Named constexpr uint8_t PROTO_UDP = 17;
constant
— value
should
not
change.
73 `` Blank line Separator between code blocks.
for
readabilit
y.
74 `// Comment ======================================
======================================= document ======================
=====================` ing intent.
75 `// Captured Packet (zero-copy view into raw Comment Captured Packet (zero-copy view into raw buffer)
buffer)` document
ing intent.

Page 87 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
76 `// Comment ======================================
======================================= document ======================
=====================` ing intent.
77 `struct PacketInfo {` Source struct PacketInfo {
code line.
78 ` std::vector<uint8_t> raw_bytes;` Executabl std::vector<uint8_t> raw_bytes;
e
statement
.
79 ` int64_t timestamp_us;` Executabl int64_t timestamp_us;
e
statement
.
80 ` uint32_t length; // wire length` Source uint32_t length; // wire length
code line.

Li Source Easy Technical Explanation


ne Explana
tion
81 ` uint32_t cap_length; // captured length` Source uint32_t cap_length; // captured length
code line.
82 `` Blank line Separator between code blocks.
for
readabilit
y.
83 ` // Parsed fields (filled by parser)` Comment Parsed fields (filled by parser)
document
ing intent.
84 ` uint32_t src_ip = 0;` Executabl uint32_t src_ip = 0;
e
statement
.
85 ` uint32_t dst_ip = 0;` Executabl uint32_t dst_ip = 0;
e
statement
.
86 ` uint16_t src_port = 0;` Executabl uint16_t src_port = 0;
e
statement
.
87 ` uint16_t dst_port = 0;` Executabl uint16_t dst_port = 0;
e
statement
.
88 ` uint8_t protocol = 0;` Executabl uint8_t protocol = 0;
e
statement
.
89 ` uint8_t tcp_flags = 0;` Executabl uint8_t tcp_flags = 0;
e
statement
.

Page 88 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
90 ` uint16_t payload_size = 0;` Executabl uint16_t payload_size = 0;
e
statement
.
91 ` uint32_t payload_offset = 0; // offset into Byte Replaces old payload_ptr.
raw_bytes` index
where
payload
starts
inside
raw_byte
s (safe
after
move).
92 ` bool valid = false;` Executabl bool valid = false;
e
statement
.
93 `` Blank line Separator between code blocks.
for
readabilit
y.
94 ` struct L7Hints {` Source struct L7Hints {
code line.
95 ` bool is_http = false;` Executabl bool is_http = false;
e
statement
.
96 ` bool is_tls = false;` Executabl bool is_tls = false;
e
statement
.
97 ` bool is_dns = false;` Executabl bool is_dns = false;
e
statement
.
98 ` bool malformed_tls = false;` Executabl bool malformed_tls = false;
e
statement
.
99 ` bool http_on_non_standard_port = false;` Executabl bool http_on_non_standard_port = false;
e
statement
.
10 ` bool dns_tunnel_suspect = false;` Executabl bool dns_tunnel_suspect = false;
0 e
statement
.
10 ` std::string sni;` Executabl std::string sni;
1 e
statement
.
10 ` std::string ja3_placeholder;` Executabl std::string ja3_placeholder;
2 e

Page 89 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
statement
.
10 ` double dns_entropy = 0.0;` Executabl double dns_entropy = 0.0;
3 e
statement
.
10 ` } l7;` Executabl } l7;
4 e
statement
.
10 `};` Brace or C/C++ syntax structure.
5 parenthes
is
closing/o
pening a
block.
10 `` Blank line Separator between code blocks.
6 for
readabilit
y.
10 `// Comment ======================================
7 ======================================= document ======================
=====================` ing intent.
10 `// Flow Identification` Comment Flow Identification
8 document
ing intent.
10 `// Comment ======================================
9 ======================================= document ======================
=====================` ing intent.
11 `struct FlowKey {` Source struct FlowKey {
0 code line.
11 ` uint32_t src_ip;` Executabl uint32_t src_ip;
1 e
statement
.
11 ` uint32_t dst_ip;` Executabl uint32_t dst_ip;
2 e
statement
.
11 ` uint16_t src_port;` Executabl uint16_t src_port;
3 e
statement
.
11 ` uint16_t dst_port;` Executabl uint16_t dst_port;
4 e
statement
.
11 ` uint8_t protocol;` Executabl uint8_t protocol;
5 e
statement
.
11 `` Blank line Separator between code blocks.
6 for

Page 90 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
readabilit
y.
11 ` bool operator==(const FlowKey& o) const {` Named bool operator==(const FlowKey& o) const {
7 constant
— value
should
not
change.
11 ` return src_ip == o.src_ip && dst_ip == Exit return src_ip == o.src_ip && dst_ip == o.dst_ip &&
8 o.dst_ip &&` function
and give
back a
value.
11 ` src_port == o.src_port && dst_port == Source src_port == o.src_port && dst_port == o.dst_port
9 o.dst_port &&` code line. &&
12 ` protocol == [Link];` Executabl protocol == [Link];
0 e
statement
.
12 ` }` Brace or C/C++ syntax structure.
1 parenthes
is
closing/o
pening a
block.
12 `};` Brace or C/C++ syntax structure.
2 parenthes
is
closing/o
pening a
block.
12 `` Blank line Separator between code blocks.
3 for
readabilit
y.
12 `struct FlowKeyHash {` Source struct FlowKeyHash {
4 code line.
12 ` std::size_t operator()(const FlowKey& k) const Named std::size_t operator()(const FlowKey& k) const
5 noexcept {` constant noexcept {
— value
should
not
change.
12 ` // FNV-1a inspired mixing` Comment FNV-1a inspired mixing
6 document
ing intent.
12 ` uint64_t h = 1469598103934665603ull;` Executabl uint64_t h = 1469598103934665603ull;
7 e
statement
.
12 ` auto mix = [&](uint64_t v) {` Source auto mix = [&](uint64_t v) {
8 code line.

Page 91 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
12 ` h ^= v;` Executabl h ^= v;
9 e
statement
.
13 ` h *= 1099511628211ull;` Executabl h *= 1099511628211ull;
0 e
statement
.
13 ` };` Brace or C/C++ syntax structure.
1 parenthes
is
closing/o
pening a
block.
13 ` mix(k.src_ip);` Executabl mix(k.src_ip);
2 e
statement
.
13 ` mix(k.dst_ip);` Executabl mix(k.dst_ip);
3 e
statement
.
13 ` mix(static_cast<uint64_t>(k.src_port) << 16 \ k.dst_port Executable statement.
4 );`
13 ` mix([Link]);` Executabl mix([Link]);
5 e
statement
.
13 ` return static_cast<std::size_t>(h);` Exit return static_cast<std::size_t>(h);
6 function
and give
back a
value.
13 ` }` Brace or C/C++ syntax structure.
7 parenthes
is
closing/o
pening a
block.
13 `};` Brace or C/C++ syntax structure.
8 parenthes
is
closing/o
pening a
block.
13 `` Blank line Separator between code blocks.
9 for
readabilit
y.
14 `// Comment ======================================
0 ======================================= document ======================
=====================` ing intent.

Page 92 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
14 `// Flow Record - what we track per conversation` Comment Flow Record - what we track per conversation
1 document
ing intent.
14 `// Comment ======================================
2 ======================================= document ======================
=====================` ing intent.
14 `struct FlowRecord {` Source struct FlowRecord {
3 code line.
14 ` FlowKey key{};` Executabl FlowKey key{};
4 e
statement
.
14 `` Blank line Separator between code blocks.
5 for
readabilit
y.
14 ` // Counters` Comment Counters
6 document
ing intent.
14 ` uint64_t packet_count = 0;` Executabl uint64_t packet_count = 0;
7 e
statement
.
14 ` uint64_t byte_count = 0;` Executabl uint64_t byte_count = 0;
8 e
statement
.
14 ` uint32_t syn_count = 0;` Executabl uint32_t syn_count = 0;
9 e
statement
.
15 ` uint32_t ack_count = 0;` Executabl uint32_t ack_count = 0;
0 e
statement
.
15 ` uint32_t fin_count = 0;` Executabl uint32_t fin_count = 0;
1 e
statement
.
15 ` uint32_t rst_count = 0;` Executabl uint32_t rst_count = 0;
2 e
statement
.
15 ` uint32_t psh_count = 0;` Executabl uint32_t psh_count = 0;
3 e
statement
.
15 ` uint32_t urg_count = 0;` Executabl uint32_t urg_count = 0;
4 e
statement
.
15 ` uint32_t null_flag_count = 0;` Executabl uint32_t null_flag_count = 0;
5 e

Page 93 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
statement
.
15 ` uint32_t xmas_flag_count = 0;` Executabl uint32_t xmas_flag_count = 0;
6 e
statement
.
15 `` Blank line Separator between code blocks.
7 for
readabilit
y.
15 ` // Timing` Comment Timing
8 document
ing intent.
15 ` int64_t first_seen_us = 0;` Executabl int64_t first_seen_us = 0;
9 e
statement
.
16 ` int64_t last_seen_us = 0;` Executabl int64_t last_seen_us = 0;
0 e
statement
.

Li Source Easy Technical Explanation


ne Explana
tion
16 ` std::deque<int64_t> iat_buffer; // inter-arrival Source std::deque<int64_t> iat_buffer; // inter-arrival times
1 times (microseconds)` code line. (microseconds)
16 `` Blank line Separator between code blocks.
2 for
readabilit
y.
16 ` // Payload features` Comment Payload features
3 document
ing intent.
16 ` std::deque<uint16_t> size_buf;` Executabl std::deque<uint16_t> size_buf;
4 e
statement
.
16 ` double mean_pkt_size = 0.0;` Executabl double mean_pkt_size = 0.0;
5 e
statement
.
16 ` double stddev_pkt_size = 0.0;` Executabl double stddev_pkt_size = 0.0;
6 e
statement
.
16 ` double mean_iat = 0.0;` Executabl double mean_iat = 0.0;
7 e
statement
.
16 ` double stddev_iat = 0.0;` Executabl double stddev_iat = 0.0;
8 e

Page 94 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
statement
.
16 ` double entropy = 0.0;` Executabl double entropy = 0.0;
9 e
statement
.
17 ` std::array<uint64_t, 256> byte_histogram{}; // Source std::array<uint64_t, 256> byte_histogram{}; // for
0 for entropy` code line. entropy
17 `` Blank line Separator between code blocks.
1 for
readabilit
y.
17 ` // Derived rates (computed on demand)` Comment Derived rates (computed on demand)
2 document
ing intent.
17 ` double pps = 0.0;` Executabl double pps = 0.0;
3 e
statement
.
17 ` double bps = 0.0;` Executabl double bps = 0.0;
4 e
statement
.
17 ` double syn_ack_ratio = 0.0;` Executabl double syn_ack_ratio = 0.0;
5 e
statement
.
17 `` Blank line Separator between code blocks.
6 for
readabilit
y.
17 ` // Status flags` Comment Status flags
7 document
ing intent.
17 ` bool is_complete = false;` Executabl bool is_complete = false;
8 e
statement
.
17 ` bool has_full_handshake = false;` Executabl bool has_full_handshake = false;
9 e
statement
.
18 ` bool has_null_flags = false;` Executabl bool has_null_flags = false;
0 e
statement
.
18 ` bool has_xmas_flags = false;` Executabl bool has_xmas_flags = false;
1 e
statement
.
18 `` Blank line Separator between code blocks.
2 for

Page 95 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
readabilit
y.
18 ` static constexpr size_t MAX_BUF = 256;` Named static constexpr size_t MAX_BUF = 256;
3 constant
— value
should
not
change.
18 `` Blank line Separator between code blocks.
4 for
readabilit
y.
18 ` void touch_size(uint16_t s) {` Source void touch_size(uint16_t s) {
5 code line.
18 ` size_buf.push_back(s);` Executabl size_buf.push_back(s);
6 e
statement
.
18 ` if (size_buf.size() > MAX_BUF) Condition if (size_buf.size() > MAX_BUF)
7 size_buf.pop_front();` al branch size_buf.pop_front();
— run
code only
when
condition
true.
18 ` }` Brace or C/C++ syntax structure.
8 parenthes
is
closing/o
pening a
block.
18 ` void touch_iat(int64_t iat) {` Source void touch_iat(int64_t iat) {
9 code line.
19 ` iat_buffer.push_back(iat);` Executabl iat_buffer.push_back(iat);
0 e
statement
.
19 ` if (iat_buffer.size() > MAX_BUF) Condition if (iat_buffer.size() > MAX_BUF)
1 iat_buffer.pop_front();` al branch iat_buffer.pop_front();
— run
code only
when
condition
true.
19 ` }` Brace or C/C++ syntax structure.
2 parenthes
is
closing/o
pening a
block.
19 `};` Brace or C/C++ syntax structure.
3 parenthes
is
closing/o

Page 96 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
pening a
block.
19 `` Blank line Separator between code blocks.
4 for
readabilit
y.
19 `// Comment ======================================
5 ======================================= document ======================
=====================` ing intent.
19 `// Detector Result (returned by every detector)` Comment Detector Result (returned by every detector)
6 document
ing intent.
19 `// Comment ======================================
7 ======================================= document ======================
=====================` ing intent.
19 `struct DetectorResult {` Build or score 0-1, flags, detail string.
8 return a
detector
score
result.
19 ` double score = 0.0; // [0.0, 1.0]` Source double score = 0.0; // [0.0, 1.0]
9 code line.
20 ` bool is_anomaly = false;` Executabl bool is_anomaly = false;
0 e
statement
.
20 ` std::string detector_name;` Executabl std::string detector_name;
1 e
statement
.
20 ` std::vector<std::string> flags; // attack hints` Source std::vector<std::string> flags; // attack hints
2 code line.
20 ` std::string detail;` Executabl std::string detail;
3 e
statement
.
20 `};` Brace or C/C++ syntax structure.
4 parenthes
is
closing/o
pening a
block.
20 `` Blank line Separator between code blocks.
5 for
readabilit
y.
20 `struct FusionResult {` Combine Fusion / correlation logic.
6 multiple
detector
scores.
20 ` double final_score = 0.0;` Executabl double final_score = 0.0;
7 e

Page 97 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
statement
.
20 ` bool is_anomaly = false;` Executabl bool is_anomaly = false;
8 e
statement
.
20 ` std::vector<DetectorResult> detector_results;` Build or score 0-1, flags, detail string.
9 return a
detector
score
result.
21 `};` Brace or C/C++ syntax structure.
0 parenthes
is
closing/o
pening a
block.
21 `` Blank line Separator between code blocks.
1 for
readabilit
y.
21 `// Comment ======================================
2 ======================================= document ======================
=====================` ing intent.
21 `// Anomaly Event (final output)` Comment Anomaly Event (final output)
3 document
ing intent.
21 `// Comment ======================================
4 ======================================= document ======================
=====================` ing intent.
21 `enum class Severity {` Source enum class Severity {
5 code line.
21 ` INFO, LOW, MEDIUM, HIGH, CRITICAL` Source INFO, LOW, MEDIUM, HIGH, CRITICAL
6 code line.
21 `};` Brace or C/C++ syntax structure.
7 parenthes
is
closing/o
pening a
block.
21 `` Blank line Separator between code blocks.
8 for
readabilit
y.
21 `struct AnomalyEvent {` Final alert Enterprise alert struct.
9 record
sent to
logs and
UI.
22 ` int64_t timestamp_us = 0;` Executabl int64_t timestamp_us = 0;
0 e
statement
.

Page 98 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
22 ` uint32_t src_ip = 0;` Executabl uint32_t src_ip = 0;
1 e
statement
.
22 ` uint32_t dst_ip = 0;` Executabl uint32_t dst_ip = 0;
2 e
statement
.
22 ` uint16_t src_port = 0;` Executabl uint16_t src_port = 0;
3 e
statement
.
22 ` uint16_t dst_port = 0;` Executabl uint16_t dst_port = 0;
4 e
statement
.
22 ` uint8_t protocol = 0;` Executabl uint8_t protocol = 0;
5 e
statement
.
22 ` std::string attack_type;` Executabl std::string attack_type;
6 e
statement
.
22 ` Severity severity = Severity::INFO;` Executabl Severity severity = Severity::INFO;
7 e
statement
.
22 ` double confidence = 0.0;` Executabl double confidence = 0.0;
8 e
statement
.
22 ` double final_score = 0.0;` Executabl double final_score = 0.0;
9 e
statement
.
23 ` std::string description;` Executabl std::string description;
0 e
statement
.
23 ` std::string recommendation;` Executabl std::string recommendation;
1 e
statement
.
23 ` std::vector<DetectorResult> detector_results;` Build or score 0-1, flags, detail string.
2 return a
detector
score
result.
23 ` std::vector<std::string> mitre_techniques;` Executabl std::vector<std::string> mitre_techniques;
3 e
statement
.

Page 99 of 629
NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
23 ` std::vector<std::string> mitre_tactics;` Executabl std::vector<std::string> mitre_tactics;
4 e
statement
.
23 ` std::vector<std::string> evidence;` Executabl std::vector<std::string> evidence;
5 e
statement
.
23 ` std::string flow_summary;` Executabl std::string flow_summary;
6 e
statement
.
23 ` std::string correlation_id;` Executabl std::string correlation_id;
7 e
statement
.
23 ` double correlation_boost = 0.0;` Executabl double correlation_boost = 0.0;
8 e
statement
.
23 ` std::string kafka_topic; // empty = disabled` Source std::string kafka_topic; // empty = disabled
9 code line.
24 ` std::string webhook_url;` Executabl std::string webhook_url;
0 e
statement
.

Li Source Easy Technical Explanation


ne Explana
tion
24 `};` Brace or C/C++ syntax structure.
1 parenthes
is
closing/o
pening a
block.
24 `` Blank line Separator between code blocks.
2 for
readabilit
y.
24 `// Comment ======================================
3 ======================================= document ======================
=====================` ing intent.
24 `// Live Statistics (for dashboard)` Comment Live Statistics (for dashboard)
4 document
ing intent.
24 `// Comment ======================================
5 ======================================= document ======================
=====================` ing intent.
24 `struct LiveStats {` Source struct LiveStats {
6 code line.

Page 100 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
24 ` std::atomic<uint64_t> Counter Lock-free atomic variable.
7 total_packets_captured{0};` safe to
read/write
from
multiple
threads.
24 ` std::atomic<uint64_t> Counter Lock-free atomic variable.
8 total_packets_processed{0};` safe to
read/write
from
multiple
threads.
24 ` std::atomic<uint64_t> Counter Lock-free atomic variable.
9 total_packets_dropped{0};` safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> total_bytes{0};` Counter Lock-free atomic variable.
0 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> active_flows{0};` Counter Lock-free atomic variable.
1 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> completed_flows{0};` Counter Lock-free atomic variable.
2 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> total_hosts{0};` Counter Lock-free atomic variable.
3 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> alerts_total{0};` Counter Lock-free atomic variable.
4 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> alerts_critical{0};` Counter Lock-free atomic variable.
5 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> alerts_high{0};` Counter Lock-free atomic variable.
6 safe to

Page 101 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> alerts_medium{0};` Counter Lock-free atomic variable.
7 safe to
read/write
from
multiple
threads.
25 ` std::atomic<uint64_t> queue_size{0};` Counter Lock-free atomic variable.
8 safe to
read/write
from
multiple
threads.
25 ` std::atomic<double> current_pps{0.0};` Counter Lock-free atomic variable.
9 safe to
read/write
from
multiple
threads.
26 ` std::atomic<double> current_bps{0.0};` Counter Lock-free atomic variable.
0 safe to
read/write
from
multiple
threads.
26 ` std::atomic<int64_t> start_time_us{0};` Counter Lock-free atomic variable.
1 safe to
read/write
from
multiple
threads.
26 `};` Brace or C/C++ syntax structure.
2 parenthes
is
closing/o
pening a
block.
26 `` Blank line Separator between code blocks.
3 for
readabilit
y.
26 `// Comment ======================================
4 ======================================= document ======================
=====================` ing intent.
26 `// Configuration` Comment Configuration
5 document
ing intent.
26 `// Comment ======================================
6 ======================================= document ======================
=====================` ing intent.
26 `struct Config {` Source struct Config {
7 code line.

Page 102 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
26 ` std::string interface = "lo";` Executabl std::string interface = "lo";
8 e
statement
.
26 ` std::string bpf_filter = "";` Executabl std::string bpf_filter = "";
9 e
statement
.
27 ` std::string output_log = "[Link]";` Executabl std::string output_log = "[Link]";
0 e
statement
.
27 ` std::string json_output = "[Link]";` Executabl std::string json_output = "[Link]";
1 e
statement
.
27 ` double alert_threshold = 0.7;` Executabl double alert_threshold = 0.7;
2 e
statement
.
27 ` double critical_threshold = 0.9;` Executabl double critical_threshold = 0.9;
3 e
statement
.
27 ` int window_seconds = 60;` Executabl int window_seconds = 60;
4 e
statement
.
27 ` int flow_timeout_sec = 60;` Executabl int flow_timeout_sec = 60;
5 e
statement
.
27 ` bool read_only = false;` Executabl bool read_only = false;
6 e
statement
.
27 ` bool no_dashboard = false;` Executabl bool no_dashboard = false;
7 e
statement
.
27 ` bool verbose = false;` Executabl bool verbose = false;
8 e
statement
.
27 ` int web_server_port = 8080;` Executabl int web_server_port = 8080;
9 e
statement
.
28 ` double syn_flood_threshold_pps = 500.0;` Executabl double syn_flood_threshold_pps = 500.0;
0 e
statement
.

Page 103 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
28 ` double packet_flood_threshold_pps = 2000.0;` Executabl double packet_flood_threshold_pps = 2000.0;
1 e
statement
.
28 `` Blank line Separator between code blocks.
2 for
readabilit
y.
28 ` // Adaptive statistics` Comment Adaptive statistics
3 document
ing intent.
28 ` double ewma_alpha = 0.05;` Executabl double ewma_alpha = 0.05;
4 e
statement
.
28 ` int percentile_window = 256;` Executabl int percentile_window = 256;
5 e
statement
.
28 ` bool adaptive_thresholds = true;` Executabl bool adaptive_thresholds = true;
6 e
statement
.
28 `` Blank line Separator between code blocks.
7 for
readabilit
y.
28 ` // Fusion / correlation` Comment Fusion / correlation
8 document
ing intent.
28 ` std::string fusion_type = "weighted";` Combine Fusion / correlation logic.
9 multiple
detector
scores.
29 ` bool use_logistic_fusion = false;` Executabl bool use_logistic_fusion = false;
0 e
statement
.
29 ` std::string fusion_weights_path = Combine Fusion / correlation logic.
1 "fusion_weights.txt";` multiple
detector
scores.
29 ` double fusion_learning_rate = 0.01;` Combine Fusion / correlation logic.
2 multiple
detector
scores.
29 ` int correlation_window_sec = 30;` Executabl int correlation_window_sec = 30;
3 e
statement
.
29 ` bool use_legacy_fusion_boost = true;` Combine Fusion / correlation logic.
4 multiple

Page 104 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
detector
scores.
29 `` Blank line Separator between code blocks.
5 for
readabilit
y.
29 ` // Profiling / observability` Comment Profiling / observability
6 document
ing intent.
29 ` bool use_per_service_baseline = true;` Executabl bool use_per_service_baseline = true;
7 e
statement
.
29 ` bool metrics_enabled = true;` Executabl bool metrics_enabled = true;
8 e
statement
.
29 ` std::string webhook_url;` Executabl std::string webhook_url;
9 e
statement
.
30 `` Blank line Separator between code blocks.
0 for
readabilit
y.
30 ` // Advanced detectors (feature flags)` Comment Advanced detectors (feature flags)
1 document
ing intent.
30 ` bool enable_slow_scan = true;` Executabl bool enable_slow_scan = true;
2 e
statement
.
30 ` bool enable_beacon_detector = true;` Executabl bool enable_beacon_detector = true;
3 e
statement
.
30 ` bool enable_burst_detector = true;` Executabl bool enable_burst_detector = true;
4 e
statement
.
30 ` bool enable_dns_tunnel = true;` Executabl bool enable_dns_tunnel = true;
5 e
statement
.
30 ` bool enable_syn_ratio = true;` Executabl bool enable_syn_ratio = true;
6 e
statement
.
30 ` bool enable_long_lived_flow = true;` Executabl bool enable_long_lived_flow = true;
7 e
statement
.

Page 105 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
30 `` Blank line Separator between code blocks.
8 for
readabilit
y.
30 ` // Detector weights` Comment Detector weights
9 document
ing intent.
31 ` double w_statistical = 0.20;` Executabl double w_statistical = 0.20;
0 e
statement
.
31 ` double w_volume = 0.25;` Executabl double w_volume = 0.25;
1 e
statement
.
31 ` double w_protocol = 0.20;` Executabl double w_protocol = 0.20;
2 e
statement
.
31 ` double w_baseline = 0.15;` Executabl double w_baseline = 0.15;
3 e
statement
.
31 ` double w_graph = 0.10;` Executabl double w_graph = 0.10;
4 e
statement
.
31 ` double w_temporal = 0.05;` Executabl double w_temporal = 0.05;
5 e
statement
.
31 ` double w_entropy = 0.05;` Executabl double w_entropy = 0.05;
6 e
statement
.
31 `};` Brace or C/C++ syntax structure.
7 parenthes
is
closing/o
pening a
block.
31 `` Blank line Separator between code blocks.
8 for
readabilit
y.
31 `// Helper: get current time in microseconds` Comment Helper: get current time in microseconds
9 document
ing intent.
32 `inline int64_t now_us() {` Source inline int64_t now_us() {
0 code line.

Page 106 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
321 ` using namespace std::chrono;` Executable using namespace std::chrono;
statement.
322 ` return duration_cast<microseconds>(` Exit function return duration_cast<microseconds>(
and give back
a value.
323 ` Executable steady_clock::now().time_since_epoch()).count
steady_clock::now().time_since_epoch()).count( statement. ();
);`
324 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
325 `` Blank line for Separator between code blocks.
readability.
326 `inline int64_t wall_us() {` Source code inline int64_t wall_us() {
line.
327 ` using namespace std::chrono;` Executable using namespace std::chrono;
statement.
328 ` return duration_cast<microseconds>(` Exit function return duration_cast<microseconds>(
and give back
a value.
329 ` Executable system_clock::now().time_since_epoch()).count
system_clock::now().time_since_epoch()).count( statement. ();
);`
330 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
331 `` Blank line for Separator between code blocks.
readability.
332 `// IP -> dotted string` Comment IP -> dotted string
documenting
intent.
333 `std::string ip_to_string(uint32_t ip_be);` Executable std::string ip_to_string(uint32_t ip_be);
statement.
334 `std::string severity_to_string(Severity s);` Executable std::string severity_to_string(Severity s);
statement.
335 `` Blank line for Separator between code blocks.
readability.
336 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/include/volume_detector.h
Total lines: 53

Page 107 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `#pragma once` Compiler directive (packing, #pragma once
once, etc.).
2 `` Blank line for readability. Separator between code blocks.
3 `#include "types.h"` Import another header file into #include "types.h"
this compilation unit.
4 `#include "running_stats.h"` Import another header file into #include "running_stats.h"
this compilation unit.
5 `#include <array>` Import another header file into #include <array>
this compilation unit.
6 `#include <mutex>` Import another header file into #include <mutex>
this compilation unit.
7 `` Blank line for readability. Separator between code blocks.
8 `namespace nads {` Start a named code region so namespace nads {
names do not clash globally.
9 `` Blank line for readability. Separator between code blocks.
10 `class VolumeDetector {` Source code line. class VolumeDetector {
11 `public:` Source code line. public:
12 ` explicit VolumeDetector(const Named constant — value explicit VolumeDetector(const
Config& cfg);` should not change. Config& cfg);
13 `` Blank line for readability. Separator between code blocks.
14 ` void on_packet(const Named constant — value void on_packet(const PacketInfo&
PacketInfo& pkt);` should not change. pkt);
15 ` void on_new_flow();` Executable statement. void on_new_flow();
16 `` Blank line for readability. Separator between code blocks.
17 ` struct Rates {` Source code line. struct Rates {
18 ` double pps = 0.0;` Executable statement. double pps = 0.0;
19 ` double bps = 0.0;` Executable statement. double bps = 0.0;
20 ` double syn_pps = 0.0;` Executable statement. double syn_pps = 0.0;
21 ` double new_flow_per_sec = Executable statement. double new_flow_per_sec = 0.0;
0.0;`
22 ` };` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
23 `` Blank line for readability. Separator between code blocks.
24 ` Rates current_rates() const;` Executable statement. Rates current_rates() const;
25 ` DetectorResult detect();` Build or return a detector score score 0-1, flags, detail string.
result.
26 `` Blank line for readability. Separator between code blocks.
27 `private:` Source code line. private:
28 ` static constexpr int Named constant — value static constexpr int
NUM_BUCKETS = 60;` should not change. NUM_BUCKETS = 60;
29 ` static constexpr int Named constant — value static constexpr int BUCKET_MS
BUCKET_MS = 1000;` should not change. = 1000;
30 `` Blank line for readability. Separator between code blocks.
31 ` struct Bucket {` Source code line. struct Bucket {
32 ` uint64_t packets = 0;` Executable statement. uint64_t packets = 0;

Page 108 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


33 ` uint64_t bytes = 0;` Executable statement. uint64_t bytes = 0;
34 ` uint64_t syn = 0;` Executable statement. uint64_t syn = 0;
35 ` uint64_t new_flows = 0;` Executable statement. uint64_t new_flows = 0;
36 ` int64_t bucket_id = -1;` Executable statement. int64_t bucket_id = -1;
37 ` };` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
38 `` Blank line for readability. Separator between code blocks.
39 ` int bucket_index_for(int64_t Executable statement. int bucket_index_for(int64_t
ts_us) const;` ts_us) const;
40 ` void rotate_if_needed(int64_t Executable statement. void rotate_if_needed(int64_t
ts_us);` ts_us);
41 `` Blank line for readability. Separator between code blocks.
42 ` mutable std::mutex mtx_;` Executable statement. mutable std::mutex mtx_;
43 ` std::array<Bucket, Executable statement. std::array<Bucket,
NUM_BUCKETS> buckets_{};` NUM_BUCKETS> buckets_{};
44 ` int64_t newest_id_ = -1;` Executable statement. int64_t newest_id_ = -1;
45 `` Blank line for readability. Separator between code blocks.
46 ` RunningStats Executable statement. RunningStats hist_pps_legacy_;
hist_pps_legacy_;`
47 ` RunningStats Executable statement. RunningStats hist_syn_legacy_;
hist_syn_legacy_;`
48 ` AdaptiveBaseline hist_pps_;` Executable statement. AdaptiveBaseline hist_pps_;
49 ` AdaptiveBaseline hist_syn_;` Executable statement. AdaptiveBaseline hist_syn_;
50 ` const Config& cfg_;` Named constant — value const Config& cfg_;
should not change.
51 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
52 `` Blank line for readability. Separator between code blocks.
53 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/src/advanced_detectors.cpp
Total lines: 118

Lin Source Easy Technical Explanation


e Explanation
1 `#include "advanced_detectors.h"` Import another #include "advanced_detectors.h"
header file into
this
compilation
unit.
2 `#include "scoring_utils.h"` Import another #include "scoring_utils.h"
header file into
this

Page 109 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file into
this
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `AdvancedDetectors::AdvancedDetectors(const Named AdvancedDetectors::AdvancedDetectors(const
Config& cfg) : cfg_(cfg) {}` constant — Config& cfg) : cfg_(cfg) {}
value should
not change.
8 `` Blank line for Separator between code blocks.
readability.
9 `DetectorResult Build or return score 0-1, flags, detail string.
AdvancedDetectors::on_packet(const a detector
PacketInfo& pkt) {` score result.
10 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
11 ` res.detector_name = "advanced_packet";` Executable res.detector_name = "advanced_packet";
statement.
12 ` if (![Link] \ \ [Link] != PROTO_TCP) return res;`
13 ` if (pkt.tcp_flags & TCP_SYN) {` Conditional if (pkt.tcp_flags & TCP_SYN) {
branch — run
code only
when
condition true.
14 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
15 ` host_syn_[pkt.src_ip]++;` Executable host_syn_[pkt.src_ip]++;
statement.
16 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
17 ` if (pkt.tcp_flags & TCP_ACK) {` Conditional if (pkt.tcp_flags & TCP_ACK) {
branch — run
code only
when
condition true.
18 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one

Page 110 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
thread uses
shared data at
a time.
19 ` host_ack_[pkt.src_ip]++;` Executable host_ack_[pkt.src_ip]++;
statement.
20 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
21 ` return res;` Exit function return res;
and give back
a value.
22 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
23 `` Blank line for Separator between code blocks.
readability.
24 `DetectorResult Build or return score 0-1, flags, detail string.
AdvancedDetectors::slow_scan(const a detector
FlowRecord& flow) {` score result.
25 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
26 ` res.detector_name = "slow_scan";` Executable res.detector_name = "slow_scan";
statement.
27 ` if (!cfg_.enable_slow_scan) return res;` Conditional if (!cfg_.enable_slow_scan) return res;
branch — run
code only
when
condition true.
28 `` Blank line for Separator between code blocks.
readability.
29 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
30 ` auto& ports = Executable auto& ports =
host_ports_seen_[[Link].src_ip];` statement. host_ports_seen_[[Link].src_ip];
31 ` bool novel = Executable bool novel =
[Link]([Link].dst_port).second;` statement. [Link]([Link].dst_port).second;
32 ` double dur_s = (flow.last_seen_us - Executable double dur_s = (flow.last_seen_us -
flow.first_seen_us) / 1e6;` statement. flow.first_seen_us) / 1e6;
33 ` if (novel && dur_s > 5.0 && Conditional if (novel && dur_s > 5.0 && flow.packet_count
flow.packet_count <= 6 && [Link]() > 15) {` branch — run <= 6 && [Link]() > 15) {
code only
when
condition true.
34 ` [Link] = 0.75;` Executable [Link] = 0.75;
statement.

Page 111 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
35 ` res.is_anomaly = true;` Executable res.is_anomaly = true;
statement.
36 ` Executable [Link].push_back("SLOW_PORT_SCAN");
[Link].push_back("SLOW_PORT_SCAN");` statement.
37 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
38 ` return res;` Exit function return res;
and give back
a value.
39 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
40 `` Blank line for Separator between code blocks.
readability.
41 `DetectorResult AdvancedDetectors::burst(const Build or return score 0-1, flags, detail string.
FlowRecord& flow) {` a detector
score result.
42 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
43 ` res.detector_name = "burst";` Executable res.detector_name = "burst";
statement.
44 ` if (!cfg_.enable_burst_detector) return res;` Conditional if (!cfg_.enable_burst_detector) return res;
branch — run
code only
when
condition true.
45 ` if ([Link] > 500.0 && flow.packet_count > Conditional if ([Link] > 500.0 && flow.packet_count > 50)
50) {` branch — run {
code only
when
condition true.
46 ` [Link] = std::min(1.0, [Link] / Executable [Link] = std::min(1.0, [Link] / 2000.0);
2000.0);` statement.
47 ` res.is_anomaly = [Link] > 0.6;` Executable res.is_anomaly = [Link] > 0.6;
statement.
48 ` Executable [Link].push_back("TRAFFIC_BURST");
[Link].push_back("TRAFFIC_BURST");` statement.
49 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
50 ` return res;` Exit function return res;
and give back
a value.
51 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 112 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
52 `` Blank line for Separator between code blocks.
readability.
53 `DetectorResult Build or return score 0-1, flags, detail string.
AdvancedDetectors::long_lived(const a detector
FlowRecord& flow) {` score result.
54 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
55 ` res.detector_name = "long_lived_flow";` Executable res.detector_name = "long_lived_flow";
statement.
56 ` if (!cfg_.enable_long_lived_flow) return res;` Conditional if (!cfg_.enable_long_lived_flow) return res;
branch — run
code only
when
condition true.
57 ` double dur_s = (flow.last_seen_us - Executable double dur_s = (flow.last_seen_us -
flow.first_seen_us) / 1e6;` statement. flow.first_seen_us) / 1e6;
58 ` if (dur_s > 3600.0 && flow.byte_count > Conditional if (dur_s > 3600.0 && flow.byte_count >
100000) {` branch — run 100000) {
code only
when
condition true.
59 ` [Link] = 0.55;` Executable [Link] = 0.55;
statement.
60 ` Executable [Link].push_back("LONG_LIVED_FLOW");
[Link].push_back("LONG_LIVED_FLOW");` statement.
61 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
62 ` return res;` Exit function return res;
and give back
a value.
63 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
64 `` Blank line for Separator between code blocks.
readability.
65 `DetectorResult Build or return score 0-1, flags, detail string.
AdvancedDetectors::dns_tunnel(const a detector
FlowRecord& flow, const PacketInfo*) {` score result.
66 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
67 ` res.detector_name = "dns_tunnel";` Executable res.detector_name = "dns_tunnel";
statement.
68 ` if (!cfg_.enable_dns_tunnel) return res;` Conditional if (!cfg_.enable_dns_tunnel) return res;
branch — run
code only
when
condition true.

Page 113 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
69 ` if ([Link] != PROTO_UDP) return Conditional if ([Link] != PROTO_UDP) return
res;` branch — run res;
code only
when
condition true.
70 ` if ([Link].dst_port != 53 && Conditional if ([Link].dst_port != 53 && [Link].src_port
[Link].src_port != 53) return res;` branch — run != 53) return res;
code only
when
condition true.
71 ` if (flow.mean_pkt_size > 400 && [Link] Conditional if (flow.mean_pkt_size > 400 && [Link] >
> 4.5) {` branch — run 4.5) {
code only
when
condition true.
72 ` [Link] = 0.8;` Executable [Link] = 0.8;
statement.
73 ` res.is_anomaly = true;` Executable res.is_anomaly = true;
statement.
74 ` Executable [Link].push_back("DNS_TUNNEL_SUSPEC
[Link].push_back("DNS_TUNNEL_SUSPECT statement. T");
");`
75 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
76 ` return res;` Exit function return res;
and give back
a value.
77 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
78 `` Blank line for Separator between code blocks.
readability.
79 `DetectorResult Build or return score 0-1, flags, detail string.
AdvancedDetectors::syn_ratio(const a detector
FlowRecord& flow) {` score result.
80 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.

Lin Source Easy Technical Explanation


e Explanation
81 ` res.detector_name = "syn_ratio";` Executable res.detector_name = "syn_ratio";
statement.
82 ` if (!cfg_.enable_syn_ratio) return res;` Conditional if (!cfg_.enable_syn_ratio) return res;
branch — run
code only
when condition
true.
83 ` if ([Link] != PROTO_TCP) return Conditional if ([Link] != PROTO_TCP) return
res;` branch — run res;

Page 114 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
code only
when condition
true.
84 `` Blank line for Separator between code blocks.
readability.
85 ` uint64_t syn = 0, ack = 0;` Executable uint64_t syn = 0, ack = 0;
statement.
86 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
87 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
88 ` syn = host_syn_[[Link].src_ip];` Executable syn = host_syn_[[Link].src_ip];
statement.
89 ` ack = host_ack_[[Link].src_ip];` Executable ack = host_ack_[[Link].src_ip];
statement.
90 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
91 ` if (syn > 20 && ack == 0) {` Conditional if (syn > 20 && ack == 0) {
branch — run
code only
when condition
true.
92 ` [Link] = 0.9;` Executable [Link] = 0.9;
statement.
93 ` res.is_anomaly = true;` Executable res.is_anomaly = true;
statement.
94 ` Executable [Link].push_back("SYN_RATIO_ANOMALY"
[Link].push_back("SYN_RATIO_ANOMALY") statement. );
;`
95 ` } else if (flow.syn_ack_ratio > 8.0 && Conditional } else if (flow.syn_ack_ratio > 8.0 &&
flow.syn_count > 30) {` branch — run flow.syn_count > 30) {
code only
when condition
true.
96 ` [Link] = 0.75;` Executable [Link] = 0.75;
statement.
97 ` Executable [Link].push_back("HIGH_SYN_ACK_RATIO
[Link].push_back("HIGH_SYN_ACK_RATIO" statement. ");
);`
98 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
99 ` return res;` Exit function return res;
and give back
a value.

Page 115 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
100 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
101 `` Blank line for Separator between code blocks.
readability.
102 `std::vector<DetectorResult> Build or return score 0-1, flags, detail string.
AdvancedDetectors::analyze_flow(const a detector
FlowRecord& flow) {` score result.
103 ` std::vector<DetectorResult> out;` Build or return score 0-1, flags, detail string.
a detector
score result.
104 ` auto push_if = [&](DetectorResult r) {` Build or return score 0-1, flags, detail string.
a detector
score result.
105 ` if ([Link] > 0.0) {` Conditional if ([Link] > 0.0) {
branch — run
code only
when condition
true.
106 ` r.detector_name = "advanced_" + Executable r.detector_name = "advanced_" +
r.detector_name;` statement. r.detector_name;
107 ` out.push_back(std::move(r));` Executable out.push_back(std::move(r));
statement.
108 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
109 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
110 ` push_if(slow_scan(flow));` Executable push_if(slow_scan(flow));
statement.
111 ` push_if(burst(flow));` Executable push_if(burst(flow));
statement.
112 ` push_if(long_lived(flow));` Executable push_if(long_lived(flow));
statement.
113 ` push_if(dns_tunnel(flow, nullptr));` Executable push_if(dns_tunnel(flow, nullptr));
statement.
114 ` push_if(syn_ratio(flow));` Executable push_if(syn_ratio(flow));
statement.
115 ` return out;` Exit function return out;
and give back
a value.
116 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
117 `` Blank line for Separator between code blocks.
readability.

Page 116 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
118 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/alert_system.cpp
Total lines: 197

Line Source Easy Technical Explanation


Explanation
1 `// alert_system.cpp - console output, log Comment alert_system.cpp - console output, log
file, JSON, with cooldown` documenting file, JSON, with cooldown
intent.
2 `#include "alert_system.h"` Import another #include "alert_system.h"
header file into this
compilation unit.
3 `#include <iostream>` Import another #include <iostream>
header file into this
compilation unit.
4 `#include <iomanip>` Import another #include <iomanip>
header file into this
compilation unit.
5 `#include <ctime>` Import another #include <ctime>
header file into this
compilation unit.
6 `#include <sstream>` Import another #include <sstream>
header file into this
compilation unit.
7 `#include <cmath>` Import another #include <cmath>
header file into this
compilation unit.
8 `` Blank line for Separator between code blocks.
readability.
9 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
10 `` Blank line for Separator between code blocks.
readability.
11 `// ANSI color helpers` Comment ANSI color helpers
documenting
intent.
12 `static const char* const C_RESET = Named constant — static const char* const C_RESET =
"\033[0m";` value should not "\033[0m";
change.
13 `static const char* const C_RED = Named constant — static const char* const C_RED =
"\033[31m";` value should not "\033[31m";
change.

Page 117 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
14 `static const char* const C_YEL = Named constant — static const char* const C_YEL =
"\033[33m";` value should not "\033[33m";
change.
15 `static const char* const C_CYAN = Named constant — static const char* const C_CYAN =
"\033[36m";` value should not "\033[36m";
change.
16 `static const char* const C_BOLD = Named constant — static const char* const C_BOLD =
"\033[1m";` value should not "\033[1m";
change.
17 `static const char* const C_RED_BG= Named constant — static const char* const C_RED_BG=
"\033[41;97m";` value should not "\033[41;97m";
change.
18 `static const char* const C_YEL_BG= Named constant — static const char* const C_YEL_BG=
"\033[43;30m";` value should not "\033[43;30m";
change.
19 `static const char* const C_BLUE = Named constant — static const char* const C_BLUE =
"\033[34m";` value should not "\033[34m";
change.
20 `` Blank line for Separator between code blocks.
readability.
21 `AlertSystem::AlertSystem(const Named constant — AlertSystem::AlertSystem(const
std::string& log_path, const std::string& value should not std::string& log_path, const std::string&
json_path)` change. json_pa
22 `{` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
23 ` log_out_.open(log_path, Executable log_out_.open(log_path, std::ios::app);
std::ios::app);` statement.
24 ` json_out_.open(json_path, Executable json_out_.open(json_path,
std::ios::trunc);` statement. std::ios::trunc);
25 ` if (json_out_.is_open()) {` Conditional branch if (json_out_.is_open()) {
— run code only
when condition
true.
26 ` json_out_ << "[\n";` Executable json_out_ << "[\n";
statement.
27 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
28 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
29 `` Blank line for Separator between code blocks.
readability.
30 `AlertSystem::~AlertSystem() {` Source code line. AlertSystem::~AlertSystem() {
31 ` shutdown();` Executable shutdown();
statement.
32 `}` Brace or C/C++ syntax structure.
parenthesis

Page 118 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
33 `` Blank line for Separator between code blocks.
readability.
34 `void AlertSystem::shutdown() {` Source code line. void AlertSystem::shutdown() {
35 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared data
at a time.
36 ` if (json_out_.is_open()) {` Conditional branch if (json_out_.is_open()) {
— run code only
when condition
true.
37 ` json_out_ << "\n]\n";` Executable json_out_ << "\n]\n";
statement.
38 ` json_out_.close();` Executable json_out_.close();
statement.
39 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
40 ` if (log_out_.is_open()) Conditional branch if (log_out_.is_open()) log_out_.close();
log_out_.close();` — run code only
when condition
true.
41 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
42 `` Blank line for Separator between code blocks.
readability.
43 `int AlertSystem::cooldown_for(const Named constant — int AlertSystem::cooldown_for(const
std::string& attack_type) const {` value should not std::string& attack_type) const {
change.
44 ` if (attack_type.find("Port Scan") != Conditional branch if (attack_type.find("Port Scan") !=
std::string::npos) return 60;` — run code only std::string::npos) return 60;
when condition
true.
45 ` if (attack_type.find("SYN Flood") != Conditional branch if (attack_type.find("SYN Flood") !=
std::string::npos) return 5;` — run code only std::string::npos) return 5;
when condition
true.
46 ` if (attack_type.find("Brute") != Conditional branch if (attack_type.find("Brute") !=
std::string::npos) return 30;` — run code only std::string::npos) return 30;
when condition
true.
47 ` if (attack_type.find("Beacon") != Conditional branch if (attack_type.find("Beacon") !=
std::string::npos) return 300;` — run code only std::string::npos) return 300;
when condition
true.
48 ` if (attack_type.find("Lateral") != Conditional branch if (attack_type.find("Lateral") !=
std::string::npos) return 60;` — run code only std::string::npos) return 60;

Page 119 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
when condition
true.
49 ` if (attack_type.find("Tunneling") != Conditional branch if (attack_type.find("Tunneling") !=
std::string::npos) return 120;` — run code only std::string::npos) return 120;
when condition
true.
50 ` return 30;` Exit function and return 30;
give back a value.
51 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
52 `` Blank line for Separator between code blocks.
readability.
53 `bool AlertSystem::should_alert(uint32_t Named constant — bool AlertSystem::should_alert(uint32_t
src_ip, const std::string& attack_type, value should not src_ip, const std::string& attack_type,
int64_t now_us) {` change.
54 ` uint64_t key = Source code line. uint64_t key =
(static_cast<uint64_t>(src_ip) << 32) ^` (static_cast<uint64_t>(src_ip) << 32) ^
55 ` Executable std::hash<std::string>{}(attack_type);
std::hash<std::string>{}(attack_type);` statement.
56 ` int cd_s = cooldown_for(attack_type);` Executable int cd_s = cooldown_for(attack_type);
statement.
57 ` auto it = last_alert_us_.find(key);` Executable auto it = last_alert_us_.find(key);
statement.
58 ` if (it != last_alert_us_.end()) {` Conditional branch if (it != last_alert_us_.end()) {
— run code only
when condition
true.
59 ` if (now_us - it->second < Conditional branch if (now_us - it->second <
static_cast<int64_t>(cd_s) * 1000000LL) — run code only static_cast<int64_t>(cd_s) *
return false;` when condition 1000000LL) return false;
true.
60 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
61 ` last_alert_us_[key] = now_us;` Executable last_alert_us_[key] = now_us;
statement.
62 ` return true;` Exit function and return true;
give back a value.
63 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
64 `` Blank line for Separator between code blocks.
readability.
65 `static std::string ts_string(int64_t us) {` Source code line. static std::string ts_string(int64_t us) {
66 ` std::time_t t = us / 1000000;` Executable std::time_t t = us / 1000000;
statement.

Page 120 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
67 ` std::tm tm{};` Executable std::tm tm{};
statement.
68 `#ifdef _WIN32` Comment ifdef _WIN32
documenting
intent.
69 ` localtime_s(&tm, &t);` Executable localtime_s(&tm, &t);
statement.
70 `#else` Comment else
documenting
intent.
71 ` localtime_r(&t, &tm);` Executable localtime_r(&t, &tm);
statement.
72 `#endif` Comment endif
documenting
intent.
73 ` char buf[32];` Executable char buf[32];
statement.
74 ` std::snprintf(buf, sizeof(buf), "%04d- Source code line. std::snprintf(buf, sizeof(buf), "%04d-
%02d-%02d %02d:%02d:%02d",` %02d-%02d %02d:%02d:%02d",
75 ` tm.tm_year + 1900, Source code line. tm.tm_year + 1900, tm.tm_mon + 1,
tm.tm_mon + 1, tm.tm_mday,` tm.tm_mday,
76 ` tm.tm_hour, tm.tm_min, Executable tm.tm_hour, tm.tm_min, tm.tm_sec);
tm.tm_sec);` statement.
77 ` return std::string(buf);` Exit function and return std::string(buf);
give back a value.
78 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
79 `` Blank line for Separator between code blocks.
readability.
80 `void AlertSystem::write_log(const Final alert record Enterprise alert struct.
AnomalyEvent& ev) {` sent to logs and
UI.

Line Source Easy Explanation Technical Explanation


81 ` if (!log_out_.is_open()) return;` Conditional branch — run code if (!log_out_.is_open()) return;
only when condition true.
82 ` log_out_ << Source code line. log_out_ <<
ts_string(ev.timestamp_us)` ts_string(ev.timestamp_us)
83 ` << " \ " << Source code line.
severity_to_string([Link])`
84 ` << " \ " << ev.attack_type` Source code line.
85 ` << " \ " << ip_to_string(ev.src_ip) << Source code line.
":" << ev.src_port`
86 ` << " -> " << Source code line. << " -> " <<
ip_to_string(ev.dst_ip) << ":" << ip_to_string(ev.dst_ip) << ":" <<
ev.dst_port` ev.dst_port

Page 121 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


87 ` << " \ score=" << std::fixed << Source code line.
std::setprecision(2) <<
ev.final_score`
88 ` << " \ conf=" << std::fixed << Executable statement.
std::setprecision(2) <<
[Link];`
89 ` log_out_ << "\n";` Executable statement. log_out_ << "\n";
90 ` log_out_.flush();` Executable statement. log_out_.flush();
91 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
92 `` Blank line for readability. Separator between code blocks.
93 `void AlertSystem::write_json(const Final alert record sent to logs Enterprise alert struct.
AnomalyEvent& ev) {` and UI.
94 ` if (!json_out_.is_open()) return;` Conditional branch — run code if (!json_out_.is_open()) return;
only when condition true.
95 ` if (!first_json_) json_out_ << Conditional branch — run code if (!first_json_) json_out_ << ",\n";
",\n";` only when condition true.
96 ` first_json_ = false;` Executable statement. first_json_ = false;
97 ` json_out_ << " {\n";` Executable statement. json_out_ << " {\n";
98 ` json_out_ << " \"timestamp\": Executable statement. json_out_ << " \"timestamp\": \""
\"" << ts_string(ev.timestamp_us) << ts_string(ev.timestamp_us) <<
<< "\",\n";` "\",\n";
99 ` json_out_ << " \"severity\": \"" Executable statement. json_out_ << " \"severity\": \""
<< severity_to_string([Link]) << severity_to_string([Link])
<< "\",\n";` << "\",\n";
100 ` json_out_ << " \"attack\": \"" Executable statement. json_out_ << " \"attack\": \"" <<
<< ev.attack_type << "\",\n";` ev.attack_type << "\",\n";
101 ` json_out_ << " \"src_ip\": \"" Executable statement. json_out_ << " \"src_ip\": \"" <<
<< ip_to_string(ev.src_ip) << ip_to_string(ev.src_ip) << "\",\n";
"\",\n";`
102 ` json_out_ << " \"src_port\": " Executable statement. json_out_ << " \"src_port\": " <<
<< ev.src_port << ",\n";` ev.src_port << ",\n";
103 ` json_out_ << " \"dst_ip\": \"" Executable statement. json_out_ << " \"dst_ip\": \"" <<
<< ip_to_string(ev.dst_ip) << ip_to_string(ev.dst_ip) << "\",\n";
"\",\n";`
104 ` json_out_ << " \"dst_port\": " Executable statement. json_out_ << " \"dst_port\": " <<
<< ev.dst_port << ",\n";` ev.dst_port << ",\n";
105 ` json_out_ << " \"protocol\": " Executable statement. json_out_ << " \"protocol\": " <<
<< static_cast<int>([Link]) << static_cast<int>([Link]) <<
",\n";` ",\n";
106 ` json_out_ << " \"final_score\": Executable statement. json_out_ << " \"final_score\": "
" << std::fixed << << std::fixed <<
std::setprecision(3) << std::setprecision(3) <<
ev.final_score << ",\n";` ev.final_score << ",\n
107 ` json_out_ << " \"confidence\": Executable statement. json_out_ << " \"confidence\": "
" << std::fixed << << std::fixed <<
std::setprecision(3) << std::setprecision(3) <<
[Link] << ",\n";` [Link] << ",\n";
108 ` json_out_ << " \"description\": Executable statement. json_out_ << " \"description\":
\"" << [Link] << "\",\n";` \"" << [Link] << "\",\n";

Page 122 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


109 ` json_out_ << " Executable statement. json_out_ << "
\"recommendation\": \"" << \"recommendation\": \"" <<
[Link] << "\",\n";` [Link] << "\",\n";
110 ` json_out_ << " Executable statement. json_out_ << " \"correlation_id\":
\"correlation_id\": \"" << \"" << ev.correlation_id << "\",\n";
ev.correlation_id << "\",\n";`
111 ` json_out_ << " Executable statement. json_out_ << "
\"correlation_boost\": " << std::fixed \"correlation_boost\": " <<
<< std::setprecision(3) << std::fixed << std::setprecision(3)
ev.correlation_boost << ",\n";` << ev.correlation_b
112 ` json_out_ << " Executable statement. json_out_ << "
\"flow_summary\": \"" << \"flow_summary\": \"" <<
ev.flow_summary << "\",\n";` ev.flow_summary << "\",\n";
113 ` json_out_ << " Executable statement. json_out_ << "
\"mitre_techniques\": [";` \"mitre_techniques\": [";
114 ` for (size_t i = 0; i < Loop over items or until for (size_t i = 0; i <
ev.mitre_techniques.size(); ++i) {` condition changes. ev.mitre_techniques.size(); ++i) {
115 ` if (i) json_out_ << ", ";` Conditional branch — run code if (i) json_out_ << ", ";
only when condition true.
116 ` json_out_ << "\"" << Executable statement. json_out_ << "\"" <<
ev.mitre_techniques[i] << "\"";` ev.mitre_techniques[i] << "\"";
117 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
118 ` json_out_ << "],\n";` Executable statement. json_out_ << "],\n";
119 ` json_out_ << " Executable statement. json_out_ << " \"mitre_tactics\":
\"mitre_tactics\": [";` [";
120 ` for (size_t i = 0; i < Loop over items or until for (size_t i = 0; i <
ev.mitre_tactics.size(); ++i) {` condition changes. ev.mitre_tactics.size(); ++i) {
121 ` if (i) json_out_ << ", ";` Conditional branch — run code if (i) json_out_ << ", ";
only when condition true.
122 ` json_out_ << "\"" << Executable statement. json_out_ << "\"" <<
ev.mitre_tactics[i] << "\"";` ev.mitre_tactics[i] << "\"";
123 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
124 ` json_out_ << "],\n";` Executable statement. json_out_ << "],\n";
125 ` json_out_ << " \"evidence\": Executable statement. json_out_ << " \"evidence\": [";
[";`
126 ` for (size_t i = 0; i < Loop over items or until for (size_t i = 0; i <
[Link](); ++i) {` condition changes. [Link](); ++i) {
127 ` if (i) json_out_ << ", ";` Conditional branch — run code if (i) json_out_ << ", ";
only when condition true.
128 ` json_out_ << "\"" << Executable statement. json_out_ << "\"" <<
[Link][i] << "\"";` [Link][i] << "\"";
129 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
130 ` json_out_ << "],\n";` Executable statement. json_out_ << "],\n";
131 ` json_out_ << " \"detectors\": Executable statement. json_out_ << " \"detectors\":
{\n";` {\n";
132 ` bool first = true;` Executable statement. bool first = true;

Page 123 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


133 ` for (const auto& dr : Loop over items or until for (const auto& dr :
ev.detector_results) {` condition changes. ev.detector_results) {
134 ` if (!first) json_out_ << ",\n";` Conditional branch — run code if (!first) json_out_ << ",\n";
only when condition true.
135 ` first = false;` Executable statement. first = false;
136 ` json_out_ << " \"" << Source code line. json_out_ << " \"" <<
dr.detector_name << "\": "` dr.detector_name << "\": "
137 ` << std::fixed << Executable statement. << std::fixed <<
std::setprecision(3) << [Link];` std::setprecision(3) << [Link];
138 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
139 ` json_out_ << "\n }\n";` Executable statement. json_out_ << "\n }\n";
140 ` json_out_ << " }";` Executable statement. json_out_ << " }";
141 ` json_out_.flush();` Executable statement. json_out_.flush();
142 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
143 `` Blank line for readability. Separator between code blocks.
144 `bool AlertSystem::send(const Final alert record sent to logs Enterprise alert struct.
AnomalyEvent& ev) {` and UI.
145 ` std::lock_guard<std::mutex> Lock a mutex so only one thread RAII mutex lock.
lock(mtx_);` uses shared data at a time.
146 ` if (!should_alert(ev.src_ip, Conditional branch — run code if (!should_alert(ev.src_ip,
ev.attack_type, ev.timestamp_us)) only when condition true. ev.attack_type,
return false;` ev.timestamp_us)) return false;
147 `` Blank line for readability. Separator between code blocks.
148 ` // Console alert (color by Comment documenting intent. Console alert (color by severity)
severity)`
149 ` const char* badge = "";` Named constant — value should const char* badge = "";
not change.
150 ` switch ([Link]) {` Source code line. switch ([Link]) {
151 ` case Severity::CRITICAL: Executable statement. case Severity::CRITICAL: badge
badge = C_RED_BG; break;` = C_RED_BG; break;
152 ` case Severity::HIGH: Executable statement. case Severity::HIGH: badge =
badge = C_RED; break;` C_RED; break;
153 ` case Severity::MEDIUM: Executable statement. case Severity::MEDIUM: badge
badge = C_YEL; break;` = C_YEL; break;
154 ` case Severity::LOW: Executable statement. case Severity::LOW: badge =
badge = C_CYAN; break;` C_CYAN; break;
155 ` default: badge = C_BLUE;` Executable statement. default: badge = C_BLUE;
156 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
157 ` std::cerr << "\n" << badge << "[" Source code line. std::cerr << "\n" << badge << "["
<< ts_string(ev.timestamp_us) << << ts_string(ev.timestamp_us) <<
"] "` "] "
158 ` << "[" << Source code line. << "[" <<
severity_to_string([Link]) << severity_to_string([Link]) <<
"] "` "] "

Page 124 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


159 ` << ev.attack_type << Executable statement. << ev.attack_type << C_RESET
C_RESET << "\n";` << "\n";
160 ` std::cerr << " " << C_BOLD << Source code line. std::cerr << " " << C_BOLD <<
"Source: " << C_RESET` "Source: " << C_RESET

Line Source Easy Technical Explanation


Explanation
161 ` << ip_to_string(ev.src_ip) << ":" << Source code line. << ip_to_string(ev.src_ip) << ":" <<
ev.src_port` ev.src_port
162 ` << " -> " << C_BOLD << "Target: " Source code line. << " -> " << C_BOLD << "Target:
<< C_RESET` " << C_RESET
163 ` << ip_to_string(ev.dst_ip) << ":" << Executable << ip_to_string(ev.dst_ip) << ":" <<
ev.dst_port << "\n";` statement. ev.dst_port << "\n";
164 ` std::cerr << " " << C_BOLD << "Score: " Source code line. std::cerr << " " << C_BOLD <<
<< C_RESET` "Score: " << C_RESET
165 ` << std::fixed << std::setprecision(2) Source code line. << std::fixed << std::setprecision(2)
<< ev.final_score` << ev.final_score
166 ` << " " << C_BOLD << "Confidence: Source code line. << " " << C_BOLD <<
" << C_RESET` "Confidence: " << C_RESET
167 ` << std::fixed << std::setprecision(2) Executable << std::fixed << std::setprecision(2)
<< [Link] << "\n";` statement. << [Link] << "\n";
168 ` for (const auto& dr : ev.detector_results) {` Loop over items or for (const auto& dr :
until condition ev.detector_results) {
changes.
169 ` if ([Link] > 0.0) {` Conditional branch if ([Link] > 0.0) {
— run code only
when condition
true.
170 ` std::cerr << " " << dr.detector_name Source code line. std::cerr << " " <<
<< "="` dr.detector_name << "="
171 ` << std::fixed << Executable << std::fixed << std::setprecision(2)
std::setprecision(2) << [Link];` statement. << [Link];
172 ` if (![Link]()) std::cerr << " (" Conditional branch if (![Link]()) std::cerr << "
<< [Link] << ")";` — run code only (" << [Link] << ")";
when condition
true.
173 ` std::cerr << "\n";` Executable std::cerr << "\n";
statement.
174 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
175 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
176 ` if (![Link]()) {` Conditional branch if (![Link]()) {
— run code only
when condition
true.

Page 125 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
177 ` std::cerr << " " << C_CYAN << "Detail: " Executable std::cerr << " " << C_CYAN <<
<< C_RESET << [Link] << "\n";` statement. "Detail: " << C_RESET <<
[Link] << "\n";
178 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
179 ` if (![Link]()) {` Conditional branch if (![Link]()) {
— run code only
when condition
true.
180 ` std::cerr << " " << C_YEL << "Action: " Executable std::cerr << " " << C_YEL <<
<< C_RESET << [Link] << "\n";` statement. "Action: " << C_RESET <<
[Link] << "\n";
181 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
182 `` Blank line for Separator between code blocks.
readability.
183 ` write_log(ev);` Executable write_log(ev);
statement.
184 ` write_json(ev);` Executable write_json(ev);
statement.
185 `` Blank line for Separator between code blocks.
readability.
186 ` recent_.push_back(ev);` Executable recent_.push_back(ev);
statement.
187 ` if (recent_.size() > MAX_RECENT) Conditional branch if (recent_.size() > MAX_RECENT)
recent_.pop_front();` — run code only recent_.pop_front();
when condition
true.
188 ` return true;` Exit function and return true;
give back a value.
189 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
190 `` Blank line for Separator between code blocks.
readability.
191 `std::deque<AnomalyEvent> Final alert record Enterprise alert struct.
AlertSystem::recent(size_t n) const {` sent to logs and UI.
192 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex so RAII mutex lock.
only one thread
uses shared data at
a time.
193 ` if (recent_.size() <= n) return recent_;` Conditional branch if (recent_.size() <= n) return
— run code only recent_;
when condition
true.

Page 126 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
194 ` return Final alert record Enterprise alert struct.
std::deque<AnomalyEvent>(recent_.end() - n, sent to logs and UI.
recent_.end());`
195 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
196 `` Blank line for Separator between code blocks.
readability.
197 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/baseline_engine.cpp
Total lines: 132

Lin Source Easy Technical Explanation


e Explanatio
n
1 `#include "baseline_engine.h"` Import #include "baseline_engine.h"
another
header file
into this
compilation
unit.
2 `#include "scoring_utils.h"` Import #include "scoring_utils.h"
another
header file
into this
compilation
unit.
3 `#include <algorithm>` Import #include <algorithm>
another
header file
into this
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a namespace nads {
named code
region so
names do not
clash
globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `BaselineEngine::BaselineEngine(const Config& cfg) : Named BaselineEngine::BaselineEngine(const
cfg_(cfg) {}` constant — Config& cfg) : cfg_(cfg) {}

Page 127 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
value should
not change.
8 `` Blank line for Separator between code blocks.
readability.
9 `double Named double
BaselineEngine::score_service(ServiceProfile& sp, constant — BaselineEngine::score_service(ServicePro
const FlowRecord& flow,` value should file& sp, const FlowRecord& flow,
not change.
10 ` std::vector<std::string>& flags) Source code std::vector<std::string>& flags) {
{` line.
11 ` double local = 0.0;` Executable double local = 0.0;
statement.
12 ` if (sp.flow_count >= 5) {` Conditional if (sp.flow_count >= 5) {
branch — run
code only
when
condition
true.
13 ` double zb = Compare Z-score or normalized score.
normalize_z([Link]([Link]), 3.0);` value to
learned
baseline
statistically.
14 ` double zs = Compare Z-score or normalized score.
normalize_z(sp.mean_pkt_size.zscore(flow.mean_pkt value to
_size), 3.0);` learned
baseline
statistically.
15 ` local = std::max(zb, zs);` Executable local = std::max(zb, zs);
statement.
16 ` if (zb > 0.7) scoring::append_unique_flag(flags, Conditional if (zb > 0.7)
"SERVICE_BPS_SPIKE");` branch — run scoring::append_unique_flag(flags,
code only "SERVICE_BPS_SPIKE");
when
condition
true.
17 ` if (zs > 0.7) scoring::append_unique_flag(flags, Conditional if (zs > 0.7)
"SERVICE_SIZE_SPIKE");` branch — run scoring::append_unique_flag(flags,
code only "SERVICE_SIZE_SPIKE");
when
condition
true.
18 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
19 ` [Link]([Link]);` Executable [Link]([Link]);
statement.
20 ` sp.mean_pkt_size.update(flow.mean_pkt_size);` Executable sp.mean_pkt_size.update(flow.mean_pkt_
statement. size);
21 ` sp.pkt_size_ring.update(flow.mean_pkt_size);` Executable sp.pkt_size_ring.update(flow.mean_pkt_si
statement. ze);

Page 128 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
22 ` sp.flow_count++;` Executable sp.flow_count++;
statement.
23 ` sp.last_seen_us = flow.last_seen_us;` Executable sp.last_seen_us = flow.last_seen_us;
statement.
24 ` return local;` Exit function return local;
and give back
a value.
25 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
26 `` Blank line for Separator between code blocks.
readability.
27 `double BaselineEngine::score_host(HostProfile& p, Named double
const FlowRecord& flow,` constant — BaselineEngine::score_host(HostProfile&
value should p, const FlowRecord& flow,
not change.
28 ` uint32_t peer_ip, Source code uint32_t peer_ip, std::vector<std::string>&
std::vector<std::string>& flags) {` line. flags) {
29 ` double local = 0.0;` Executable double local = 0.0;
statement.
30 `` Blank line for Separator between code blocks.
readability.
31 ` if (cfg_.adaptive_thresholds) {` Conditional if (cfg_.adaptive_thresholds) {
branch — run
code only
when
condition
true.
32 ` if (p.ewma_bps.ready(MIN_OBS)) {` Conditional if (p.ewma_bps.ready(MIN_OBS)) {
branch — run
code only
when
condition
true.
33 ` double zb = Compare Z-score or normalized score.
normalize_z(p.ewma_bps.zscore([Link]), 3.0);` value to
learned
baseline
statistically.
34 ` double zs = Compare Z-score or normalized score.
normalize_z(p.ewma_pkt_size.zscore(flow.mean_pkt_ value to
size), 3.0);` learned
baseline
statistically.
35 ` local = std::max(zb, zs);` Executable local = std::max(zb, zs);
statement.
36 ` if (zb > 0.7) Conditional if (zb > 0.7)
scoring::append_unique_flag(flags, branch — run scoring::append_unique_flag(flags,
"HOST_BPS_DEVIATION");` code only "HOST_BPS_DEVIATION");
when
condition
true.

Page 129 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
37 ` if (zs > 0.7) Conditional if (zs > 0.7)
scoring::append_unique_flag(flags, branch — run scoring::append_unique_flag(flags,
"HOST_SIZE_DEVIATION");` code only "HOST_SIZE_DEVIATION");
when
condition
true.
38 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
39 ` p.ewma_bps.update([Link]);` Executable p.ewma_bps.update([Link]);
statement.
40 ` p.ewma_pkt_size.update(flow.mean_pkt_size);` Executable p.ewma_pkt_size.update(flow.mean_pkt_s
statement. ize);
41 ` } else if ([Link]() >= MIN_OBS) {` Conditional } else if ([Link]() >= MIN_OBS) {
branch — run
code only
when
condition
true.
42 ` double zb = Compare Z-score or normalized score.
normalize_z(p.outbound_bps.zscore([Link]), 3.0);` value to
learned
baseline
statistically.
43 ` double zs = Compare Z-score or normalized score.
normalize_z(p.mean_pkt_size.zscore(flow.mean_pkt_ value to
size), 3.0);` learned
baseline
statistically.
44 ` local = std::max(zb, zs);` Executable local = std::max(zb, zs);
statement.
45 ` if (zb > 0.7) scoring::append_unique_flag(flags, Conditional if (zb > 0.7)
"HOST_BPS_DEVIATION");` branch — run scoring::append_unique_flag(flags,
code only "HOST_BPS_DEVIATION");
when
condition
true.
46 ` if (zs > 0.7) scoring::append_unique_flag(flags, Conditional if (zs > 0.7)
"HOST_SIZE_DEVIATION");` branch — run scoring::append_unique_flag(flags,
code only "HOST_SIZE_DEVIATION");
when
condition
true.
47 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
48 `` Blank line for Separator between code blocks.
readability.
49 ` bool new_peer = (p.known_peers.find(peer_ip) == Executable bool new_peer =
p.known_peers.end());` statement. (p.known_peers.find(peer_ip) ==
p.known_peers.end());

Page 130 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
50 ` if (new_peer) p.new_peers_this_hour++;` Conditional if (new_peer) p.new_peers_this_hour++;
branch — run
code only
when
condition
true.
51 `` Blank line for Separator between code blocks.
readability.
52 ` bool new_port = Executable bool new_port =
(p.known_dst_ports.find([Link].dst_port) == statement. (p.known_dst_ports.find([Link].dst_port)
p.known_dst_ports.end());` == p.known_dst_ports.end());
53 ` if (new_port && [Link]() > MIN_OBS) {` Conditional if (new_port && [Link]() >
branch — run MIN_OBS) {
code only
when
condition
true.
54 ` local = std::max(local, 0.3);` Executable local = std::max(local, 0.3);
statement.
55 ` scoring::append_unique_flag(flags, Executable scoring::append_unique_flag(flags,
"NEW_DST_PORT");` statement. "NEW_DST_PORT");
56 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
57 ` if (p.new_peers_this_hour > 50 && Conditional if (p.new_peers_this_hour > 50 &&
[Link]() > MIN_OBS) {` branch — run [Link]() > MIN_OBS) {
code only
when
condition
true.
58 ` local = std::max(local, 0.7);` Executable local = std::max(local, 0.7);
statement.
59 ` scoring::append_unique_flag(flags, Executable scoring::append_unique_flag(flags,
"FAST_PEER_EXPANSION");` statement. "FAST_PEER_EXPANSION");
60 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
61 ` if (new_peer && Conditional if (new_peer &&
scoring::is_admin_port([Link].dst_port) && branch — run scoring::is_admin_port([Link].dst_port)
[Link]() > MIN_OBS) {` code only && [Link]() >
when
condition
true.
62 ` local = std::max(local, 0.75);` Executable local = std::max(local, 0.75);
statement.
63 ` scoring::append_unique_flag(flags, Executable scoring::append_unique_flag(flags,
"LATERAL_MOVEMENT_SUSPECT");` statement. "LATERAL_MOVEMENT_SUSPECT");
64 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 131 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
65 `` Blank line for Separator between code blocks.
readability.
66 ` p.outbound_bps.update([Link]);` Executable p.outbound_bps.update([Link]);
statement.
67 ` p.mean_pkt_size.update(flow.mean_pkt_size);` Executable p.mean_pkt_size.update(flow.mean_pkt_si
statement. ze);
68 ` double dur_s = (flow.last_seen_us - Executable double dur_s = (flow.last_seen_us -
flow.first_seen_us) / 1e6;` statement. flow.first_seen_us) / 1e6;
69 ` if (dur_s > 0.0) Conditional if (dur_s > 0.0)
p.mean_flow_duration.update(dur_s);` branch — run p.mean_flow_duration.update(dur_s);
code only
when
condition
true.
70 ` p.known_peers.insert(peer_ip);` Executable p.known_peers.insert(peer_ip);
statement.
71 ` p.known_dst_ports.insert([Link].dst_port);` Executable p.known_dst_ports.insert([Link].dst_port
statement. );
72 `` Blank line for Separator between code blocks.
readability.
73 ` if (cfg_.use_per_service_baseline) {` Conditional if (cfg_.use_per_service_baseline) {
branch — run
code only
when
condition
true.
74 ` uint16_t svc_port = [Link].dst_port;` Executable uint16_t svc_port = [Link].dst_port;
statement.
75 ` auto sit = [Link](svc_port);` Executable auto sit = [Link](svc_port);
statement.
76 ` if (sit == [Link]()) {` Conditional if (sit == [Link]()) {
branch — run
code only
when
condition
true.
77 ` sit = [Link](` Insert into unordered_map insertion.
map if key
missing.
78 ` svc_port,` Source code svc_port,
line.
79 ` ServiceProfile(cfg_.ewma_alpha,` Source code ServiceProfile(cfg_.ewma_alpha,
line.
80 ` Source code static_cast<size_t>(cfg_.percentile_windo
static_cast<size_t>(cfg_.percentile_window))` line. w))

Line Source Easy Explanation Technical Explanation


81 ` ).first;` Executable statement. ).first;
82 ` sit->[Link] = svc_port;` Executable statement. sit->[Link] = svc_port;

Page 132 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


83 ` sit->[Link] = Executable statement. sit->[Link] =
[Link];` [Link];
84 ` sit->second.first_seen_us = Executable statement. sit->second.first_seen_us =
flow.first_seen_us;` flow.first_seen_us;
85 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
86 ` local = std::max(local, Executable statement. local = std::max(local,
score_service(sit->second, flow, score_service(sit->second, flow,
flags));` flags));
87 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
88 `` Blank line for Separator between code blocks.
readability.
89 ` return local;` Exit function and give return local;
back a value.
90 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
91 `` Blank line for Separator between code blocks.
readability.
92 `DetectorResult Build or return a score 0-1, flags, detail string.
BaselineEngine::analyze(const detector score result.
FlowRecord& flow) {`
93 ` DetectorResult res;` Build or return a score 0-1, flags, detail string.
detector score result.
94 ` res.detector_name = "baseline";` Executable statement. res.detector_name = "baseline";
95 `` Blank line for Separator between code blocks.
readability.
96 ` uint32_t ips[2] = {[Link].src_ip, Executable statement. uint32_t ips[2] = {[Link].src_ip,
[Link].dst_ip};` [Link].dst_ip};
97 ` double max_score = 0.0;` Executable statement. double max_score = 0.0;
98 ` std::vector<std::string> flags;` Executable statement. std::vector<std::string> flags;
99 `` Blank line for Separator between code blocks.
readability.
100 ` for (int side = 0; side < 2; ++side) {` Loop over items or until for (int side = 0; side < 2; ++side) {
condition changes.
101 ` uint32_t host_ip = ips[side];` Executable statement. uint32_t host_ip = ips[side];
102 ` uint32_t peer_ip = ips[1 - side];` Executable statement. uint32_t peer_ip = ips[1 - side];
103 `` Blank line for Separator between code blocks.
readability.
104 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lock(mtx_);` one thread uses
shared data at a time.
105 ` auto [it, inserted] = Insert into map if key unordered_map insertion.
hosts_.try_emplace(host_ip);` missing.
106 ` HostProfile& p = it->second;` Executable statement. HostProfile& p = it->second;

Page 133 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


107 ` if (inserted) {` Conditional branch — if (inserted) {
run code only when
condition true.
108 ` [Link] = host_ip;` Executable statement. [Link] = host_ip;
109 ` p.first_seen_us = Executable statement. p.first_seen_us = flow.first_seen_us;
flow.first_seen_us;`
110 ` p.hour_window_start_us = Executable statement. p.hour_window_start_us =
flow.first_seen_us;` flow.first_seen_us;
111 ` p.ewma_bps = Executable statement. p.ewma_bps =
EwmaStats(cfg_.ewma_alpha);` EwmaStats(cfg_.ewma_alpha);
112 ` p.ewma_pkt_size = Executable statement. p.ewma_pkt_size =
EwmaStats(cfg_.ewma_alpha);` EwmaStats(cfg_.ewma_alpha);
113 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
114 ` p.last_seen_us = Executable statement. p.last_seen_us = flow.last_seen_us;
flow.last_seen_us;`
115 ` p.connections_total++;` Executable statement. p.connections_total++;
116 `` Blank line for Separator between code blocks.
readability.
117 ` if (flow.last_seen_us - Conditional branch — if (flow.last_seen_us -
p.hour_window_start_us > 3600LL * run code only when p.hour_window_start_us > 3600LL *
1000000LL) {` condition true. 1000000LL) {
118 ` p.hour_window_start_us = Executable statement. p.hour_window_start_us =
flow.last_seen_us;` flow.last_seen_us;
119 ` p.new_peers_this_hour = 0;` Executable statement. p.new_peers_this_hour = 0;
120 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
121 `` Blank line for Separator between code blocks.
readability.
122 ` max_score = Executable statement. max_score = std::max(max_score,
std::max(max_score, score_host(p, score_host(p, flow, peer_ip, flags));
flow, peer_ip, flags));`
123 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
124 `` Blank line for Separator between code blocks.
readability.
125 ` [Link] = max_score;` Executable statement. [Link] = max_score;
126 ` res.is_anomaly = max_score > 0.6;` Executable statement. res.is_anomaly = max_score > 0.6;
127 ` [Link] = std::move(flags);` Executable statement. [Link] = std::move(flags);
128 ` [Link] = "both hosts";` Executable statement. [Link] = "both hosts";
129 ` return res;` Exit function and give return res;
back a value.
130 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

Page 134 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


131 `` Blank line for Separator between code blocks.
readability.
132 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/[Link]
Total lines: 108

Line Source Easy Technical Explanation


Explanation
1 `// [Link] - libpcap wrapper Comment [Link] - libpcap wrapper
implementation` documenting implementation
intent.
2 `#include "capture.h"` Import another #include "capture.h"
header file into
this compilation
unit.
3 `#include <pcap.h>` Import another #include <pcap.h>
header file into
this compilation
unit.
4 `#include <iostream>` Import another #include <iostream>
header file into
this compilation
unit.
5 `#include <cstring>` Import another #include <cstring>
header file into
this compilation
unit.
6 `` Blank line for Separator between code blocks.
readability.
7 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
8 `` Blank line for Separator between code blocks.
readability.
9 `PacketCapture::PacketCapture(const Named PacketCapture::PacketCapture(const
std::string& interface,` constant — std::string& interface,
value should
not change.
10 ` const std::string& Named const std::string& bpf_filter,
bpf_filter,` constant —
value should
not change.
11 ` Source code ConcurrentQueue<PacketInfo>&
ConcurrentQueue<PacketInfo>& line. out_queue,
out_queue,`

Page 135 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
12 ` LiveStats& stats)` Source code LiveStats& stats)
line.
13 ` : interface_(interface), Source code : interface_(interface),
bpf_filter_(bpf_filter),` line. bpf_filter_(bpf_filter),
14 ` queue_(out_queue), stats_(stats) {}` Source code queue_(out_queue), stats_(stats) {}
line.
15 `` Blank line for Separator between code blocks.
readability.
16 `PacketCapture::~PacketCapture() {` Source code PacketCapture::~PacketCapture() {
line.
17 ` stop();` Executable stop();
statement.
18 ` if (handle_) {` Conditional if (handle_) {
branch — run
code only when
condition true.
19 ` pcap_close(handle_);` libpcap network pcap_close(handle_);
capture API
call.
20 ` handle_ = nullptr;` Executable handle_ = nullptr;
statement.
21 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
22 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
23 `` Blank line for Separator between code blocks.
readability.
24 `bool PacketCapture::open() {` Source code bool PacketCapture::open() {
line.
25 ` char errbuf[PCAP_ERRBUF_SIZE] = Executable char errbuf[PCAP_ERRBUF_SIZE] = {0};
{0};` statement.
26 ` handle_ = libpcap network handle_ =
pcap_open_live(interface_.c_str(),` capture API pcap_open_live(interface_.c_str(),
call.
27 ` 65535, // snaplen` Source code 65535, // snaplen
line.
28 ` 1, // promisc` Source code 1, // promisc
line.
29 ` 100, // read timeout Source code 100, // read timeout ms
ms` line.
30 ` errbuf);` Executable errbuf);
statement.
31 ` if (!handle_) {` Conditional if (!handle_) {
branch — run
code only when
condition true.

Page 136 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
32 ` last_error_ = libpcap network last_error_ = std::string("pcap_open_live
std::string("pcap_open_live failed: ") + capture API failed: ") + errbuf;
errbuf;` call.
33 ` return false;` Exit function return false;
and give back a
value.
34 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
35 `` Blank line for Separator between code blocks.
readability.
36 ` link_type_ = pcap_datalink(handle_);` libpcap network link_type_ = pcap_datalink(handle_);
capture API
call.
37 `` Blank line for Separator between code blocks.
readability.
38 ` if (!bpf_filter_.empty()) {` Conditional if (!bpf_filter_.empty()) {
branch — run
code only when
condition true.
39 ` struct bpf_program prog;` Executable struct bpf_program prog;
statement.
40 ` bpf_u_int32 net = 0, mask = 0;` Executable bpf_u_int32 net = 0, mask = 0;
statement.
41 ` pcap_lookupnet(interface_.c_str(), libpcap network pcap_lookupnet(interface_.c_str(), &net,
&net, &mask, errbuf);` capture API &mask, errbuf);
call.
42 ` if (pcap_compile(handle_, &prog, libpcap network if (pcap_compile(handle_, &prog,
bpf_filter_.c_str(), 1, mask) == -1) {` capture API bpf_filter_.c_str(), 1, mask) == -1) {
call.
43 ` last_error_ = libpcap network last_error_ = std::string("pcap_compile
std::string("pcap_compile failed: ") + capture API failed: ") + pcap_geterr(handle_);
pcap_geterr(handle_);` call.
44 ` return false;` Exit function return false;
and give back a
value.
45 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
46 ` if (pcap_setfilter(handle_, &prog) == libpcap network if (pcap_setfilter(handle_, &prog) == -1) {
-1) {` capture API
call.
47 ` last_error_ = libpcap network last_error_ = std::string("pcap_setfilter
std::string("pcap_setfilter failed: ") + capture API failed: ") + pcap_geterr(handle_);
pcap_geterr(handle_);` call.
48 ` pcap_freecode(&prog);` libpcap network pcap_freecode(&prog);
capture API
call.

Page 137 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
49 ` return false;` Exit function return false;
and give back a
value.
50 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
51 ` pcap_freecode(&prog);` libpcap network pcap_freecode(&prog);
capture API
call.
52 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
53 ` return true;` Exit function return true;
and give back a
value.
54 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
55 `` Blank line for Separator between code blocks.
readability.
56 `bool libpcap network bool PacketCapture::open_pcap_file(const
PacketCapture::open_pcap_file(const capture API std::string& path) {
std::string& path) {` call.
57 ` char errbuf[PCAP_ERRBUF_SIZE] = Executable char errbuf[PCAP_ERRBUF_SIZE] = {0};
{0};` statement.
58 ` handle_ = libpcap network handle_ = pcap_open_offline(path.c_str(),
pcap_open_offline(path.c_str(), errbuf);` capture API errbuf);
call.
59 ` if (!handle_) {` Conditional if (!handle_) {
branch — run
code only when
condition true.
60 ` last_error_ = libpcap network last_error_ =
std::string("pcap_open_offline failed: ") + capture API std::string("pcap_open_offline failed: ") +
errbuf;` call. errbuf;
61 ` return false;` Exit function return false;
and give back a
value.
62 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
63 ` link_type_ = pcap_datalink(handle_);` libpcap network link_type_ = pcap_datalink(handle_);
capture API
call.
64 ` return true;` Exit function return true;
and give back a
value.
65 `}` Brace or C/C++ syntax structure.
parenthesis

Page 138 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
66 `` Blank line for Separator between code blocks.
readability.
67 `void PacketCapture::start() {` Source code void PacketCapture::start() {
line.
68 ` if (!handle_) return;` Conditional if (!handle_) return;
branch — run
code only when
condition true.
69 ` running_ = true;` Executable running_ = true;
statement.
70 ` thread_ = Executable thread_ =
std::thread(&PacketCapture::capture_loop, statement. std::thread(&PacketCapture::capture_loop,
this);` this);
71 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
72 `` Blank line for Separator between code blocks.
readability.
73 `void PacketCapture::stop() {` Source code void PacketCapture::stop() {
line.
74 ` if (running_.exchange(false)) {` Conditional if (running_.exchange(false)) {
branch — run
code only when
condition true.
75 ` if (handle_) libpcap network if (handle_) pcap_breakloop(handle_);
pcap_breakloop(handle_);` capture API
call.
76 ` if (thread_.joinable()) thread_.join();` Conditional if (thread_.joinable()) thread_.join();
branch — run
code only when
condition true.
77 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
78 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
79 `` Blank line for Separator between code blocks.
readability.
80 `void Source code void
PacketCapture::packet_callback(unsigned line. PacketCapture::packet_callback(unsigned
char* user,` char* user,

Page 139 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
81 ` const struct libpcap network const struct ::pcap_pkthdr* hdr,
::pcap_pkthdr* hdr,` capture API
call.
82 ` const unsigned char* Named const unsigned char* bytes) {
bytes) {` constant —
value should
not change.
83 ` auto* self = Executable auto* self =
reinterpret_cast<PacketCapture*>(user);` statement. reinterpret_cast<PacketCapture*>(user);
84 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
85 ` pkt.timestamp_us = Source code pkt.timestamp_us =
static_cast<int64_t>(hdr->ts.tv_sec) * line. static_cast<int64_t>(hdr->ts.tv_sec) *
1000000LL` 1000000LL
86 ` + static_cast<int64_t>(hdr- Executable + static_cast<int64_t>(hdr->ts.tv_usec);
>ts.tv_usec);` statement.
87 ` [Link] = hdr->len;` Executable [Link] = hdr->len;
statement.
88 ` pkt.cap_length = hdr->caplen;` Executable pkt.cap_length = hdr->caplen;
statement.
89 ` pkt.raw_bytes.assign(bytes, bytes + hdr- Executable pkt.raw_bytes.assign(bytes, bytes + hdr-
>caplen);` statement. >caplen);
90 `` Blank line for Separator between code blocks.
readability.
91 ` self- Thread-safe std::memory_order relaxed typical.
>stats_.total_packets_captured.fetch_add(1, update or read
std::memory_order_relaxed);` of a statistic.
92 ` self->stats_.total_bytes.fetch_add(hdr- Thread-safe std::memory_order relaxed typical.
>len, std::memory_order_relaxed);` update or read
of a statistic.
93 `` Blank line for Separator between code blocks.
readability.
94 ` if (!self->queue_.push(std::move(pkt))) {` Conditional if (!self->queue_.push(std::move(pkt))) {
branch — run
code only when
condition true.
95 ` self- Thread-safe std::memory_order relaxed typical.
>stats_.total_packets_dropped.fetch_add(1, update or read
std::memory_order_relaxed);` of a statistic.
96 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
97 ` self->stats_.queue_size.store(self- Thread-safe std::memory_order relaxed typical.
>queue_.size(), update or read
std::memory_order_relaxed);` of a statistic.
98 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
99 `` Blank line for Separator between code blocks.
readability.

Page 140 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
100 `void PacketCapture::capture_loop() {` Source code void PacketCapture::capture_loop() {
line.
101 ` int rc = pcap_loop(handle_, -1,` libpcap network int rc = pcap_loop(handle_, -1,
capture API
call.
102 ` Source code PacketCapture::packet_callback,
PacketCapture::packet_callback,` line.
103 ` reinterpret_cast<unsigned Executable reinterpret_cast<unsigned char*>(this));
char*>(this));` statement.
104 ` (void)rc; // -2 means broken by libpcap network (void)rc; // -2 means broken by
pcap_breakloop, anything else means capture API pcap_breakloop, anything else means
EOF/err` call. EOF/err
105 ` running_ = false;` Executable running_ = false;
statement.
106 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
107 `` Blank line for Separator between code blocks.
readability.
108 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/config_loader.cpp
Total lines: 90

Line Source Easy Technical Explanation


Explanation
1 `#include "config_loader.h"` Import another #include "config_loader.h"
header file into this
compilation unit.
2 `#include <fstream>` Import another #include <fstream>
header file into this
compilation unit.
3 `#include <cmath>` Import another #include <cmath>
header file into this
compilation unit.
4 `#include <cctype>` Import another #include <cctype>
header file into this
compilation unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.

Page 141 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
7 `` Blank line for Separator between code blocks.
readability.
8 `static void trim(std::string& s) {` Source code line. static void trim(std::string& s) {
9 ` while (![Link]() && Loop over items or while (![Link]() &&
std::isspace(static_cast<unsigned until condition std::isspace(static_cast<unsigned
char>([Link]()))) [Link]([Link]());` changes. char>([Link]()))) [Link]
10 ` while (![Link]() && Loop over items or while (![Link]() &&
std::isspace(static_cast<unsigned until condition std::isspace(static_cast<unsigned
char>([Link]()))) s.pop_back();` changes. char>([Link]()))) s.pop_b
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
12 `` Blank line for Separator between code blocks.
readability.
13 `static bool parse_bool(const std::string& Named constant — static bool parse_bool(const std::string&
v) {` value should not v) {
change.
14 ` return v == "1" \ \ v == "true" \
15 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
16 `` Blank line for Separator between code blocks.
readability.
17 `bool load_config_file(Config& cfg, const Named constant — bool load_config_file(Config& cfg, const
std::string& path) {` value should not std::string& path) {
change.
18 ` std::ifstream in(path);` Executable std::ifstream in(path);
statement.
19 ` if (!in) return false;` Conditional branch if (!in) return false;
— run code only
when condition true.
20 ` std::string line;` Executable std::string line;
statement.
21 ` while (std::getline(in, line)) {` Loop over items or while (std::getline(in, line)) {
until condition
changes.
22 ` if ([Link]() \ \ line[0] == '#') continue;`
23 ` auto eq = [Link]('=');` Executable auto eq = [Link]('=');
statement.
24 ` if (eq == std::string::npos) Conditional branch if (eq == std::string::npos) continue;
continue;` — run code only
when condition true.
25 ` std::string key = [Link](0, eq);` Executable std::string key = [Link](0, eq);
statement.
26 ` std::string val = [Link](eq + 1);` Executable std::string val = [Link](eq + 1);
statement.
27 ` trim(key);` Executable trim(key);
statement.

Page 142 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
28 ` trim(val);` Executable trim(val);
statement.
29 `` Blank line for Separator between code blocks.
readability.
30 ` if (key == "interface") Conditional branch if (key == "interface")
[Link] = val;` — run code only [Link] = val;
when condition true.
31 ` else if (key == "bpf_filter") Executable else if (key == "bpf_filter")
cfg.bpf_filter = val;` statement. cfg.bpf_filter = val;
32 ` else if (key == "output_log") Executable else if (key == "output_log")
cfg.output_log = val;` statement. cfg.output_log = val;
33 ` else if (key == "json_output") Executable else if (key == "json_output")
cfg.json_output = val;` statement. cfg.json_output = val;
34 ` else if (key == "alert_threshold") Executable else if (key == "alert_threshold")
cfg.alert_threshold = std::stod(val);` statement. cfg.alert_threshold = std::stod(val);
35 ` else if (key == "critical_threshold") Executable else if (key == "critical_threshold")
cfg.critical_threshold = std::stod(val);` statement. cfg.critical_threshold = std::stod(val);
36 ` else if (key == "flow_timeout_sec") Executable else if (key == "flow_timeout_sec")
cfg.flow_timeout_sec = std::stoi(val);` statement. cfg.flow_timeout_sec = std::stoi(val);
37 ` else if (key == "window_seconds") Executable else if (key == "window_seconds")
cfg.window_seconds = std::stoi(val);` statement. cfg.window_seconds = std::stoi(val);
38 ` else if (key == "w_statistical") Executable else if (key == "w_statistical")
cfg.w_statistical = std::stod(val);` statement. cfg.w_statistical = std::stod(val);
39 ` else if (key == "w_volume") Executable else if (key == "w_volume")
cfg.w_volume = std::stod(val);` statement. cfg.w_volume = std::stod(val);
40 ` else if (key == "w_protocol") Executable else if (key == "w_protocol")
cfg.w_protocol = std::stod(val);` statement. cfg.w_protocol = std::stod(val);
41 ` else if (key == "w_baseline") Executable else if (key == "w_baseline")
cfg.w_baseline = std::stod(val);` statement. cfg.w_baseline = std::stod(val);
42 ` else if (key == "w_graph") Executable else if (key == "w_graph")
cfg.w_graph = std::stod(val);` statement. cfg.w_graph = std::stod(val);
43 ` else if (key == "w_temporal") Executable else if (key == "w_temporal")
cfg.w_temporal = std::stod(val);` statement. cfg.w_temporal = std::stod(val);
44 ` else if (key == "w_entropy") Executable else if (key == "w_entropy")
cfg.w_entropy = std::stod(val);` statement. cfg.w_entropy = std::stod(val);
45 ` else if (key == Executable else if (key ==
"syn_flood_threshold_pps") statement. "syn_flood_threshold_pps")
cfg.syn_flood_threshold_pps = cfg.syn_flood_threshold_pps =
std::stod(val);` std::stod(val);
46 ` else if (key == Executable else if (key ==
"packet_flood_threshold_pps") statement. "packet_flood_threshold_pps")
cfg.packet_flood_threshold_pps = cfg.packet_flood_threshold_pps =
std::stod(val);` std::stod(val);
47 ` else if (key == "ewma_alpha") Executable else if (key == "ewma_alpha")
cfg.ewma_alpha = std::stod(val);` statement. cfg.ewma_alpha = std::stod(val);
48 ` else if (key == Executable else if (key == "percentile_window")
"percentile_window") statement. cfg.percentile_window = std::stoi(val);
cfg.percentile_window = std::stoi(val);`

Page 143 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
49 ` else if (key == Executable else if (key == "adaptive_thresholds")
"adaptive_thresholds") statement. cfg.adaptive_thresholds =
cfg.adaptive_thresholds = parse_bool(val);
parse_bool(val);`
50 ` else if (key == "fusion_type") {` Combine multiple Fusion / correlation logic.
detector scores.
51 ` cfg.fusion_type = val;` Combine multiple Fusion / correlation logic.
detector scores.
52 ` if (val == "logistic") Conditional branch if (val == "logistic")
cfg.use_logistic_fusion = true;` — run code only cfg.use_logistic_fusion = true;
when condition true.
53 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
54 ` else if (key == Executable else if (key == "use_logistic_fusion")
"use_logistic_fusion") statement. cfg.use_logistic_fusion =
cfg.use_logistic_fusion = parse_bool(val);
parse_bool(val);`
55 ` else if (key == Combine multiple Fusion / correlation logic.
"fusion_weights_path") detector scores.
cfg.fusion_weights_path = val;`
56 ` else if (key == Combine multiple Fusion / correlation logic.
"fusion_learning_rate") detector scores.
cfg.fusion_learning_rate = std::stod(val);`
57 ` else if (key == Executable else if (key ==
"correlation_window_sec") statement. "correlation_window_sec")
cfg.correlation_window_sec = cfg.correlation_window_sec =
std::stoi(val);` std::stoi(val);
58 ` else if (key == Executable else if (key ==
"use_per_service_baseline") statement. "use_per_service_baseline")
cfg.use_per_service_baseline = cfg.use_per_service_baseline =
parse_bool(val);` parse_bool(val);
59 ` else if (key == "metrics_enabled") Executable else if (key == "metrics_enabled")
cfg.metrics_enabled = parse_bool(val);` statement. cfg.metrics_enabled = parse_bool(val);
60 ` else if (key == "webhook_url") Executable else if (key == "webhook_url")
cfg.webhook_url = val;` statement. cfg.webhook_url = val;
61 ` else if (key == Executable else if (key == "enable_slow_scan")
"enable_slow_scan") statement. cfg.enable_slow_scan =
cfg.enable_slow_scan = parse_bool(val);
parse_bool(val);`
62 ` else if (key == Executable else if (key ==
"enable_beacon_detector") statement. "enable_beacon_detector")
cfg.enable_beacon_detector = cfg.enable_beacon_detector =
parse_bool(val);` parse_bool(val);
63 ` else if (key == Executable else if (key == "enable_burst_detector")
"enable_burst_detector") statement. cfg.enable_burst_detector =
cfg.enable_burst_detector = parse_bool(val);
parse_bool(val);`
64 ` else if (key == Executable else if (key == "enable_dns_tunnel")
"enable_dns_tunnel") statement. cfg.enable_dns_tunnel =
cfg.enable_dns_tunnel = parse_bool(val);
parse_bool(val);`

Page 144 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
65 ` else if (key == "enable_syn_ratio") Executable else if (key == "enable_syn_ratio")
cfg.enable_syn_ratio = parse_bool(val);` statement. cfg.enable_syn_ratio = parse_bool(val);
66 ` else if (key == Executable else if (key ==
"enable_long_lived_flow") statement. "enable_long_lived_flow")
cfg.enable_long_lived_flow = cfg.enable_long_lived_flow =
parse_bool(val);` parse_bool(val);
67 ` else if (key == Combine multiple Fusion / correlation logic.
"use_legacy_fusion_boost") detector scores.
cfg.use_legacy_fusion_boost =
parse_bool(val);`
68 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
69 ` return true;` Exit function and return true;
give back a value.
70 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
71 `` Blank line for Separator between code blocks.
readability.
72 `bool validate_config(const Config& cfg, Named constant — bool validate_config(const Config& cfg,
std::string* err) {` value should not std::string* err) {
change.
73 ` auto fail = [&](const char* msg) {` Named constant — auto fail = [&](const char* msg) {
value should not
change.
74 ` if (err) *err = msg;` Conditional branch if (err) *err = msg;
— run code only
when condition true.
75 ` return false;` Exit function and return false;
give back a value.
76 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
77 ` if (cfg.alert_threshold < 0.0 \ \ cfg.alert_threshold > 1.0)`
78 ` return fail("alert_threshold must be Exit function and return fail("alert_threshold must be in
in [0,1]");` give back a value. [0,1]");
79 ` if (cfg.ewma_alpha <= 0.0 \ \ cfg.ewma_alpha > 1.0)`
80 ` return fail("ewma_alpha must be in Exit function and return fail("ewma_alpha must be in
(0,1]");` give back a value. (0,1]");

Line Source Easy Explanation Technical Explanation


81 ` if (cfg.percentile_window < 16 \ \ cfg.percentile_window > 4096)`
82 ` return fail("percentile_window Exit function and give back return fail("percentile_window must
must be in [16,4096]");` a value. be in [16,4096]");
83 ` double wsum = cfg.w_statistical + Source code line. double wsum = cfg.w_statistical +
cfg.w_volume + cfg.w_protocol +` cfg.w_volume + cfg.w_protocol +

Page 145 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


84 ` cfg.w_baseline + Executable statement. cfg.w_baseline + cfg.w_graph +
cfg.w_graph + cfg.w_temporal + cfg.w_temporal + cfg.w_entropy;
cfg.w_entropy;`
85 ` if (std::fabs(wsum - 1.0) > 0.25)` Conditional branch — run if (std::fabs(wsum - 1.0) > 0.25)
code only when condition
true.
86 ` return fail("detector weights Exit function and give back return fail("detector weights should
should sum to ~1.0");` a value. sum to ~1.0");
87 ` return true;` Exit function and give back return true;
a value.
88 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
89 `` Blank line for readability. Separator between code blocks.
90 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/src/console_display.cpp
Total lines: 390

Line Source Easy Technical Explanation


Explanation
1 `// console_display.cpp - the live ANSI Comment console_display.cpp - the live ANSI
dashboard` documenting dashboard
intent.
2 `// Designed to look like a real SOC tool: full- Comment Designed to look like a real SOC tool: full-
width frame, colored panels,` documenting width frame, colored panels,
intent.
3 `// live counters, sparkline, top talkers, Comment live counters, sparkline, top talkers, scrolling
scrolling alert feed.` documenting alert feed.
intent.
4 `#include "console_display.h"` Import another #include "console_display.h"
header file into
this compilation
unit.
5 `#include <iostream>` Import another #include <iostream>
header file into
this compilation
unit.
6 `#include <sstream>` Import another #include <sstream>
header file into
this compilation
unit.
7 `#include <iomanip>` Import another #include <iomanip>
header file into
this compilation
unit.
8 `#include <chrono>` Import another #include <chrono>
header file into

Page 146 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
this compilation
unit.
9 `#include <thread>` Import another #include <thread>
header file into
this compilation
unit.
10 `#include <algorithm>` Import another #include <algorithm>
header file into
this compilation
unit.
11 `#include <vector>` Import another #include <vector>
header file into
this compilation
unit.
12 `#include <cstdio>` Import another #include <cstdio>
header file into
this compilation
unit.
13 `#include <ctime>` Import another #include <ctime>
header file into
this compilation
unit.
14 `#include <cmath>` Import another #include <cmath>
header file into
this compilation
unit.
15 `` Blank line for Separator between code blocks.
readability.
16 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
17 `` Blank line for Separator between code blocks.
readability.
18 `// ANSI helpers` Comment ANSI helpers
documenting
intent.
19 `static const char* RESET = "\033[0m";` Named static const char* RESET = "\033[0m";
constant —
value should
not change.
20 `static const char* BOLD = "\033[1m";` Named static const char* BOLD = "\033[1m";
constant —
value should
not change.
21 `// DIM reserved for future muted text styling` Comment DIM reserved for future muted text styling
documenting
intent.
22 `static const char* HIDE = "\033[?25l";` Named static const char* HIDE = "\033[?25l";
constant —
value should
not change.

Page 147 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
23 `static const char* SHOW = "\033[?25h";` Named static const char* SHOW = "\033[?25h";
constant —
value should
not change.
24 `static const char* CLEAR = "\033[2J";` Named static const char* CLEAR = "\033[2J";
constant —
value should
not change.
25 `static const char* HOME = "\033[H";` Named static const char* HOME = "\033[H";
constant —
value should
not change.
26 `` Blank line for Separator between code blocks.
readability.
27 `// Truecolor codes (24-bit RGB)` Comment Truecolor codes (24-bit RGB)
documenting
intent.
28 `static std::string fg(int r, int g, int b) {` Source code static std::string fg(int r, int g, int b) {
line.
29 ` char b2[32];` Executable char b2[32];
statement.
30 ` std::snprintf(b2, sizeof(b2), Executable std::snprintf(b2, sizeof(b2),
"\033[38;2;%d;%d;%dm", r, g, b);` statement. "\033[38;2;%d;%d;%dm", r, g, b);
31 ` return b2;` Exit function return b2;
and give back
a value.
32 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
33 `static std::string bg(int r, int g, int b) {` Source code static std::string bg(int r, int g, int b) {
line.
34 ` char b2[32];` Executable char b2[32];
statement.
35 ` std::snprintf(b2, sizeof(b2), Executable std::snprintf(b2, sizeof(b2),
"\033[48;2;%d;%d;%dm", r, g, b);` statement. "\033[48;2;%d;%d;%dm", r, g, b);
36 ` return b2;` Exit function return b2;
and give back
a value.
37 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
38 `` Blank line for Separator between code blocks.
readability.
39 `// Custom palette - dark, professional SOC Comment Custom palette - dark, professional SOC
look` documenting look
intent.
40 `static const std::string FG_BORDER = Named static const std::string FG_BORDER =
fg(80, 100, 130);` constant — fg(80, 100, 130);
value should
not change.

Page 148 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
41 `static const std::string FG_TITLE = Named static const std::string FG_TITLE =
fg(180, 220, 255);` constant — fg(180, 220, 255);
value should
not change.
42 `static const std::string FG_LABEL = Named static const std::string FG_LABEL =
fg(140, 170, 200);` constant — fg(140, 170, 200);
value should
not change.
43 `static const std::string FG_VALUE = Named static const std::string FG_VALUE =
fg(220, 230, 245);` constant — fg(220, 230, 245);
value should
not change.
44 `static const std::string FG_ACCENT_OK = Named static const std::string FG_ACCENT_OK =
fg(120, 220, 130);` constant — fg(120, 220, 130);
value should
not change.
45 `static const std::string Named static const std::string
FG_ACCENT_WARN= fg(255, 200, 90);` constant — FG_ACCENT_WARN= fg(255, 200, 90);
value should
not change.
46 `static const std::string FG_ACCENT_BAD = Named static const std::string FG_ACCENT_BAD =
fg(255, 90, 90);` constant — fg(255, 90, 90);
value should
not change.
47 `static const std::string FG_ACCENT_INFO= Named static const std::string FG_ACCENT_INFO=
fg(120, 200, 245);` constant — fg(120, 200, 245);
value should
not change.
48 `static const std::string FG_DIM = fg(95, Named static const std::string FG_DIM = fg(95,
115, 140);` constant — 115, 140);
value should
not change.
49 `static const std::string FG_SPARK = Named static const std::string FG_SPARK =
fg(150, 220, 255);` constant — fg(150, 220, 255);
value should
not change.
50 `static const std::string BG_HEAD = Named static const std::string BG_HEAD =
bg(20, 30, 50);` constant — bg(20, 30, 50);
value should
not change.
51 `` Blank line for Separator between code blocks.
readability.
52 `ConsoleDisplay::ConsoleDisplay(LiveStats& Named ConsoleDisplay::ConsoleDisplay(LiveStats&
stats, AlertSystem& alerts, const Config& constant — stats, AlertSystem& alerts, const Conf
cfg)` value should
not change.
53 ` : stats_(stats), alerts_(alerts), cfg_(cfg) {}` Source code : stats_(stats), alerts_(alerts), cfg_(cfg) {}
line.
54 `` Blank line for Separator between code blocks.
readability.
55 `ConsoleDisplay::~ConsoleDisplay() {` Source code ConsoleDisplay::~ConsoleDisplay() {
line.

Page 149 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
56 ` stop();` Executable stop();
statement.
57 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
58 `` Blank line for Separator between code blocks.
readability.
59 `void ConsoleDisplay::start() {` Source code void ConsoleDisplay::start() {
line.
60 ` if (cfg_.no_dashboard) return;` Conditional if (cfg_.no_dashboard) return;
branch — run
code only when
condition true.
61 ` running_ = true;` Executable running_ = true;
statement.
62 ` thread_ = Executable thread_ = std::thread(&ConsoleDisplay::run,
std::thread(&ConsoleDisplay::run, this);` statement. this);
63 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
64 `` Blank line for Separator between code blocks.
readability.
65 `void ConsoleDisplay::stop() {` Source code void ConsoleDisplay::stop() {
line.
66 ` if (running_.exchange(false)) {` Conditional if (running_.exchange(false)) {
branch — run
code only when
condition true.
67 ` if (thread_.joinable()) thread_.join();` Conditional if (thread_.joinable()) thread_.join();
branch — run
code only when
condition true.
68 ` std::cout << SHOW << RESET << Executable std::cout << SHOW << RESET << "\n";
"\n";` statement.
69 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
70 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
71 `` Blank line for Separator between code blocks.
readability.
72 `void ConsoleDisplay::clear_screen() {` Source code void ConsoleDisplay::clear_screen() {
line.
73 ` std::cout << CLEAR << HOME;` Executable std::cout << CLEAR << HOME;
statement.
74 `}` Brace or C/C++ syntax structure.
parenthesis

Page 150 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
75 `` Blank line for Separator between code blocks.
readability.
76 `void ConsoleDisplay::move_cursor(int row, Source code void ConsoleDisplay::move_cursor(int row,
int col) {` line. int col) {
77 ` std::cout << "\033[" << row << ";" << col Executable std::cout << "\033[" << row << ";" << col <<
<< "H";` statement. "H";
78 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
79 `` Blank line for Separator between code blocks.
readability.
80 `void Source code void
ConsoleDisplay::push_bps_sample(double line. ConsoleDisplay::push_bps_sample(double
bps) {` bps) {

Line Source Easy Technical Explanation


Explanation
81 ` std::lock_guard<std::mutex> Lock a mutex RAII mutex lock.
lock(mtx_);` so only one
thread uses
shared data at
a time.
82 ` bps_samples_.push_back(bps);` Executable bps_samples_.push_back(bps);
statement.
83 ` if (bps_samples_.size() > SPARK_LEN) Conditional if (bps_samples_.size() > SPARK_LEN)
bps_samples_.pop_front();` branch — run bps_samples_.pop_front();
code only when
condition true.
84 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
85 `` Blank line for Separator between code blocks.
readability.
86 `void Source code void
ConsoleDisplay::update_top_talker(uint32_t line. ConsoleDisplay::update_top_talker(uint32_t
src_ip, uint64_t bytes_added) {` src_ip, uint64_t bytes_added) {
87 ` std::lock_guard<std::mutex> Lock a mutex RAII mutex lock.
lock(mtx_);` so only one
thread uses
shared data at
a time.
88 ` top_talkers_[src_ip] += bytes_added;` Executable top_talkers_[src_ip] += bytes_added;
statement.
89 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Page 151 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
90 `` Blank line for Separator between code blocks.
readability.
91 `static std::string fmt_bytes_per_sec(double Source code static std::string fmt_bytes_per_sec(double
bps) {` line. bps) {
92 ` char buf[32];` Executable char buf[32];
statement.
93 ` if (bps >= 1e9) std::snprintf(buf, Conditional if (bps >= 1e9) std::snprintf(buf, sizeof(buf),
sizeof(buf), "%6.2f Gbps", bps/1e9);` branch — run "%6.2f Gbps", bps/1e9);
code only when
condition true.
94 ` else if (bps >= 1e6) std::snprintf(buf, Executable else if (bps >= 1e6) std::snprintf(buf,
sizeof(buf), "%6.2f Mbps", bps/1e6);` statement. sizeof(buf), "%6.2f Mbps", bps/1e6);
95 ` else if (bps >= 1e3) std::snprintf(buf, Executable else if (bps >= 1e3) std::snprintf(buf,
sizeof(buf), "%6.2f Kbps", bps/1e3);` statement. sizeof(buf), "%6.2f Kbps", bps/1e3);
96 ` else std::snprintf(buf, sizeof(buf), "%6.0f Executable else std::snprintf(buf, sizeof(buf), "%6.0f
bps ", bps);` statement. bps ", bps);
97 ` return buf;` Exit function return buf;
and give back
a value.
98 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
99 `` Blank line for Separator between code blocks.
readability.
100 `static std::string fmt_count(uint64_t n) {` Source code static std::string fmt_count(uint64_t n) {
line.
101 ` if (n >= 1'000'000'000ULL) {` Conditional if (n >= 1'000'000'000ULL) {
branch — run
code only when
condition true.
102 ` char b[32]; std::snprintf(b, sizeof(b), Executable char b[32]; std::snprintf(b, sizeof(b),
"%.2fB", n/1e9); return b;` statement. "%.2fB", n/1e9); return b;
103 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
104 ` if (n >= 1'000'000ULL) {` Conditional if (n >= 1'000'000ULL) {
branch — run
code only when
condition true.
105 ` char b[32]; std::snprintf(b, sizeof(b), Executable char b[32]; std::snprintf(b, sizeof(b),
"%.2fM", n/1e6); return b;` statement. "%.2fM", n/1e6); return b;
106 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
107 ` if (n >= 1000ULL) {` Conditional if (n >= 1000ULL) {
branch — run
code only when
condition true.

Page 152 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
108 ` char b[32]; std::snprintf(b, sizeof(b), Executable char b[32]; std::snprintf(b, sizeof(b),
"%.1fK", n/1e3); return b;` statement. "%.1fK", n/1e3); return b;
109 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
110 ` return std::to_string(n);` Exit function return std::to_string(n);
and give back
a value.
111 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
112 `` Blank line for Separator between code blocks.
readability.
113 `static std::string fmt_uptime(int64_t Source code static std::string fmt_uptime(int64_t
us_now, int64_t us_start) {` line. us_now, int64_t us_start) {
114 ` int64_t s = (us_now - us_start) / Executable int64_t s = (us_now - us_start) /
1000000LL;` statement. 1000000LL;
115 ` if (s < 0) s = 0;` Conditional if (s < 0) s = 0;
branch — run
code only when
condition true.
116 ` int h = static_cast<int>(s / 3600);` Executable int h = static_cast<int>(s / 3600);
statement.
117 ` int m = static_cast<int>((s % 3600) / Executable int m = static_cast<int>((s % 3600) / 60);
60);` statement.
118 ` int sec = static_cast<int>(s % 60);` Executable int sec = static_cast<int>(s % 60);
statement.
119 ` char b[32];` Executable char b[32];
statement.
120 ` std::snprintf(b, sizeof(b), Executable std::snprintf(b, sizeof(b),
"%02d:%02d:%02d", h, m, sec);` statement. "%02d:%02d:%02d", h, m, sec);
121 ` return b;` Exit function return b;
and give back
a value.
122 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
123 `` Blank line for Separator between code blocks.
readability.
124 `// Render a unicode block sparkline` Comment Render a unicode block sparkline
documenting
intent.
125 `static std::string render_sparkline(const Named static std::string render_sparkline(const
std::deque<double>& samples, size_t constant — std::deque<double>& samples, size_t wi
width) {` value should
not change.
126 ` static const char* blocks[] = {" ", Named static const char* blocks[] = {" ",
"▁","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█"};` constant — "▁","▂ ","▃ ","▄","▅ ","▆ ","▇ ","█"};

Page 153 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
value should
not change.
127 ` if ([Link]()) return Conditional if ([Link]()) return std::string(width,
std::string(width, ' ');` branch — run ' ');
code only when
condition true.
128 ` double mx = 0.0;` Executable double mx = 0.0;
statement.
129 ` for (double v : samples) if (v > mx) mx = Loop over for (double v : samples) if (v > mx) mx = v;
v;` items or until
condition
changes.
130 ` if (mx <= 0.0) return std::string(width, ' Conditional if (mx <= 0.0) return std::string(width, ' ');
');` branch — run
code only when
condition true.
131 ` std::string out;` Executable std::string out;
statement.
132 ` [Link](width * 3);` Executable [Link](width * 3);
statement.
133 ` size_t start = ([Link]() > width) ? Executable size_t start = ([Link]() > width) ?
[Link]() - width : 0;` statement. [Link]() - width : 0;
134 ` size_t pad = ([Link]() < width) ? Executable size_t pad = ([Link]() < width) ?
width - [Link]() : 0;` statement. width - [Link]() : 0;
135 ` for (size_t i = 0; i < pad; ++i) out += " ";` Loop over for (size_t i = 0; i < pad; ++i) out += " ";
items or until
condition
changes.
136 ` for (size_t i = start; i < [Link](); Loop over for (size_t i = start; i < [Link](); ++i) {
++i) {` items or until
condition
changes.
137 ` int idx = Executable int idx =
static_cast<int>(std::round(samples[i] / mx * statement. static_cast<int>(std::round(samples[i] / mx *
8.0));` 8.0));
138 ` if (idx < 0) idx = 0;` Conditional if (idx < 0) idx = 0;
branch — run
code only when
condition true.
139 ` if (idx > 8) idx = 8;` Conditional if (idx > 8) idx = 8;
branch — run
code only when
condition true.
140 ` out += blocks[idx];` Executable out += blocks[idx];
statement.
141 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
142 ` return out;` Exit function return out;
and give back
a value.

Page 154 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
143 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
144 `` Blank line for Separator between code blocks.
readability.
145 `// Static box-drawing helpers` Comment Static box-drawing helpers
documenting
intent.
146 `static const char* TL = "╔"; static const Named static const char* TL = "╔"; static const
char* TR = "╗";` constant — char* TR = "╗";
value should
not change.
147 `static const char* BL = "╚"; static const Named static const char* BL = "╚"; static const
char* BR = "╝";` constant — char* BR = "╝";
value should
not change.
148 `static const char* H = "═"; static const Named static const char* H = "═"; static const
char* V = "║";` constant — char* V = "║";
value should
not change.
149 `static const char* LJ = "╠"; static const Named static const char* LJ = "╠"; static const
char* RJ = "╣";` constant — char* RJ = "╣";
value should
not change.
150 `` Blank line for Separator between code blocks.
readability.
151 `static std::string repeat(const char* s, int n) Named static std::string repeat(const char* s, int n)
{` constant — {
value should
not change.
152 ` std::string out;` Executable std::string out;
statement.
153 ` for (int i = 0; i < n; ++i) out += s;` Loop over for (int i = 0; i < n; ++i) out += s;
items or until
condition
changes.
154 ` return out;` Exit function return out;
and give back
a value.
155 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
156 `` Blank line for Separator between code blocks.
readability.
157 `// Pad-or-truncate a visible-string to exactly Comment Pad-or-truncate a visible-string to exactly
`width` columns. Strips ANSI for the` documenting `width` columns. Strips ANSI for the
intent.
158 `// length count, but keeps codes in the Comment length count, but keeps codes in the output.
output. Simple - we don't insert escapes` documenting Simple - we don't insert escapes
intent.

Page 155 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
159 `// in the middle of words below.` Comment in the middle of words below.
documenting
intent.
160 `static std::string pad_visible(const Named static std::string pad_visible(const
std::string& s, int width) {` constant — std::string& s, int width) {
value should
not change.

Line Source Easy Technical Explanation


Explanation
161 ` // Count visible chars (skip ANSI \033[...m sequences).` Comment Count visible chars (skip ANSI
documenting \033[...m sequences).
intent.
162 ` int vis = 0;` Executable int vis = 0;
statement.
163 ` for (size_t i = 0; i < [Link](); ) {` Loop over for (size_t i = 0; i < [Link](); ) {
items or until
condition
changes.
164 ` if (s[i] == '\033') {` Conditional if (s[i] == '\033') {
branch — run
code only when
condition true.
165 ` while (i < [Link]() && s[i] != 'm') ++i;` Loop over while (i < [Link]() && s[i] != 'm')
items or until ++i;
condition
changes.
166 ` if (i < [Link]()) ++i;` Conditional if (i < [Link]()) ++i;
branch — run
code only when
condition true.
167 ` } else {` Source code } else {
line.
168 ` // crude: count multi-byte UTF-8 codepoints as 1` Comment crude: count multi-byte UTF-8
documenting codepoints as 1
intent.
169 ` unsigned char c = static_cast<unsigned Executable unsigned char c =
char>(s[i]);` statement. static_cast<unsigned
char>(s[i]);
170 ` if ((c & 0x80) == 0) { ++vis; ++i; }` Conditional if ((c & 0x80) == 0) { ++vis; ++i;
branch — run }
code only when
condition true.
171 ` else if ((c & 0xE0) == 0xC0) { ++vis; i += 2; }` Source code else if ((c & 0xE0) == 0xC0) {
line. ++vis; i += 2; }
172 ` else if ((c & 0xF0) == 0xE0) { ++vis; i += 3; }` Source code else if ((c & 0xF0) == 0xE0) {
line. ++vis; i += 3; }
173 ` else if ((c & 0xF8) == 0xF0) { ++vis; i += 4; }` Source code else if ((c & 0xF8) == 0xF0) {
line. ++vis; i += 4; }
174 ` else ++i;` Executable else ++i;
statement.

Page 156 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
175 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
176 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
177 ` if (vis >= width) return s; // assume caller built it to fit` Conditional if (vis >= width) return s; //
branch — run assume caller built it to fit
code only when
condition true.
178 ` return s + std::string(width - vis, ' ');` Exit function return s + std::string(width - vis,
and give back ' ');
a value.
179 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
180 `` Blank line for Separator between code
readability. blocks.
181 `void ConsoleDisplay::render_frame() {` Source code void
line. ConsoleDisplay::render_frame()
{
182 ` constexpr int W = 92; // dashboard width` Named constexpr int W = 92; //
constant — dashboard width
value should
not change.
183 ` std::ostringstream out;` Executable std::ostringstream out;
statement.
184 `` Blank line for Separator between code
readability. blocks.
185 ` // ---- Top banner ----` Comment ---- Top banner ----
documenting
intent.
186 ` auto banner_inner = [&]() -> std::string {` Source code auto banner_inner = [&]() ->
line. std::string {
187 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
188 ` s << BG_HEAD << FG_TITLE << BOLD` Source code s << BG_HEAD << FG_TITLE
line. << BOLD
189 ` << " ⛬NADS " << RESET << BG_HEAD << Source code << " ⛬NADS " << RESET <<
FG_LABEL` line. BG_HEAD << FG_LABEL
190 ` << "│ Network Anomaly Detection System v1.0 "` Source code << "│ Network Anomaly
line. Detection System v1.0 "
191 ` << FG_DIM << "│ iface=" << FG_VALUE << Source code << FG_DIM << "│ iface=" <<
cfg_.interface` line. FG_VALUE << cfg_.interface
192 ` << FG_DIM << " threshold=" << FG_VALUE` Source code << FG_DIM << " threshold="
line. << FG_VALUE
193 ` << std::fixed << std::setprecision(2) << Source code << std::fixed <<
cfg_.alert_threshold` line. std::setprecision(2) <<
cfg_.alert_threshold

Page 157 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
194 ` << " " << RESET;` Executable << " " << RESET;
statement.
195 ` return [Link]();` Exit function return [Link]();
and give back
a value.
196 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
197 `` Blank line for Separator between code
readability. blocks.
198 ` out << HOME;` Executable out << HOME;
statement.
199 ` out << FG_BORDER << TL << repeat(H, W - 2) << TR Executable out << FG_BORDER << TL <<
<< RESET << "\n";` statement. repeat(H, W - 2) << TR <<
RESET << "\n";
200 ` out << FG_BORDER << V << RESET << Source code out << FG_BORDER << V <<
pad_visible(banner_inner(), W - 2)` line. RESET <<
pad_visible(banner_inner(), W -
2)
201 ` << FG_BORDER << V << RESET << "\n";` Executable << FG_BORDER << V <<
statement. RESET << "\n";
202 ` out << FG_BORDER << LJ << repeat(H, W - 2) << RJ Executable out << FG_BORDER << LJ <<
<< RESET << "\n";` statement. repeat(H, W - 2) << RJ <<
RESET << "\n";
203 `` Blank line for Separator between code
readability. blocks.
204 ` // ---- Stats row 1 ----` Comment ---- Stats row 1 ----
documenting
intent.
205 ` int64_t now = wall_us();` Executable int64_t now = wall_us();
statement.
206 ` int64_t start = stats_.start_time_us.load();` Thread-safe std::memory_order relaxed
update or read typical.
of a statistic.
207 ` if (start == 0) { start = now; Thread-safe std::memory_order relaxed
stats_.start_time_us.store(start); }` update or read typical.
of a statistic.
208 `` Blank line for Separator between code
readability. blocks.
209 ` auto cell = [&](const std::string& label, const std::string& Named auto cell = [&](const std::string&
value, int w) {` constant — label, const std::string& value,
value should int w) {
not change.
210 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
211 ` s << " " << FG_LABEL << label << " " << FG_VALUE Executable s << " " << FG_LABEL << label
<< BOLD << value << RESET;` statement. << " " << FG_VALUE << BOLD
<< value << RESET;
212 ` return pad_visible([Link](), w);` Exit function return pad_visible([Link](), w);
and give back
a value.

Page 158 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
213 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
214 `` Blank line for Separator between code
readability. blocks.
215 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
216 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
217 ` s << cell("Packets/s", Thread-safe std::memory_order relaxed
fmt_count(static_cast<uint64_t>(stats_.current_pps.load())), update or read typical.
28);` of a statistic.
218 ` s << FG_BORDER << "│" << RESET;` Executable s << FG_BORDER << "│" <<
statement. RESET;
219 ` s << cell("Active Flows", Thread-safe std::memory_order relaxed
fmt_count(stats_.active_flows.load()), 28);` update or read typical.
of a statistic.
220 ` s << FG_BORDER << "│" << RESET;` Executable s << FG_BORDER << "│" <<
statement. RESET;
221 ` s << cell("Uptime", fmt_uptime(now, start), 26);` Executable s << cell("Uptime",
statement. fmt_uptime(now, start), 26);
222 ` out << FG_BORDER << V << RESET << Source code out << FG_BORDER << V <<
pad_visible([Link](), W - 2)` line. RESET << pad_visible([Link](),
W - 2)
223 ` << FG_BORDER << V << RESET << "\n";` Executable << FG_BORDER << V <<
statement. RESET << "\n";
224 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
225 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
226 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
227 ` s << cell("Throughput", Thread-safe std::memory_order relaxed
fmt_bytes_per_sec(stats_.current_bps.load()), 28);` update or read typical.
of a statistic.
228 ` s << FG_BORDER << "│" << RESET;` Executable s << FG_BORDER << "│" <<
statement. RESET;
229 ` s << cell("Total Hosts", Thread-safe std::memory_order relaxed
fmt_count(stats_.total_hosts.load()), 28);` update or read typical.
of a statistic.
230 ` s << FG_BORDER << "│" << RESET;` Executable s << FG_BORDER << "│" <<
statement. RESET;
231 ` s << cell("Queue Depth", Thread-safe std::memory_order relaxed
fmt_count(stats_.queue_size.load()), 26);` update or read typical.
of a statistic.

Page 159 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
232 ` out << FG_BORDER << V << RESET << Source code out << FG_BORDER << V <<
pad_visible([Link](), W - 2)` line. RESET << pad_visible([Link](),
W - 2)
233 ` << FG_BORDER << V << RESET << "\n";` Executable << FG_BORDER << V <<
statement. RESET << "\n";
234 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
235 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
236 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
237 ` s << cell("Captured", Thread-safe std::memory_order relaxed
fmt_count(stats_.total_packets_captured.load()), 28);` update or read typical.
of a statistic.
238 ` s << FG_BORDER << "│" << RESET;` Executable s << FG_BORDER << "│" <<
statement. RESET;
239 ` std::string drop = Thread-safe std::memory_order relaxed
fmt_count(stats_.total_packets_dropped.load());` update or read typical.
of a statistic.
240 ` if (stats_.total_packets_dropped.load() > 0) drop = Thread-safe std::memory_order relaxed
FG_ACCENT_BAD + drop + FG_VALUE;` update or read typical.
of a statistic.

Line Source Easy Technical Explanation


Explanation
241 ` s << cell("Dropped", drop, 28);` Executable s << cell("Dropped", drop, 28);
statement.
242 ` s << FG_BORDER << "│" << Executable s << FG_BORDER << "│" << RESET;
RESET;` statement.
243 ` std::ostringstream alerts_str;` Executable std::ostringstream alerts_str;
statement.
244 ` alerts_str << Thread-safe std::memory_order relaxed typical.
fmt_count(stats_.alerts_total.load())` update or read
of a statistic.
245 ` << FG_DIM << " ("` Source code << FG_DIM << " ("
line.
246 ` << FG_ACCENT_BAD << Thread-safe std::memory_order relaxed typical.
stats_.alerts_critical.load()` update or read
of a statistic.
247 ` << FG_DIM << "/" << Thread-safe std::memory_order relaxed typical.
FG_ACCENT_WARN << update or read
stats_.alerts_high.load()` of a statistic.
248 ` << FG_DIM << ")" << Executable << FG_DIM << ")" << FG_VALUE;
FG_VALUE;` statement.
249 ` s << cell("Alerts", alerts_str.str(), Executable s << cell("Alerts", alerts_str.str(), 26);
26);` statement.

Page 160 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
250 ` out << FG_BORDER << V << RESET Source code out << FG_BORDER << V << RESET <<
<< pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
251 ` << FG_BORDER << V << RESET Executable << FG_BORDER << V << RESET << "\n";
<< "\n";` statement.
252 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
253 `` Blank line for Separator between code blocks.
readability.
254 ` // ---- Sparkline panel ----` Comment ---- Sparkline panel ----
documenting
intent.
255 ` out << FG_BORDER << LJ << Executable out << FG_BORDER << LJ << repeat(H, W
repeat(H, W - 2) << RJ << RESET << "\n";` statement. - 2) << RJ << RESET << "\n";
256 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
257 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
258 ` s << " " << FG_LABEL << "Bandwidth Executable s << " " << FG_LABEL << "Bandwidth (last
(last " << SPARK_LEN << "s) " << FG_DIM statement. " << SPARK_LEN << "s) " << FG_DIM <<
<< "│ " << RESET;` "│ " << RESET;
259 ` std::deque<double> samples_copy;` Executable std::deque<double> samples_copy;
statement.
260 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
261 ` std::lock_guard<std::mutex> Lock a mutex RAII mutex lock.
lock(mtx_);` so only one
thread uses
shared data at
a time.
262 ` samples_copy = bps_samples_;` Executable samples_copy = bps_samples_;
statement.
263 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
264 ` s << FG_SPARK << Executable s << FG_SPARK <<
render_sparkline(samples_copy, statement. render_sparkline(samples_copy,
SPARK_LEN) << RESET;` SPARK_LEN) << RESET;
265 ` out << FG_BORDER << V << RESET Source code out << FG_BORDER << V << RESET <<
<< pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
266 ` << FG_BORDER << V << RESET Executable << FG_BORDER << V << RESET << "\n";
<< "\n";` statement.
267 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Page 161 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
268 `` Blank line for Separator between code blocks.
readability.
269 ` // ---- Top talkers + top alerts ----` Comment ---- Top talkers + top alerts ----
documenting
intent.
270 ` out << FG_BORDER << LJ << Executable out << FG_BORDER << LJ << repeat(H, W
repeat(H, W - 2) << RJ << RESET << "\n";` statement. - 2) << RJ << RESET << "\n";
271 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
272 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
273 ` s << " " << BOLD << FG_TITLE << Source code s << " " << BOLD << FG_TITLE << "TOP
"TOP TALKERS" << RESET` line. TALKERS" << RESET
274 ` << FG_DIM << " (by bytes)" << Executable << FG_DIM << " (by bytes)" << RESET;
RESET;` statement.
275 ` out << FG_BORDER << V << RESET Source code out << FG_BORDER << V << RESET <<
<< pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
276 ` << FG_BORDER << V << RESET Executable << FG_BORDER << V << RESET << "\n";
<< "\n";` statement.
277 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
278 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
279 ` std::vector<std::pair<uint32_t, Executable std::vector<std::pair<uint32_t, uint64_t>>
uint64_t>> top;` statement. top;
280 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
281 ` std::lock_guard<std::mutex> Lock a mutex RAII mutex lock.
lock(mtx_);` so only one
thread uses
shared data at
a time.
282 ` [Link](top_talkers_.begin(), Executable [Link](top_talkers_.begin(),
top_talkers_.end());` statement. top_talkers_.end());
283 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
284 ` std::sort([Link](), [Link](),` Source code std::sort([Link](), [Link](),
line.
285 ` [](const auto& a, const auto& b) Named [](const auto& a, const auto& b) { return
{ return [Link] > [Link]; });` constant — [Link] > [Link]; });
value should
not change.

Page 162 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
286 ` if ([Link]() > 5) [Link](5);` Conditional if ([Link]() > 5) [Link](5);
branch — run
code only when
condition true.
287 ` if ([Link]()) {` Conditional if ([Link]()) {
branch — run
code only when
condition true.
288 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
289 ` s << " " << FG_DIM << "(no traffic Executable s << " " << FG_DIM << "(no traffic yet)" <<
yet)" << RESET;` statement. RESET;
290 ` out << FG_BORDER << V << Source code out << FG_BORDER << V << RESET <<
RESET << pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
291 ` << FG_BORDER << V << Executable << FG_BORDER << V << RESET << "\n";
RESET << "\n";` statement.
292 ` } else {` Source code } else {
line.
293 ` int rank = 1;` Executable int rank = 1;
statement.
294 ` uint64_t mx = [Link]().second;` Executable uint64_t mx = [Link]().second;
statement.
295 ` for (const auto& [ip, by] : top) {` Loop over for (const auto& [ip, by] : top) {
items or until
condition
changes.
296 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
297 ` int barlen = static_cast<int>(40.0 Executable int barlen = static_cast<int>(40.0 * by /
* by / std::max<uint64_t>(mx, 1));` statement. std::max<uint64_t>(mx, 1));
298 ` if (barlen < 1) barlen = 1;` Conditional if (barlen < 1) barlen = 1;
branch — run
code only when
condition true.
299 ` std::string bar;` Executable std::string bar;
statement.
300 ` [Link](barlen * 3);` Executable [Link](barlen * 3);
statement.
301 ` for (int b = 0; b < barlen; ++b) Loop over for (int b = 0; b < barlen; ++b) bar +=
bar += "\xe2\x96\x88"; // U+2588 FULL items or until "\xe2\x96\x88"; // U+2588 FULL BLOCK
BLOCK` condition
changes.
302 ` s << " " << FG_DIM << rank << Source code s << " " << FG_DIM << rank << "." <<
"." << FG_VALUE` line. FG_VALUE
303 ` << std::left << std::setw(16) << Source code << std::left << std::setw(16) <<
ip_to_string(ip)` line. ip_to_string(ip)
304 ` << " " << FG_ACCENT_INFO Source code << " " << FG_ACCENT_INFO << bar <<
<< bar << RESET` line. RESET
305 ` << " " << FG_VALUE << Executable << " " << FG_VALUE <<
fmt_bytes_per_sec(static_cast<double>(by) statement. fmt_bytes_per_sec(static_cast<double>(by)
* 8.0) << RESET;` * 8.0) << RESET;

Page 163 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
306 ` out << FG_BORDER << V << Source code out << FG_BORDER << V << RESET <<
RESET << pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
307 ` << FG_BORDER << V << Executable << FG_BORDER << V << RESET << "\n";
RESET << "\n";` statement.
308 ` ++rank;` Executable ++rank;
statement.
309 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
310 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
311 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
312 `` Blank line for Separator between code blocks.
readability.
313 ` // ---- Recent alerts ----` Comment ---- Recent alerts ----
documenting
intent.
314 ` out << FG_BORDER << LJ << Executable out << FG_BORDER << LJ << repeat(H, W
repeat(H, W - 2) << RJ << RESET << "\n";` statement. - 2) << RJ << RESET << "\n";
315 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
316 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
317 ` s << " " << BOLD << FG_TITLE << Source code s << " " << BOLD << FG_TITLE <<
"RECENT ALERTS" << RESET` line. "RECENT ALERTS" << RESET
318 ` << FG_DIM << " (newest first)" << Executable << FG_DIM << " (newest first)" << RESET;
RESET;` statement.
319 ` out << FG_BORDER << V << RESET Source code out << FG_BORDER << V << RESET <<
<< pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
320 ` << FG_BORDER << V << RESET Executable << FG_BORDER << V << RESET << "\n";
<< "\n";` statement.

Lin Source Easy Technical Explanation


e Explanatio
n
321 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
322 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 164 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
323 ` auto recent = alerts_.recent(8);` Executable auto recent = alerts_.recent(8);
statement.
324 ` if ([Link]()) {` Conditional if ([Link]()) {
branch —
run code
only when
condition
true.
325 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
326 ` s << " " << FG_DIM << "No anomalies Executable s << " " << FG_DIM << "No anomalies detected
detected yet — system learning baselines..." << statement. yet — system learning baselines..." << RESET;
RESET;`
327 ` out << FG_BORDER << V << RESET << Source code out << FG_BORDER << V << RESET <<
pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
328 ` << FG_BORDER << V << RESET << Executable << FG_BORDER << V << RESET << "\n";
"\n";` statement.
329 ` } else {` Source code } else {
line.
330 ` for (auto it = [Link](); it != Loop over for (auto it = [Link](); it != [Link]();
[Link](); ++it) {` items or until ++it) {
condition
changes.
331 ` const auto& ev = *it;` Named const auto& ev = *it;
constant —
value should
not change.
332 ` std::time_t t = ev.timestamp_us / Executable std::time_t t = ev.timestamp_us / 1000000;
1000000;` statement.
333 ` std::tm tm{};` Executable std::tm tm{};
statement.
334 `#ifdef _WIN32` Comment ifdef _WIN32
documenting
intent.
335 ` localtime_s(&tm, &t);` Executable localtime_s(&tm, &t);
statement.
336 `#else` Comment else
documenting
intent.
337 ` localtime_r(&t, &tm);` Executable localtime_r(&t, &tm);
statement.
338 `#endif` Comment endif
documenting
intent.
339 ` char tbuf[16];` Executable char tbuf[16];
statement.
340 ` std::snprintf(tbuf, sizeof(tbuf), Source code std::snprintf(tbuf, sizeof(tbuf),
"%02d:%02d:%02d",` line. "%02d:%02d:%02d",
341 ` tm.tm_hour, tm.tm_min, Executable tm.tm_hour, tm.tm_min, tm.tm_sec);
tm.tm_sec);` statement.

Page 165 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
342 `` Blank line for Separator between code blocks.
readability.
343 ` std::string sev_color;` Executable std::string sev_color;
statement.
344 ` std::string sev_label;` Executable std::string sev_label;
statement.
345 ` switch ([Link]) {` Source code switch ([Link]) {
line.
346 ` case Severity::CRITICAL: sev_color Executable case Severity::CRITICAL: sev_color =
= FG_ACCENT_BAD; sev_label = "CRIT"; statement. FG_ACCENT_BAD; sev_label = "CRIT"; break;
break;`
347 ` case Severity::HIGH: sev_color = Executable case Severity::HIGH: sev_color =
FG_ACCENT_BAD; sev_label = "HIGH"; break;` statement. FG_ACCENT_BAD; sev_label = "HIGH"; break;
348 ` case Severity::MEDIUM: sev_color Executable case Severity::MEDIUM: sev_color =
= FG_ACCENT_WARN; sev_label = "MED "; statement. FG_ACCENT_WARN; sev_label = "MED ";
break;` break;
349 ` case Severity::LOW: sev_color = Executable case Severity::LOW: sev_color =
FG_ACCENT_INFO; sev_label = "LOW "; break;` statement. FG_ACCENT_INFO; sev_label = "LOW "; break;
350 ` default: sev_color = Executable default: sev_color = FG_DIM;
FG_DIM; sev_label = "INFO";` statement. sev_label = "INFO";
351 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
352 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
353 ` s << " " << FG_DIM << "[" << tbuf << "] Source code s << " " << FG_DIM << "[" << tbuf << "] " <<
" << RESET` line. RESET
354 ` << sev_color << "[" << sev_label << Source code << sev_color << "[" << sev_label << "]" <<
"]" << RESET << " "` line. RESET << " "
355 ` << FG_VALUE << std::left << Source code << FG_VALUE << std::left << std::setw(28)
std::setw(28)` line.
356 ` << (ev.attack_type.size() > 28 ? Source code << (ev.attack_type.size() > 28 ?
ev.attack_type.substr(0,28) : ev.attack_type)` line. ev.attack_type.substr(0,28) : ev.attack_type)
357 ` << " " << FG_DIM` Source code << " " << FG_DIM
line.
358 ` << ip_to_string(ev.src_ip) << "->" << Source code << ip_to_string(ev.src_ip) << "->" <<
ip_to_string(ev.dst_ip) << ":" << ev.dst_port` line. ip_to_string(ev.dst_ip) << ":" << ev.dst_port
359 ` << " " << FG_LABEL << "score="` Source code << " " << FG_LABEL << "score="
line.
360 ` << FG_VALUE << std::fixed << Source code << FG_VALUE << std::fixed <<
std::setprecision(2) << ev.final_score` line. std::setprecision(2) << ev.final_score
361 ` << RESET;` Executable << RESET;
statement.
362 ` out << FG_BORDER << V << RESET Source code out << FG_BORDER << V << RESET <<
<< pad_visible([Link](), W - 2)` line. pad_visible([Link](), W - 2)
363 ` << FG_BORDER << V << RESET Executable << FG_BORDER << V << RESET << "\n";
<< "\n";` statement.

Page 166 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
364 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
365 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
366 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
367 `` Blank line for Separator between code blocks.
readability.
368 ` // ---- Footer ----` Comment ---- Footer ----
documenting
intent.
369 ` out << FG_BORDER << BL << repeat(H, W - Executable out << FG_BORDER << BL << repeat(H, W - 2)
2) << BR << RESET << "\n";` statement. << BR << RESET << "\n";
370 ` out << FG_DIM << " [Ctrl+C] Quit │ log: " << Source code out << FG_DIM << " [Ctrl+C] Quit │ log: " <<
cfg_.output_log` line. cfg_.output_log
371 ` << " │ json: " << cfg_.json_output << Executable << " │ json: " << cfg_.json_output << RESET
RESET << "\n";` statement. << "\n";
372 `` Blank line for Separator between code blocks.
readability.
373 ` // Clear remainder of screen` Comment Clear remainder of screen
documenting
intent.
374 ` out << "\033[J";` Executable out << "\033[J";
statement.
375 `` Blank line for Separator between code blocks.
readability.
376 ` std::cout << [Link]();` Executable std::cout << [Link]();
statement.
377 ` std::[Link]();` Executable std::[Link]();
statement.
378 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
379 `` Blank line for Separator between code blocks.
readability.
380 `void ConsoleDisplay::run() {` Source code void ConsoleDisplay::run() {
line.
381 ` std::cout << HIDE;` Executable std::cout << HIDE;
statement.
382 ` clear_screen();` Executable clear_screen();
statement.
383 ` while (running_.load()) {` Thread-safe std::memory_order relaxed typical.
update or

Page 167 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
read of a
statistic.
384 ` render_frame();` Executable render_frame();
statement.
385 ` Executable std::this_thread::sleep_for(std::chrono::millisecon
std::this_thread::sleep_for(std::chrono::millisecon statement. ds(500));
ds(500));`
386 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
387 ` std::cout << SHOW;` Executable std::cout << SHOW;
statement.
388 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
389 `` Blank line for Separator between code blocks.
readability.
390 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/correlation_engine.cpp
Total lines: 74

Lin Source Easy Technical Explanation


e Explanation
1 `#include "correlation_engine.h"` Import #include "correlation_engine.h"
another
header file
into this
compilation
unit.
2 `#include <sstream>` Import #include <sstream>
another
header file
into this
compilation
unit.
3 `#include <cmath>` Import #include <cmath>
another
header file
into this
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.

Page 168 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
5 `namespace nads {` Start a named namespace nads {
code region
so names do
not clash
globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `CorrelationEngine::CorrelationEngine(int Source code CorrelationEngine::CorrelationEngine(int
window_sec)` line. window_sec)
8 ` : window_us_(window_sec * 1000000) {}` Source code : window_us_(window_sec * 1000000) {}
line.
9 `` Blank line for Separator between code blocks.
readability.
10 `void Named void
CorrelationEngine::prune(std::deque<DetectorHi constant — CorrelationEngine::prune(std::deque<DetectorHi
t>& q, int64_t now_us) const {` value should t>& q, int64_t now_us) const
not change.
11 ` while (![Link]() && now_us - Loop over while (![Link]() && now_us -
[Link]().timestamp_us > window_us_) {` items or until [Link]().timestamp_us > window_us_) {
condition
changes.
12 ` q.pop_front();` Executable q.pop_front();
statement.
13 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
14 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
15 `` Blank line for Separator between code blocks.
readability.
16 `void CorrelationEngine::record(uint32_t src_ip, Build or return score 0-1, flags, detail string.
const DetectorResult& r, int64_t now_us) {` a detector
score result.
17 ` if ([Link] < 0.5) return;` Conditional if ([Link] < 0.5) return;
branch — run
code only
when
condition true.
18 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
19 ` auto& q = by_src_[src_ip];` Executable auto& q = by_src_[src_ip];
statement.
20 ` prune(q, now_us);` Executable prune(q, now_us);
statement.
21 `` Blank line for Separator between code blocks.
readability.

Page 169 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
22 ` if (![Link]()) {` Conditional if (![Link]()) {
branch — run
code only
when
condition true.
23 ` const auto& last = [Link]();` Named const auto& last = [Link]();
constant —
value should
not change.
24 ` if ([Link] == r.detector_name &&` Conditional if ([Link] == r.detector_name &&
branch — run
code only
when
condition true.
25 ` now_us - last.timestamp_us < Source code now_us - last.timestamp_us < 1000000LL &&
1000000LL &&` line.
26 ` std::fabs([Link] - [Link]) < 0.05) {` Source code std::fabs([Link] - [Link]) < 0.05) {
line.
27 ` return;` Exit function return;
and give back
a value.
28 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
29 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
30 `` Blank line for Separator between code blocks.
readability.
31 ` DetectorHit h;` Executable DetectorHit h;
statement.
32 ` [Link] = r.detector_name;` Executable [Link] = r.detector_name;
statement.
33 ` [Link] = [Link];` Executable [Link] = [Link];
statement.
34 ` h.timestamp_us = now_us;` Executable h.timestamp_us = now_us;
statement.
35 ` h.src_ip = src_ip;` Executable h.src_ip = src_ip;
statement.
36 ` q.push_back(h);` Executable q.push_back(h);
statement.
37 `` Blank line for Separator between code blocks.
readability.
38 ` std::ostringstream cid;` Executable std::ostringstream cid;
statement.
39 ` cid << "corr-" << src_ip << "-" << now_us;` Executable cid << "corr-" << src_ip << "-" << now_us;
statement.
40 ` correlation_ids_[src_ip] = [Link]();` Executable correlation_ids_[src_ip] = [Link]();
statement.

Page 170 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
41 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
42 `` Blank line for Separator between code blocks.
readability.
43 `double Named double
CorrelationEngine::correlation_boost(uint32_t constant — CorrelationEngine::correlation_boost(uint32_t
src_ip, int64_t now_us) const {` value should src_ip, int64_t now_us) con
not change.
44 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
45 ` auto it = by_src_.find(src_ip);` Executable auto it = by_src_.find(src_ip);
statement.
46 ` if (it == by_src_.end()) return 0.0;` Conditional if (it == by_src_.end()) return 0.0;
branch — run
code only
when
condition true.
47 `` Blank line for Separator between code blocks.
readability.
48 ` auto q = it->second;` Executable auto q = it->second;
statement.
49 ` prune(q, now_us);` Executable prune(q, now_us);
statement.
50 `` Blank line for Separator between code blocks.
readability.
51 ` std::unordered_set<std::string> types;` Executable std::unordered_set<std::string> types;
statement.
52 ` int repeats = 0;` Executable int repeats = 0;
statement.
53 ` for (const auto& h : q) {` Loop over for (const auto& h : q) {
items or until
condition
changes.
54 ` if ([Link] < 0.5) continue;` Conditional if ([Link] < 0.5) continue;
branch — run
code only
when
condition true.
55 ` [Link]([Link]);` Executable [Link]([Link]);
statement.
56 ` ++repeats;` Executable ++repeats;
statement.
57 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 171 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
58 `` Blank line for Separator between code blocks.
readability.
59 ` double boost = 0.0;` Executable double boost = 0.0;
statement.
60 ` if ([Link]() >= 2) boost += 0.10;` Conditional if ([Link]() >= 2) boost += 0.10;
branch — run
code only
when
condition true.
61 ` if ([Link]() >= 3) boost += 0.08;` Conditional if ([Link]() >= 3) boost += 0.08;
branch — run
code only
when
condition true.
62 ` if ([Link]("temporal") && Conditional if ([Link]("temporal") &&
[Link]("protocol")) boost += 0.07;` branch — run [Link]("protocol")) boost += 0.07;
code only
when
condition true.
63 ` if (repeats >= 4) boost += 0.05;` Conditional if (repeats >= 4) boost += 0.05;
branch — run
code only
when
condition true.
64 ` return std::min(0.25, boost);` Exit function return std::min(0.25, boost);
and give back
a value.
65 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
66 `` Blank line for Separator between code blocks.
readability.
67 `std::string Named std::string
CorrelationEngine::last_correlation_id(uint32_t constant — CorrelationEngine::last_correlation_id(uint32_t
src_ip) const {` value should src_ip) const {
not change.
68 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
69 ` auto it = correlation_ids_.find(src_ip);` Executable auto it = correlation_ids_.find(src_ip);
statement.
70 ` if (it == correlation_ids_.end()) return {};` Conditional if (it == correlation_ids_.end()) return {};
branch — run
code only
when
condition true.
71 ` return it->second;` Exit function return it->second;
and give back
a value.
72 `}` Brace or C/C++ syntax structure.
parenthesis

Page 172 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
closing/openin
g a block.
73 `` Blank line for Separator between code blocks.
readability.
74 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/entropy_profiler.cpp
Total lines: 58

Lin Source Easy Technical Explanation


e Explanatio
n
1 `// entropy_profiler.cpp - Shannon entropy on Comment entropy_profiler.cpp - Shannon entropy on
sampled payload bytes` documenting sampled payload bytes
intent.
2 `#include "entropy_profiler.h"` Import #include "entropy_profiler.h"
another
header file
into this
compilation
unit.
3 `#include <cmath>` Import #include <cmath>
another
header file
into this
compilation
unit.
4 `#include <sstream>` Import #include <sstream>
another
header file
into this
compilation
unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a namespace nads {
named code
region so
names do
not clash
globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `double EntropyProfiler::shannon(const Named double EntropyProfiler::shannon(const
std::array<uint64_t, 256>& hist, uint64_t total) {` constant — std::array<uint64_t, 256>& hist, uint64_t
value should
not change.

Page 173 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
9 ` if (total == 0) return 0.0;` Conditional if (total == 0) return 0.0;
branch —
run code
only when
condition
true.
10 ` double H = 0.0;` Executable double H = 0.0;
statement.
11 ` for (auto v : hist) {` Loop over for (auto v : hist) {
items or until
condition
changes.
12 ` if (v == 0) continue;` Conditional if (v == 0) continue;
branch —
run code
only when
condition
true.
13 ` double p = static_cast<double>(v) / total;` Executable double p = static_cast<double>(v) / total;
statement.
14 ` H -= p * std::log2(p);` Executable H -= p * std::log2(p);
statement.
15 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
16 ` return H;` Exit function return H;
and give
back a
value.
17 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
18 `` Blank line for Separator between code blocks.
readability.
19 `DetectorResult EntropyProfiler::score(const Build or score 0-1, flags, detail string.
FlowRecord& flow) {` return a
detector
score result.
20 ` DetectorResult res;` Build or score 0-1, flags, detail string.
return a
detector
score result.
21 ` res.detector_name = "entropy";` Executable res.detector_name = "entropy";
statement.
22 `` Blank line for Separator between code blocks.
readability.
23 ` uint64_t total = 0;` Executable uint64_t total = 0;
statement.
24 ` for (auto v : flow.byte_histogram) total += v;` Loop over for (auto v : flow.byte_histogram) total += v;
items or until

Page 174 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
condition
changes.
25 ` if (total < 50) {` Conditional if (total < 50) {
branch —
run code
only when
condition
true.
26 ` [Link] = 0.0;` Executable [Link] = 0.0;
statement.
27 ` return res;` Exit function return res;
and give
back a
value.
28 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
29 `` Blank line for Separator between code blocks.
readability.
30 ` double H = [Link];` Executable double H = [Link];
statement.
31 ` double s = 0.0;` Executable double s = 0.0;
statement.
32 ` bool plaintext_port = ([Link].dst_port == 80 \ \ [Link].dst_port == 21 \
33 ` [Link].dst_port == 23 \ \ [Link].dst_port == 25 \
34 ` [Link].dst_port == 110 \ \ [Link].dst_port == 143);`
35 ` bool encrypted_port = ([Link].dst_port == \ [Link].dst_port == 22 \
443 \
36 ` [Link].dst_port == 993 \ \ [Link].dst_port == 995);`
37 `` Blank line for Separator between code blocks.
readability.
38 ` if (plaintext_port && H > 7.0) {` Conditional if (plaintext_port && H > 7.0) {
branch —
run code
only when
condition
true.
39 ` s = 0.7;` Executable s = 0.7;
statement.
40 ` Executable [Link].push_back("UNEXPECTED_HIGH_EN
[Link].push_back("UNEXPECTED_HIGH_EN statement. TROPY");
TROPY");`
41 ` } else if (encrypted_port && H < 4.0) {` Conditional } else if (encrypted_port && H < 4.0) {
branch —
run code
only when
condition
true.

Page 175 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
42 ` s = 0.5;` Executable s = 0.5;
statement.
43 ` Executable [Link].push_back("UNEXPECTED_LOW_EN
[Link].push_back("UNEXPECTED_LOW_ENT statement. TROPY");
ROPY");`
44 ` } else if (H > 7.8 && flow.byte_count > 10000) Conditional } else if (H > 7.8 && flow.byte_count > 10000) {
{` branch —
run code
only when
condition
true.
45 ` // Extremely high entropy on large transfer Comment Extremely high entropy on large transfer =
= compressed/encrypted` documenting compressed/encrypted
intent.
46 ` s = 0.3;` Executable s = 0.3;
statement.
47 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
48 `` Blank line for Separator between code blocks.
readability.
49 ` [Link] = s;` Executable [Link] = s;
statement.
50 ` res.is_anomaly = s > 0.6;` Executable res.is_anomaly = s > 0.6;
statement.
51 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
52 ` ss << "H=" << std::round(H * 100) / 100` Source code ss << "H=" << std::round(H * 100) / 100
line.
53 ` << " sampled=" << total;` Executable << " sampled=" << total;
statement.
54 ` [Link] = [Link]();` Executable [Link] = [Link]();
statement.
55 ` return res;` Exit function return res;
and give
back a
value.
56 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
57 `` Blank line for Separator between code blocks.
readability.
58 `} // namespace nads` End of nads } // namespace nads
namespace.

Page 176 of 629


NADS Complete Technical Reference

File: nads/src/flow_table.cpp
Total lines: 162

Lin Source Easy Technical Explanation


e Explanation
1 `// flow_table.cpp - flow aggregation & feature Comment flow_table.cpp - flow aggregation & feature
extraction` documenting extraction
intent.
2 `#include "flow_table.h"` Import #include "flow_table.h"
another
header file
into this
compilation
unit.
3 `#include <cmath>` Import #include <cmath>
another
header file
into this
compilation
unit.
4 `#include <algorithm>` Import #include <algorithm>
another
header file
into this
compilation
unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a named namespace nads {
code region
so names do
not clash
globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `FlowTable::FlowTable(int flow_timeout_sec)` Source code FlowTable::FlowTable(int flow_timeout_sec)
line.
9 ` : Source code :
timeout_us_(static_cast<int64_t>(flow_timeout_ line. timeout_us_(static_cast<int64_t>(flow_timeout_
sec) * 1000000LL) {` sec) * 1000000LL) {
10 ` flows_.reserve(16384);` Executable flows_.reserve(16384);
statement.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
12 `` Blank line for Separator between code blocks.
readability.
13 `FlowKey FlowTable::normalize_key(const Named FlowKey FlowTable::normalize_key(const
PacketInfo& pkt) {` constant — PacketInfo& pkt) {
value should
not change.
14 ` FlowKey k{};` Executable FlowKey k{};
statement.

Page 177 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
15 ` [Link] = [Link];` Executable [Link] = [Link];
statement.
16 ` // Smaller IP becomes "src" so A->B and B- Comment Smaller IP becomes "src" so A->B and B->A
>A collapse into one record.` documenting collapse into one record.
intent.
17 ` if (pkt.src_ip <= pkt.dst_ip) {` Conditional if (pkt.src_ip <= pkt.dst_ip) {
branch — run
code only
when
condition true.
18 ` k.src_ip = pkt.src_ip;` Executable k.src_ip = pkt.src_ip;
statement.
19 ` k.dst_ip = pkt.dst_ip;` Executable k.dst_ip = pkt.dst_ip;
statement.
20 ` k.src_port = pkt.src_port;` Executable k.src_port = pkt.src_port;
statement.
21 ` k.dst_port = pkt.dst_port;` Executable k.dst_port = pkt.dst_port;
statement.
22 ` } else {` Source code } else {
line.
23 ` k.src_ip = pkt.dst_ip;` Executable k.src_ip = pkt.dst_ip;
statement.
24 ` k.dst_ip = pkt.src_ip;` Executable k.dst_ip = pkt.src_ip;
statement.
25 ` k.src_port = pkt.dst_port;` Executable k.src_port = pkt.dst_port;
statement.
26 ` k.dst_port = pkt.src_port;` Executable k.dst_port = pkt.src_port;
statement.
27 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
28 ` return k;` Exit function return k;
and give back
a value.
29 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
30 `` Blank line for Separator between code blocks.
readability.
31 `FlowRecord& FlowTable::touch(const Named FlowRecord& FlowTable::touch(const
PacketInfo& pkt, bool* is_new_flow) {` constant — PacketInfo& pkt, bool* is_new_flow) {
value should
not change.
32 ` FlowKey key = normalize_key(pkt);` Executable FlowKey key = normalize_key(pkt);
statement.
33 `` Blank line for Separator between code blocks.
readability.
34 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one

Page 178 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
thread uses
shared data at
a time.
35 ` auto [it, inserted] = flows_.emplace(key, Insert into unordered_map insertion.
FlowRecord{});` map if key
missing.
36 ` FlowRecord& r = it->second;` Executable FlowRecord& r = it->second;
statement.
37 ` if (inserted) {` Conditional if (inserted) {
branch — run
code only
when
condition true.
38 ` [Link] = key;` Executable [Link] = key;
statement.
39 ` r.first_seen_us = pkt.timestamp_us;` Executable r.first_seen_us = pkt.timestamp_us;
statement.
40 ` r.byte_histogram.fill(0);` Executable r.byte_histogram.fill(0);
statement.
41 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
42 ` if (is_new_flow) *is_new_flow = inserted;` Conditional if (is_new_flow) *is_new_flow = inserted;
branch — run
code only
when
condition true.
43 `` Blank line for Separator between code blocks.
readability.
44 ` // Update counters` Comment Update counters
documenting
intent.
45 ` r.packet_count++;` Executable r.packet_count++;
statement.
46 ` r.byte_count += [Link];` Executable r.byte_count += [Link];
statement.
47 ` if ([Link] == PROTO_TCP) {` Conditional if ([Link] == PROTO_TCP) {
branch — run
code only
when
condition true.
48 ` if (pkt.tcp_flags & TCP_SYN) Conditional if (pkt.tcp_flags & TCP_SYN) r.syn_count++;
r.syn_count++;` branch — run
code only
when
condition true.
49 ` if (pkt.tcp_flags & TCP_ACK) Conditional if (pkt.tcp_flags & TCP_ACK) r.ack_count++;
r.ack_count++;` branch — run
code only
when
condition true.

Page 179 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
50 ` if (pkt.tcp_flags & TCP_FIN) Conditional if (pkt.tcp_flags & TCP_FIN) r.fin_count++;
r.fin_count++;` branch — run
code only
when
condition true.
51 ` if (pkt.tcp_flags & TCP_RST) Conditional if (pkt.tcp_flags & TCP_RST) r.rst_count++;
r.rst_count++;` branch — run
code only
when
condition true.
52 ` if (pkt.tcp_flags & TCP_PSH) Conditional if (pkt.tcp_flags & TCP_PSH) r.psh_count++;
r.psh_count++;` branch — run
code only
when
condition true.
53 ` if (pkt.tcp_flags & TCP_URG) Conditional if (pkt.tcp_flags & TCP_URG) r.urg_count++;
r.urg_count++;` branch — run
code only
when
condition true.
54 `` Blank line for Separator between code blocks.
readability.
55 ` // NULL scan: no flags` Comment NULL scan: no flags
documenting
intent.
56 ` if (pkt.tcp_flags == 0) {` Conditional if (pkt.tcp_flags == 0) {
branch — run
code only
when
condition true.
57 ` r.null_flag_count++;` Executable r.null_flag_count++;
statement.
58 ` r.has_null_flags = true;` Executable r.has_null_flags = true;
statement.
59 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
60 ` // XMAS scan: FIN+PSH+URG` Comment XMAS scan: FIN+PSH+URG
documenting
intent.
61 ` if ((pkt.tcp_flags & (TCP_FIN \ TCP_PSH \ TCP_URG)) ==`
62 ` (TCP_FIN \ TCP_PSH \ TCP_URG)) {`
63 ` r.xmas_flag_count++;` Executable r.xmas_flag_count++;
statement.
64 ` r.has_xmas_flags = true;` Executable r.has_xmas_flags = true;
statement.
65 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 180 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
66 ` // Full handshake heuristic` Comment Full handshake heuristic
documenting
intent.
67 ` if (r.syn_count > 0 && r.ack_count > 0 && Conditional if (r.syn_count > 0 && r.ack_count > 0 &&
r.packet_count > 2) {` branch — run r.packet_count > 2) {
code only
when
condition true.
68 ` r.has_full_handshake = true;` Executable r.has_full_handshake = true;
statement.
69 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
70 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
71 `` Blank line for Separator between code blocks.
readability.
72 ` // Timing` Comment Timing
documenting
intent.
73 ` if (r.last_seen_us > 0) {` Conditional if (r.last_seen_us > 0) {
branch — run
code only
when
condition true.
74 ` r.touch_iat(pkt.timestamp_us - Executable r.touch_iat(pkt.timestamp_us - r.last_seen_us);
r.last_seen_us);` statement.
75 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
76 ` r.last_seen_us = pkt.timestamp_us;` Executable r.last_seen_us = pkt.timestamp_us;
statement.
77 ` Executable r.touch_size(static_cast<uint16_t>([Link]));
r.touch_size(static_cast<uint16_t>([Link]));` statement.
78 `` Blank line for Separator between code blocks.
readability.
79 ` // Payload byte histogram (first 100 bytes Comment Payload byte histogram (first 100 bytes only to
only to bound CPU)` documenting bound CPU)
intent.
80 ` if (pkt.payload_size > 0 &&` Conditional if (pkt.payload_size > 0 &&
branch — run
code only
when
condition true.

Page 181 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
81 ` pkt.payload_offset + pkt.payload_size Byte index Replaces old payload_ptr.
<= pkt.raw_bytes.size()) {` where payload
starts inside
raw_bytes
(safe after
move).
82 ` const uint8_t* ptr = Byte index Replaces old payload_ptr.
pkt.raw_bytes.data() + pkt.payload_offset;` where payload
starts inside
raw_bytes
(safe after
move).
83 ` size_t n = Executable size_t n =
std::min<size_t>(pkt.payload_size, 100);` statement. std::min<size_t>(pkt.payload_size, 100);
84 ` for (size_t i = 0; i < n; ++i) {` Loop over for (size_t i = 0; i < n; ++i) {
items or until
condition
changes.
85 ` r.byte_histogram[ptr[i]]++;` Executable r.byte_histogram[ptr[i]]++;
statement.
86 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
87 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
88 `` Blank line for Separator between code blocks.
readability.
89 ` return r;` Exit function return r;
and give back
a value.
90 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
91 `` Blank line for Separator between code blocks.
readability.
92 `std::vector<FlowRecord> Source code std::vector<FlowRecord>
FlowTable::sweep_expired(int64_t now_us) line. FlowTable::sweep_expired(int64_t now_us)
{` {
93 ` std::vector<FlowRecord> expired;` Executable std::vector<FlowRecord> expired;
statement.
94 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
95 ` for (auto it = flows_.begin(); it != Loop over for (auto it = flows_.begin(); it !=
flows_.end(); ) {` items or until flows_.end(); ) {
condition
changes.

Page 182 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
96 ` if (now_us - it->second.last_seen_us Conditional if (now_us - it->second.last_seen_us >
> timeout_us_) {` branch — run timeout_us_) {
code only when
condition true.
97 ` it->second.is_complete = true;` Executable it->second.is_complete = true;
statement.
98 ` FlowTable::compute_features(it- Executable FlowTable::compute_features(it->second);
>second);` statement.
99 ` expired.push_back(it->second);` Executable expired.push_back(it->second);
statement.
100 ` it = flows_.erase(it);` Executable it = flows_.erase(it);
statement.
101 ` } else {` Source code } else {
line.
102 ` ++it;` Executable ++it;
statement.
103 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
104 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
105 ` return expired;` Exit function return expired;
and give back
a value.
106 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
107 `` Blank line for Separator between code blocks.
readability.
108 `void Source code void
FlowTable::compute_features(FlowRecord& line. FlowTable::compute_features(FlowRecord&
r) {` r) {
109 ` double dur_s = (r.last_seen_us - Executable double dur_s = (r.last_seen_us -
r.first_seen_us) / 1e6;` statement. r.first_seen_us) / 1e6;
110 ` if (dur_s <= 0.0) dur_s = 1e-3;` Conditional if (dur_s <= 0.0) dur_s = 1e-3;
branch — run
code only when
condition true.
111 ` [Link] = r.packet_count / dur_s;` Executable [Link] = r.packet_count / dur_s;
statement.
112 ` [Link] = (r.byte_count * 8.0) / dur_s;` Executable [Link] = (r.byte_count * 8.0) / dur_s;
statement.
113 `` Blank line for Separator between code blocks.
readability.
114 ` if (r.ack_count == 0) {` Conditional if (r.ack_count == 0) {
branch — run
code only when
condition true.

Page 183 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
115 ` r.syn_ack_ratio = (r.syn_count > 0) ? Executable r.syn_ack_ratio = (r.syn_count > 0) ? 999.0
999.0 : 0.0;` statement. : 0.0;
116 ` } else {` Source code } else {
line.
117 ` r.syn_ack_ratio = Executable r.syn_ack_ratio =
static_cast<double>(r.syn_count) / statement. static_cast<double>(r.syn_count) /
r.ack_count;` r.ack_count;
118 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
119 `` Blank line for Separator between code blocks.
readability.
120 ` // Mean / stddev of packet sizes` Comment Mean / stddev of packet sizes
documenting
intent.
121 ` if (!r.size_buf.empty()) {` Conditional if (!r.size_buf.empty()) {
branch — run
code only when
condition true.
122 ` double sum = 0.0;` Executable double sum = 0.0;
statement.
123 ` for (auto s : r.size_buf) sum += s;` Loop over for (auto s : r.size_buf) sum += s;
items or until
condition
changes.
124 ` r.mean_pkt_size = sum / Executable r.mean_pkt_size = sum / r.size_buf.size();
r.size_buf.size();` statement.
125 ` double sq = 0.0;` Executable double sq = 0.0;
statement.
126 ` for (auto s : r.size_buf) {` Loop over for (auto s : r.size_buf) {
items or until
condition
changes.
127 ` double d = s - r.mean_pkt_size;` Executable double d = s - r.mean_pkt_size;
statement.
128 ` sq += d * d;` Executable sq += d * d;
statement.
129 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
130 ` r.stddev_pkt_size = (r.size_buf.size() Source code r.stddev_pkt_size = (r.size_buf.size() > 1)
> 1)` line.
131 ` ? std::sqrt(sq / (r.size_buf.size() - Executable ? std::sqrt(sq / (r.size_buf.size() - 1)) : 0.0;
1)) : 0.0;` statement.
132 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
133 `` Blank line for Separator between code blocks.
readability.

Page 184 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
134 ` // Mean / stddev of inter-arrival times` Comment Mean / stddev of inter-arrival times
documenting
intent.
135 ` if (!r.iat_buffer.empty()) {` Conditional if (!r.iat_buffer.empty()) {
branch — run
code only when
condition true.
136 ` double sum = 0.0;` Executable double sum = 0.0;
statement.
137 ` for (auto v : r.iat_buffer) sum += v;` Loop over for (auto v : r.iat_buffer) sum += v;
items or until
condition
changes.
138 ` r.mean_iat = sum / r.iat_buffer.size();` Executable r.mean_iat = sum / r.iat_buffer.size();
statement.
139 ` double sq = 0.0;` Executable double sq = 0.0;
statement.
140 ` for (auto v : r.iat_buffer) {` Loop over for (auto v : r.iat_buffer) {
items or until
condition
changes.
141 ` double d = v - r.mean_iat;` Executable double d = v - r.mean_iat;
statement.
142 ` sq += d * d;` Executable sq += d * d;
statement.
143 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
144 ` r.stddev_iat = (r.iat_buffer.size() > 1)` Source code r.stddev_iat = (r.iat_buffer.size() > 1)
line.
145 ` ? std::sqrt(sq / (r.iat_buffer.size() - Executable ? std::sqrt(sq / (r.iat_buffer.size() - 1)) : 0.0;
1)) : 0.0;` statement.
146 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
147 `` Blank line for Separator between code blocks.
readability.
148 ` // Shannon entropy` Comment Shannon entropy
documenting
intent.
149 ` uint64_t total = 0;` Executable uint64_t total = 0;
statement.
150 ` for (auto v : r.byte_histogram) total += Loop over for (auto v : r.byte_histogram) total += v;
v;` items or until
condition
changes.
151 ` if (total > 0) {` Conditional if (total > 0) {
branch — run
code only when
condition true.

Page 185 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
152 ` double H = 0.0;` Executable double H = 0.0;
statement.
153 ` for (auto v : r.byte_histogram) {` Loop over for (auto v : r.byte_histogram) {
items or until
condition
changes.
154 ` if (v == 0) continue;` Conditional if (v == 0) continue;
branch — run
code only when
condition true.
155 ` double p = static_cast<double>(v) / Executable double p = static_cast<double>(v) / total;
total;` statement.
156 ` H -= p * std::log2(p);` Executable H -= p * std::log2(p);
statement.
157 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
158 ` [Link] = H;` Executable [Link] = H;
statement.
159 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
160 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Line Source Easy Explanation Technical Explanation


161 `` Blank line for readability. Separator between code blocks.
162 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/src/fusion_engine.cpp
Total lines: 63

Line Source Easy Technical Explanation


Explanation
1 `#include "fusion_engine.h"` Import another #include "fusion_engine.h"
header file into this
compilation unit.
2 `#include "logistic_fusion.h"` Import another #include "logistic_fusion.h"
header file into this
compilation unit.
3 `#include <algorithm>` Import another #include <algorithm>
header file into this
compilation unit.

Page 186 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `FusionEngine::FusionEngine(const Config& Named constant — FusionEngine::FusionEngine(const
cfg) : cfg_(cfg) {` value should not Config& cfg) : cfg_(cfg) {
change.
8 ` if (cfg_.use_logistic_fusion \ \ cfg_.fusion_type == "logistic") {`
9 ` logistic_ = Own a module Heap object with unique ownership.
std::make_unique<LogisticFusion>(cfg_);` object; auto-
deleted when
done.
10 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
12 `` Blank line for Separator between code blocks.
readability.
13 `double FusionEngine::weight_for(const Named constant — double
std::string& name) const {` value should not FusionEngine::weight_for(const
change. std::string& name) const {
14 ` if (name == "statistical") return Conditional branch if (name == "statistical") return
cfg_.w_statistical;` — run code only cfg_.w_statistical;
when condition
true.
15 ` if (name == "volume") return Conditional branch if (name == "volume") return
cfg_.w_volume;` — run code only cfg_.w_volume;
when condition
true.
16 ` if (name == "protocol") return Conditional branch if (name == "protocol") return
cfg_.w_protocol;` — run code only cfg_.w_protocol;
when condition
true.
17 ` if (name == "baseline") return Conditional branch if (name == "baseline") return
cfg_.w_baseline;` — run code only cfg_.w_baseline;
when condition
true.
18 ` if (name == "graph") return Conditional branch if (name == "graph") return
cfg_.w_graph;` — run code only cfg_.w_graph;
when condition
true.
19 ` if (name == "temporal") return Conditional branch if (name == "temporal") return
cfg_.w_temporal;` — run code only cfg_.w_temporal;
when condition
true.

Page 187 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
20 ` if (name == "entropy") return Conditional branch if (name == "entropy") return
cfg_.w_entropy;` — run code only cfg_.w_entropy;
when condition
true.
21 ` if ([Link]("advanced_", 0) == 0) Conditional branch if ([Link]("advanced_", 0) == 0)
return 0.05;` — run code only return 0.05;
when condition
true.
22 ` return 0.0;` Exit function and return 0.0;
give back a value.
23 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
24 `` Blank line for Separator between code blocks.
readability.
25 `FusionResult FusionEngine::fuse(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results) {` detector score
result.
26 ` if (logistic_) {` Conditional branch if (logistic_) {
— run code only
when condition
true.
27 ` FusionResult lr = logistic_- Combine multiple Fusion / correlation logic.
>fuse(results);` detector scores.
28 ` lr.final_score = std::min(1.0, Executable lr.final_score = std::min(1.0,
lr.final_score);` statement. lr.final_score);
29 ` lr.is_anomaly = lr.final_score >= Executable lr.is_anomaly = lr.final_score >=
cfg_.alert_threshold;` statement. cfg_.alert_threshold;
30 ` return lr;` Exit function and return lr;
give back a value.
31 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
32 `` Blank line for Separator between code blocks.
readability.
33 ` FusionResult r;` Combine multiple Fusion / correlation logic.
detector scores.
34 ` r.detector_results = results;` Executable r.detector_results = results;
statement.
35 ` double total_w = 0.0;` Executable double total_w = 0.0;
statement.
36 ` double sum = 0.0;` Executable double sum = 0.0;
statement.
37 ` double max_single = 0.0;` Executable double max_single = 0.0;
statement.
38 `` Blank line for Separator between code blocks.
readability.

Page 188 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
39 ` for (const auto& d : results) {` Loop over items or for (const auto& d : results) {
until condition
changes.
40 ` double w = Executable double w =
weight_for(d.detector_name);` statement. weight_for(d.detector_name);
41 ` total_w += w;` Executable total_w += w;
statement.
42 ` sum += w * [Link];` Executable sum += w * [Link];
statement.
43 ` if ([Link] > max_single) max_single = Conditional branch if ([Link] > max_single) max_single
[Link];` — run code only = [Link];
when condition
true.
44 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
45 ` if (total_w > 0.0) r.final_score = sum / Conditional branch if (total_w > 0.0) r.final_score = sum /
total_w;` — run code only total_w;
when condition
true.
46 ` if (r.final_score > 1.0) r.final_score = 1.0;` Conditional branch if (r.final_score > 1.0) r.final_score =
— run code only 1.0;
when condition
true.
47 `` Blank line for Separator between code blocks.
readability.
48 ` if (cfg_.use_legacy_fusion_boost) {` Combine multiple Fusion / correlation logic.
detector scores.
49 ` int firing = 0;` Executable int firing = 0;
statement.
50 ` for (const auto& d : results) if ([Link] Loop over items or for (const auto& d : results) if
> 0.5) firing++;` until condition ([Link] > 0.5) firing++;
changes.
51 ` if (firing >= 2) r.final_score = Conditional branch if (firing >= 2) r.final_score =
std::min(1.0, r.final_score + 0.08);` — run code only std::min(1.0, r.final_score + 0.08);
when condition
true.
52 ` if (firing >= 3) r.final_score = Conditional branch if (firing >= 3) r.final_score =
std::min(1.0, r.final_score + 0.10);` — run code only std::min(1.0, r.final_score + 0.10);
when condition
true.
53 ` if (firing >= 4) r.final_score = Conditional branch if (firing >= 4) r.final_score =
std::min(1.0, r.final_score + 0.05);` — run code only std::min(1.0, r.final_score + 0.05);
when condition
true.
54 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
55 `` Blank line for Separator between code blocks.
readability.

Page 189 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
56 ` if (max_single >= 0.85)` Conditional branch if (max_single >= 0.85)
— run code only
when condition
true.
57 ` r.final_score = std::max(r.final_score, Executable r.final_score = std::max(r.final_score,
max_single * 0.90);` statement. max_single * 0.90);
58 `` Blank line for Separator between code blocks.
readability.
59 ` r.is_anomaly = r.final_score >= Executable r.is_anomaly = r.final_score >=
cfg_.alert_threshold;` statement. cfg_.alert_threshold;
60 ` return r;` Exit function and return r;
give back a value.
61 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
62 `` Blank line for Separator between code blocks.
readability.
63 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/graph_detector.cpp
Total lines: 55

Lin Source Easy Technical Explanation


e Explanation
1 `// graph_detector.cpp - tracks per-host degree Comment graph_detector.cpp - tracks per-host degree
and detects spikes` documenting and detects spikes
intent.
2 `#include "graph_detector.h"` Import another #include "graph_detector.h"
header file
into this
compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file
into this
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region
so names do
not clash
globally.
6 `` Blank line for Separator between code blocks.
readability.

Page 190 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
7 `DetectorResult Build or return score 0-1, flags, detail string.
GraphDetector::on_new_flow(uint32_t src_ip, a detector
uint32_t dst_ip, int64_t ts_us) {` score result.
8 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
9 ` res.detector_name = "graph";` Executable res.detector_name = "graph";
statement.
10 `` Blank line for Separator between code blocks.
readability.
11 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
12 ` auto& node = nodes_[src_ip];` Executable auto& node = nodes_[src_ip];
statement.
13 ` [Link] = src_ip;` Executable [Link] = src_ip;
statement.
14 `` Blank line for Separator between code blocks.
readability.
15 ` bool is_new_edge = Executable bool is_new_edge =
[Link](dst_ip).second;` statement. [Link](dst_ip).second;
16 ` if (!is_new_edge) {` Conditional if (!is_new_edge) {
branch — run
code only
when
condition true.
17 ` // Existing edge: no spike signal` Comment Existing edge: no spike signal
documenting
intent.
18 ` [Link] = 0.0;` Executable [Link] = 0.0;
statement.
19 ` return res;` Exit function return res;
and give back
a value.
20 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
21 `` Blank line for Separator between code blocks.
readability.
22 ` Executable node.recent_new_edges_us.push_back(ts_us);
node.recent_new_edges_us.push_back(ts_us);` statement.
23 ` // Drop edges older than window` Comment Drop edges older than window
documenting
intent.
24 ` while (!node.recent_new_edges_us.empty() Loop over while (!node.recent_new_edges_us.empty() &&
&&` items or until
condition
changes.

Page 191 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
25 ` ts_us - Source code ts_us - node.recent_new_edges_us.front() >
node.recent_new_edges_us.front() > line. WINDOW_US) {
WINDOW_US) {`
26 ` node.recent_new_edges_us.pop_front();` Executable node.recent_new_edges_us.pop_front();
statement.
27 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
28 `` Blank line for Separator between code blocks.
readability.
29 ` double new_edge_per_min = Source code double new_edge_per_min =
node.recent_new_edges_us.size() / 10.0; // per line. node.recent_new_edges_us.size() / 10.0; // per
minute` minute
30 ` double score = 0.0;` Executable double score = 0.0;
statement.
31 `` Blank line for Separator between code blocks.
readability.
32 ` // Hard thresholds (cold start)` Comment Hard thresholds (cold start)
documenting
intent.
33 ` if (new_edge_per_min > 50.0) score = Conditional if (new_edge_per_min > 50.0) score =
std::max(score, 0.95);` branch — run std::max(score, 0.95);
code only
when
condition true.
34 ` else if (new_edge_per_min > 20.0) score = Executable else if (new_edge_per_min > 20.0) score =
std::max(score, 0.8);` statement. std::max(score, 0.8);
35 ` else if (new_edge_per_min > 10.0) score = Executable else if (new_edge_per_min > 10.0) score =
std::max(score, 0.5);` statement. std::max(score, 0.5);
36 `` Blank line for Separator between code blocks.
readability.
37 ` if (node.degree_velocity.ready(10)) {` Conditional if (node.degree_velocity.ready(10)) {
branch — run
code only
when
condition true.
38 ` double z = Compare Z-score or normalized score.
node.degree_velocity.zscore(new_edge_per_mi value to
n);` learned
baseline
statistically.
39 ` score = std::max(score, normalize_z(z, Compare Z-score or normalized score.
3.0));` value to
learned
baseline
statistically.
40 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 192 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
41 ` Executable node.degree_velocity.update(new_edge_per_m
node.degree_velocity.update(new_edge_per_mi statement. in);
n);`
42 `` Blank line for Separator between code blocks.
readability.
43 ` [Link] = score;` Executable [Link] = score;
statement.
44 ` res.is_anomaly = score > 0.6;` Executable res.is_anomaly = score > 0.6;
statement.
45 ` if (score > 0.6) Conditional if (score > 0.6)
[Link].push_back("DEGREE_SPIKE");` branch — run [Link].push_back("DEGREE_SPIKE");
code only
when
condition true.
46 `` Blank line for Separator between code blocks.
readability.
47 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
48 ` ss << "host=" << ip_to_string(src_ip)` Source code ss << "host=" << ip_to_string(src_ip)
line.
49 ` << " degree=" << [Link]()` Source code << " degree=" << [Link]()
line.
50 ` << " new_edges/min=" << Executable << " new_edges/min=" <<
static_cast<int>(new_edge_per_min);` statement. static_cast<int>(new_edge_per_min);
51 ` [Link] = [Link]();` Executable [Link] = [Link]();
statement.
52 ` return res;` Exit function return res;
and give back
a value.
53 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
54 `` Blank line for Separator between code blocks.
readability.
55 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/http_server.cpp
Total lines: 1004

Page 193 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
1 `// http_server.cpp — REST API + proper RFC Comment http_server.cpp — REST API + proper RFC 6455
6455 WebSocket server for NADS` documentin WebSocket server for NADS
g intent.
2 `#include "http_server.h"` Import #include "http_server.h"
another
header file
into this
compilation
unit.
3 `#include "orchestrator.h"` Import #include "orchestrator.h"
another
header file
into this
compilation
unit.
4 `#include "flow_table.h"` Import #include "flow_table.h"
another
header file
into this
compilation
unit.
5 `#include "metrics_registry.h"` Import #include "metrics_registry.h"
another
header file
into this
compilation
unit.
6 `` Blank line Separator between code blocks.
for
readability.
7 `#include <iostream>` Import #include <iostream>
another
header file
into this
compilation
unit.
8 `#include <sstream>` Import #include <sstream>
another
header file
into this
compilation
unit.
9 `#include <fstream>` Import #include <fstream>
another
header file
into this
compilation
unit.
1 `#include <iomanip>` Import #include <iomanip>
0 another
header file
into this
compilation
unit.

Page 194 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
1 `#include <ctime>` Import #include <ctime>
1 another
header file
into this
compilation
unit.
1 `#include <cstring>` Import #include <cstring>
2 another
header file
into this
compilation
unit.
1 `#include <algorithm>` Import #include <algorithm>
3 another
header file
into this
compilation
unit.
1 `#include <cassert>` Import #include <cassert>
4 another
header file
into this
compilation
unit.
1 `#include <chrono>` Import #include <chrono>
5 another
header file
into this
compilation
unit.
1 `` Blank line Separator between code blocks.
6 for
readability.
1 `#include <arpa/inet.h>` Import #include <arpa/inet.h>
7 another
header file
into this
compilation
unit.
1 `#include <sys/socket.h>` Import #include <sys/socket.h>
8 another
header file
into this
compilation
unit.
1 `#include <sys/select.h>` Import #include <sys/select.h>
9 another
header file
into this
compilation
unit.
2 `#include <sys/stat.h>` Import #include <sys/stat.h>
0 another
header file
into this

Page 195 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
compilation
unit.
2 `#include <unistd.h>` Import #include <unistd.h>
1 another
header file
into this
compilation
unit.
2 `#include <fcntl.h>` Import #include <fcntl.h>
2 another
header file
into this
compilation
unit.
2 `` Blank line Separator between code blocks.
3 for
readability.
2 `namespace nads {` Start a namespace nads {
4 named
code region
so names
do not clash
globally.
2 `` Blank line Separator between code blocks.
5 for
readability.
2 `// Comment ═══════════════════════════════
6 ═══════════════════════════════ documentin ═══════════════════════════════
═══════════════════════════════ g intent. ══════════════
══════════════`
2 `// SHA-1 (FIPS 180-4) — needed for WebSocket Comment SHA-1 (FIPS 180-4) — needed for WebSocket
7 handshake` documentin handshake
g intent.
2 `// Comment ═══════════════════════════════
8 ═══════════════════════════════ documentin ═══════════════════════════════
═══════════════════════════════ g intent. ══════════════
══════════════`
2 `` Blank line Separator between code blocks.
9 for
readability.
3 `#define SHA1_ROTL(v,n) (((v)<<(n))\ ((v)>>(32- Comment documenting intent.
0 (n))))`
3 `` Blank line Separator between code blocks.
1 for
readability.
3 `void HttpServer::sha1(const uint8_t* data, size_t Named void HttpServer::sha1(const uint8_t* data, size_t
2 len, uint8_t out[20]) {` constant — len, uint8_t out[20]) {
value
should not
change.
3 ` uint32_t H[5] = {` Source uint32_t H[5] = {
3 code line.

Page 196 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
3 ` 0x67452301u, 0xEFCDAB89u, Source 0x67452301u, 0xEFCDAB89u, 0x98BADCFEu,
4 0x98BADCFEu, 0x10325476u, 0xC3D2E1F0u` code line. 0x10325476u, 0xC3D2E1F0u
3 ` };` Brace or C/C++ syntax structure.
5 parenthesis
closing/ope
ning a
block.
3 `` Blank line Separator between code blocks.
6 for
readability.
3 ` // Pre-processing: append bit '1', then zeros, Comment Pre-processing: append bit '1', then zeros, then
7 then 64-bit length` documentin 64-bit length
g intent.
3 ` size_t total = len;` Executable size_t total = len;
8 statement.
3 ` std::vector<uint8_t> msg(data, data + len);` Executable std::vector<uint8_t> msg(data, data + len);
9 statement.
4 ` msg.push_back(0x80);` Executable msg.push_back(0x80);
0 statement.
4 ` while ([Link]() % 64 != 56) Loop over while ([Link]() % 64 != 56)
1 msg.push_back(0x00);` items or msg.push_back(0x00);
until
condition
changes.
4 ` uint64_t bitlen = (uint64_t)total * 8;` Executable uint64_t bitlen = (uint64_t)total * 8;
2 statement.
4 ` for (int i = 7; i >= 0; --i)` Loop over for (int i = 7; i >= 0; --i)
3 items or
until
condition
changes.
4 ` msg.push_back((uint8_t)(bitlen >> (i * 8)));` Executable msg.push_back((uint8_t)(bitlen >> (i * 8)));
4 statement.
4 `` Blank line Separator between code blocks.
5 for
readability.
4 ` // Process each 512-bit block` Comment Process each 512-bit block
6 documentin
g intent.
4 ` for (size_t i = 0; i < [Link](); i += 64) {` Loop over for (size_t i = 0; i < [Link](); i += 64) {
7 items or
until
condition
changes.
4 ` uint32_t W[80];` Executable uint32_t W[80];
8 statement.
4 ` for (int t = 0; t < 16; ++t) {` Loop over for (int t = 0; t < 16; ++t) {
9 items or
until
condition
changes.

Page 197 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
5 ` W[t] = ((uint32_t)msg[i+t*4+0]<<24)\ ((uint32_t)m `
0 sg[i+t*4+1]<
<16)\
5 ` ((uint32_t)msg[i+t*4+2]<< 8)\ ((uint32_t)m Executable statement.
1 sg[i+t*4+3]);
`
5 ` }` Brace or C/C++ syntax structure.
2 parenthesis
closing/ope
ning a
block.
5 ` for (int t = 16; t < 80; ++t)` Loop over for (int t = 16; t < 80; ++t)
3 items or
until
condition
changes.
5 ` W[t] = SHA1_ROTL(W[t-3]^W[t-8]^W[t- Executable W[t] = SHA1_ROTL(W[t-3]^W[t-8]^W[t-14]^W[t-
4 14]^W[t-16], 1);` statement. 16], 1);
5 `` Blank line Separator between code blocks.
5 for
readability.
5 ` uint32_t Executable uint32_t a=H[0],b=H[1],c=H[2],d=H[3],e=H[4];
6 a=H[0],b=H[1],c=H[2],d=H[3],e=H[4];` statement.
5 ` for (int t = 0; t < 80; ++t) {` Loop over for (int t = 0; t < 80; ++t) {
7 items or
until
condition
changes.
5 ` uint32_t f, k;` Executable uint32_t f, k;
8 statement.
5 ` if (t < 20) { f=(b&c)\ ((~b)&d); Conditional branch — run code only when
9 k=0x5A827 condition true.
999u; }`
6 ` else if (t < 40) { f= b^c^d; Source else if (t < 40) { f= b^c^d; k=0x6ED9EBA1u; }
0 k=0x6ED9EBA1u; }` code line.
6 ` else if (t < 60) { f=(b&c)\ (b&d)\ (c&d);k=0x8F1BBCDCu; }`
1
6 ` else { f= b^c^d; Source else { f= b^c^d; k=0xCA62C1D6u; }
2 k=0xCA62C1D6u; }` code line.
6 ` uint32_t tmp = Executable uint32_t tmp = SHA1_ROTL(a,5)+f+e+k+W[t];
3 SHA1_ROTL(a,5)+f+e+k+W[t];` statement.
6 ` e=d; d=c; c=SHA1_ROTL(b,30); b=a; Executable e=d; d=c; c=SHA1_ROTL(b,30); b=a; a=tmp;
4 a=tmp;` statement.
6 ` }` Brace or C/C++ syntax structure.
5 parenthesis
closing/ope
ning a
block.
6 ` H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d; Executable H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d; H[4]+=e;
6 H[4]+=e;` statement.

Page 198 of 629


NADS Complete Technical Reference

L Source Easy Technical Explanation


i Explanati
n on
e
6 ` }` Brace or C/C++ syntax structure.
7 parenthesis
closing/ope
ning a
block.
6 ` for (int i = 0; i < 5; ++i) {` Loop over for (int i = 0; i < 5; ++i) {
8 items or
until
condition
changes.
6 ` out[i*4+0]=(H[i]>>24)&0xFF; Executable out[i*4+0]=(H[i]>>24)&0xFF;
9 out[i*4+1]=(H[i]>>16)&0xFF;` statement. out[i*4+1]=(H[i]>>16)&0xFF;
7 ` out[i*4+2]=(H[i]>> 8)&0xFF; out[i*4+3]=(H[i] Executable out[i*4+2]=(H[i]>> 8)&0xFF; out[i*4+3]=(H[i]
0 )&0xFF;` statement. )&0xFF;
7 ` }` Brace or C/C++ syntax structure.
1 parenthesis
closing/ope
ning a
block.
7 `}` Brace or C/C++ syntax structure.
2 parenthesis
closing/ope
ning a
block.
7 `` Blank line Separator between code blocks.
3 for
readability.
7 `std::string HttpServer::base64_encode(const Named std::string HttpServer::base64_encode(const
4 uint8_t* data, size_t len) {` constant — uint8_t* data, size_t len) {
value
should not
change.
7 ` static const char* Named static const char*
5 T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef constant — T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef
ghijklmnopqrstuvwxyz0123456789+/";` value ghijklmnopqrstuvwxyz012345
should not
change.
7 ` std::string out;` Executable std::string out;
6 statement.
7 ` [Link](((len+2)/3)*4);` Executable [Link](((len+2)/3)*4);
7 statement.
7 ` for (size_t i = 0; i < len; i += 3) {` Loop over for (size_t i = 0; i < len; i += 3) {
8 items or
until
condition
changes.
7 ` uint32_t v = (uint32_t)data[i] << 16;` Executable uint32_t v = (uint32_t)data[i] << 16;
9 statement.
8 ` if (i+1 < len) v \ = Conditional branch — run code only when
0 (uint32_t)da condition true.
ta[i+1] <<
8;`

Page 199 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
8 ` if (i+2 < len) v \ = Conditional branch — run code only when condition
1 (uint32_ true.
t)data[i+
2];`
8 ` out += T[(v>>18)&63]; out += T[(v>>12)&63];` Executa out += T[(v>>18)&63]; out += T[(v>>12)&63];
2 ble
stateme
nt.
8 ` out += (i+1<len) ? T[(v>>6)&63] : '=';` Executa out += (i+1<len) ? T[(v>>6)&63] : '=';
3 ble
stateme
nt.
8 ` out += (i+2<len) ? T[(v )&63] : '=';` Executa out += (i+2<len) ? T[(v )&63] : '=';
4 ble
stateme
nt.
8 ` }` Brace C/C++ syntax structure.
5 or
parenth
esis
closing/
opening
a block.
8 ` return out;` Exit return out;
6 function
and
give
back a
value.
8 `}` Brace C/C++ syntax structure.
7 or
parenth
esis
closing/
opening
a block.
8 `` Blank Separator between code blocks.
8 line for
readabil
ity.
8 `std::string HttpServer::ws_accept_key(const Named std::string HttpServer::ws_accept_key(const
9 std::string& client_key) {` constan std::string& client_key) {
t—
value
should
not
change.
9 ` // RFC 6455 §4.2.2` Comme RFC 6455 §4.2.2
0 nt
docume
nting
intent.
9 ` std::string s = client_key + "258EAFA5-E914- Executa std::string s = client_key + "258EAFA5-E914-47DA-
1 47DA-95CA-C5AB0DC85B11";` ble 95CA-C5AB0DC85B11";

Page 200 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
stateme
nt.
9 ` uint8_t digest[20];` Executa uint8_t digest[20];
2 ble
stateme
nt.
9 ` sha1((const uint8_t*)[Link](), [Link](), digest);` Named sha1((const uint8_t*)[Link](), [Link](), digest);
3 constan
t—
value
should
not
change.
9 ` return base64_encode(digest, 20);` Exit return base64_encode(digest, 20);
4 function
and
give
back a
value.
9 `}` Brace C/C++ syntax structure.
5 or
parenth
esis
closing/
opening
a block.
9 `` Blank Separator between code blocks.
6 line for
readabil
ity.
9 `// Comme ════════════════════════════════
7 ═════════════════════════════════ nt ════════════════════════════════
═════════════════════════════════ docume ════════════
══════════` nting
intent.
9 `// Constructor / Destructor` Comme Constructor / Destructor
8 nt
docume
nting
intent.
9 `// Comme ════════════════════════════════
9 ═════════════════════════════════ nt ════════════════════════════════
═════════════════════════════════ docume ════════════
══════════` nting
intent.
1 `` Blank Separator between code blocks.
0 line for
0 readabil
ity.
1 `HttpServer::HttpServer(int port, Orchestrator* orch)` Source HttpServer::HttpServer(int port, Orchestrator* orch)
0 code
1 line.
1 ` : port_(port), orch_(orch) {}` Source : port_(port), orch_(orch) {}
0 code
2 line.

Page 201 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
1 `` Blank Separator between code blocks.
0 line for
3 readabil
ity.
1 `HttpServer::~HttpServer() { stop(); }` Source HttpServer::~HttpServer() { stop(); }
0 code
4 line.
1 `` Blank Separator between code blocks.
0 line for
5 readabil
ity.
1 `// Comme ════════════════════════════════
0 ═════════════════════════════════ nt ════════════════════════════════
6 ═════════════════════════════════ docume ════════════
══════════` nting
intent.
1 `// Start / Stop` Comme Start / Stop
0 nt
7 docume
nting
intent.
1 `// Comme ════════════════════════════════
0 ═════════════════════════════════ nt ════════════════════════════════
8 ═════════════════════════════════ docume ════════════
══════════` nting
intent.
1 `` Blank Separator between code blocks.
0 line for
9 readabil
ity.
1 `bool HttpServer::start() {` Source bool HttpServer::start() {
1 code
0 line.
1 ` if (running_.exchange(true)) return false;` Conditio if (running_.exchange(true)) return false;
1 nal
1 branch
— run
code
only
when
conditio
n true.
1 ` server_thread_ = Own a Heap object with unique ownership.
1 std::make_unique<std::thread>([this]{ server_loop(); module
2 });` object;
auto-
deleted
when
done.
1 ` return true;` Exit return true;
1 function
3 and
give
back a
value.

Page 202 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
1 `}` Brace C/C++ syntax structure.
1 or
4 parenth
esis
closing/
opening
a block.
1 `` Blank Separator between code blocks.
1 line for
5 readabil
ity.
1 `void HttpServer::stop() {` Source void HttpServer::stop() {
1 code
6 line.
1 ` if (!running_.exchange(false)) return;` Conditio if (!running_.exchange(false)) return;
1 nal
7 branch
— run
code
only
when
conditio
n true.
1 ` if (listen_fd_ >= 0) { close(listen_fd_); listen_fd_ = Conditio if (listen_fd_ >= 0) { close(listen_fd_); listen_fd_ = -1;
1 -1; }` nal }
8 branch
— run
code
only
when
conditio
n true.
1 ` if (server_thread_ && server_thread_->joinable()) Conditio if (server_thread_ && server_thread_->joinable())
1 server_thread_->join();` nal server_thread_->join();
9 branch
— run
code
only
when
conditio
n true.
1 `}` Brace C/C++ syntax structure.
2 or
0 parenth
esis
closing/
opening
a block.
1 `` Blank Separator between code blocks.
2 line for
1 readabil
ity.
1 `// Comme ════════════════════════════════
2 ═════════════════════════════════ nt ════════════════════════════════
2 ═════════════════════════════════ docume ════════════
══════════`

Page 203 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
nting
intent.
1 `// Main server loop (select-based, single thread)` Comme Main server loop (select-based, single thread)
2 nt
3 docume
nting
intent.
1 `// Comme ════════════════════════════════
2 ═════════════════════════════════ nt ════════════════════════════════
4 ═════════════════════════════════ docume ════════════
══════════` nting
intent.
1 `` Blank Separator between code blocks.
2 line for
5 readabil
ity.
1 `void HttpServer::server_loop() {` Source void HttpServer::server_loop() {
2 code
6 line.
1 ` listen_fd_ = socket(AF_INET, SOCK_STREAM, Executa listen_fd_ = socket(AF_INET, SOCK_STREAM, 0);
2 0);` ble
7 stateme
nt.
1 ` if (listen_fd_ < 0) { std::cerr<<"[HTTP] socket Conditio if (listen_fd_ < 0) { std::cerr<<"[HTTP] socket
2 failed\n"; return; }` nal failed\n"; return; }
8 branch
— run
code
only
when
conditio
n true.
1 `` Blank Separator between code blocks.
2 line for
9 readabil
ity.
1 ` int opt = 1;` Executa int opt = 1;
3 ble
0 stateme
nt.
1 ` setsockopt(listen_fd_, SOL_SOCKET, Executa setsockopt(listen_fd_, SOL_SOCKET,
3 SO_REUSEADDR, &opt, sizeof(opt));` ble SO_REUSEADDR, &opt, sizeof(opt));
1 stateme
nt.
1 ` fcntl(listen_fd_, F_SETFL, O_NONBLOCK);` Executa fcntl(listen_fd_, F_SETFL, O_NONBLOCK);
3 ble
2 stateme
nt.
1 `` Blank Separator between code blocks.
3 line for
3 readabil
ity.

Page 204 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
1 ` sockaddr_in addr{};` Executa sockaddr_in addr{};
3 ble
4 stateme
nt.
1 ` addr.sin_family = AF_INET;` Executa addr.sin_family = AF_INET;
3 ble
5 stateme
nt.
1 ` addr.sin_port = htons(port_);` Executa addr.sin_port = htons(port_);
3 ble
6 stateme
nt.
1 ` addr.sin_addr.s_addr = htonl(INADDR_ANY);` Executa addr.sin_addr.s_addr = htonl(INADDR_ANY);
3 ble
7 stateme
nt.
1 `` Blank Separator between code blocks.
3 line for
8 readabil
ity.
1 ` if \ `
3 (bind(listen_fd_,(sockaddr*)&addr,sizeof(addr))<0 \
9
1 ` listen(listen_fd_,16)<0) {` Source listen(listen_fd_,16)<0) {
4 code
0 line.
1 ` std::cerr<<"[HTTP] bind/listen failed on port Executa std::cerr<<"[HTTP] bind/listen failed on port
4 "<<port_<<"\n";` ble "<<port_<<"\n";
1 stateme
nt.
1 ` close(listen_fd_); listen_fd_=-1; return;` Executa close(listen_fd_); listen_fd_=-1; return;
4 ble
2 stateme
nt.
1 ` }` Brace C/C++ syntax structure.
4 or
3 parenth
esis
closing/
opening
a block.
1 ` std::cout<<"[HTTP] Listening on port Executa std::cout<<"[HTTP] Listening on port "<<port_<<"\n";
4 "<<port_<<"\n";` ble
4 stateme
nt.
1 `` Blank Separator between code blocks.
4 line for
5 readabil
ity.
1 ` while (running_.load()) {` Thread- std::memory_order relaxed typical.
4 safe
6 update
or read

Page 205 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
of a
statistic.
1 ` fd_set rfds;` Executa fd_set rfds;
4 ble
7 stateme
nt.
1 ` FD_ZERO(&rfds);` Executa FD_ZERO(&rfds);
4 ble
8 stateme
nt.
1 ` FD_SET(listen_fd_, &rfds);` Executa FD_SET(listen_fd_, &rfds);
4 ble
9 stateme
nt.
1 ` int maxfd = listen_fd_;` Executa int maxfd = listen_fd_;
5 ble
0 stateme
nt.
1 `` Blank Separator between code blocks.
5 line for
1 readabil
ity.
1 ` {` Brace C/C++ syntax structure.
5 or
2 parenth
esis
closing/
opening
a block.
1 ` std::lock_guard<std::mutex> Lock a RAII mutex lock.
5 lk(clients_mtx_);` mutex
3 so only
one
thread
uses
shared
data at
a time.
1 ` for (auto& c : clients_) {` Loop for (auto& c : clients_) {
5 over
4 items or
until
conditio
n
change
s.
1 ` if (c && c->fd >= 0 && !c->closing) {` Conditio if (c && c->fd >= 0 && !c->closing) {
5 nal
5 branch
— run
code
only
when
conditio
n true.

Page 206 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
1 ` FD_SET(c->fd, &rfds);` Executa FD_SET(c->fd, &rfds);
5 ble
6 stateme
nt.
1 ` maxfd = std::max(maxfd, c->fd);` Executa maxfd = std::max(maxfd, c->fd);
5 ble
7 stateme
nt.
1 ` }` Brace C/C++ syntax structure.
5 or
8 parenth
esis
closing/
opening
a block.
1 ` }` Brace C/C++ syntax structure.
5 or
9 parenth
esis
closing/
opening
a block.
1 ` }` Brace C/C++ syntax structure.
6 or
0 parenth
esis
closing/
opening
a block.

Line Source Easy Technical Explanation


Explanation
161 `` Blank line for Separator between code blocks.
readability.
162 ` timeval tv{1,0};` Executable timeval tv{1,0};
statement.
163 ` if (select(maxfd+1, &rfds, nullptr, Conditional branch if (select(maxfd+1, &rfds, nullptr, nullptr,
nullptr, &tv) < 0) continue;` — run code only &tv) < 0) continue;
when condition
true.
164 `` Blank line for Separator between code blocks.
readability.
165 ` // Accept new connection` Comment Accept new connection
documenting intent.
166 ` if (FD_ISSET(listen_fd_, &rfds)) {` Conditional branch if (FD_ISSET(listen_fd_, &rfds)) {
— run code only
when condition
true.
167 ` sockaddr_in ca{}; socklen_t Executable sockaddr_in ca{}; socklen_t
cl=sizeof(ca);` statement. cl=sizeof(ca);
168 ` int fd = Executable int fd =
accept(listen_fd_,(sockaddr*)&ca,&cl);` statement. accept(listen_fd_,(sockaddr*)&ca,&cl);

Page 207 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
169 ` if (fd >= 0) {` Conditional branch if (fd >= 0) {
— run code only
when condition
true.
170 ` fcntl(fd, F_SETFL, Executable fcntl(fd, F_SETFL, O_NONBLOCK);
O_NONBLOCK);` statement.
171 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(clients_mtx_);` only one thread
uses shared data
at a time.
172 ` auto cl2 = Own a module Heap object with unique ownership.
std::make_unique<Client>();` object; auto-
deleted when done.
173 ` cl2->fd = fd;` Executable cl2->fd = fd;
statement.
174 ` Executable clients_.push_back(std::move(cl2));
clients_.push_back(std::move(cl2));` statement.
175 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
176 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
177 `` Blank line for Separator between code blocks.
readability.
178 ` // Service existing connections` Comment Service existing connections
documenting intent.
179 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
180 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(clients_mtx_);` only one thread
uses shared data
at a time.
181 ` for (auto& cp : clients_) {` Loop over items or for (auto& cp : clients_) {
until condition
changes.
182 ` if (!cp \ \ cp->fd < 0 \
183 ` if (!FD_ISSET(cp->fd, &rfds)) Conditional branch if (!FD_ISSET(cp->fd, &rfds)) continue;
continue;` — run code only
when condition
true.
184 `` Blank line for Separator between code blocks.
readability.
185 ` char buf[8192];` Executable char buf[8192];
statement.
186 ` ssize_t n = recv(cp->fd, buf, Executable ssize_t n = recv(cp->fd, buf, sizeof(buf),
sizeof(buf), 0);` statement. 0);

Page 208 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
187 ` if (n <= 0) { cp->closing = true; Conditional branch if (n <= 0) { cp->closing = true; continue;
continue; }` — run code only }
when condition
true.
188 `` Blank line for Separator between code blocks.
readability.
189 ` cp->[Link](buf, n);` Executable cp->[Link](buf, n);
statement.
190 `` Blank line for Separator between code blocks.
readability.
191 ` if (!cp->upgraded) {` Conditional branch if (!cp->upgraded) {
— run code only
when condition
true.
192 ` // Look for full HTTP Comment Look for full HTTP headers
headers` documenting intent.
193 ` auto pos = cp- Executable auto pos = cp->[Link]("\r\n\r\n");
>[Link]("\r\n\r\n");` statement.
194 ` if (pos == std::string::npos) Conditional branch if (pos == std::string::npos) continue;
continue;` — run code only
when condition
true.
195 `` Blank line for Separator between code blocks.
readability.
196 ` // Try WebSocket upgrade Comment Try WebSocket upgrade first
first` documenting intent.
197 ` if (cp->[Link]("Upgrade: \ `
websocket") != std::string::npos \
198 ` cp->[Link]("Upgrade: Source code line. cp->[Link]("Upgrade: WebSocket") !=
WebSocket") != std::string::npos) {` std::string::npos) {
199 ` if (!try_ws_upgrade(*cp, Conditional branch if (!try_ws_upgrade(*cp, cp->rbuf)) {
cp->rbuf)) {` — run code only
when condition
true.
200 ` cp->closing = true;` Executable cp->closing = true;
statement.
201 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
202 ` cp->[Link]();` Executable cp->[Link]();
statement.
203 ` } else {` Source code line. } else {
204 ` // Regular HTTP` Comment Regular HTTP
documenting intent.
205 ` if (!try_handle_http(*cp)) {` Conditional branch if (!try_handle_http(*cp)) {
— run code only
when condition
true.
206 ` cp->closing = true;` Executable cp->closing = true;
statement.

Page 209 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
207 ` } else {` Source code line. } else {
208 ` cp->closing = true; // Source code line. cp->closing = true; // HTTP is close-
HTTP is close-after-reply` after-reply
209 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
210 ` cp->[Link]();` Executable cp->[Link]();
statement.
211 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
212 ` } else {` Source code line. } else {
213 ` // WebSocket frames` Comment WebSocket frames
documenting intent.
214 ` ws_handle_frames(*cp);` Executable ws_handle_frames(*cp);
statement.
215 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
216 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
217 `` Blank line for Separator between code blocks.
readability.
218 ` // Reap closed connections` Comment Reap closed connections
documenting intent.
219 ` clients_.erase(` Source code line. clients_.erase(
220 ` std::remove_if(clients_.begin(), Source code line. std::remove_if(clients_.begin(),
clients_.end(),` clients_.end(),
221 ` [](const Own a module Heap object with unique ownership.
std::unique_ptr<Client>& c){` object; auto-
deleted when done.
222 ` if (!c \ \ c->closing) {`
223 ` if (c && c->fd>=0) Conditional branch if (c && c->fd>=0) close(c->fd);
close(c->fd);` — run code only
when condition
true.
224 ` return true;` Exit function and return true;
give back a value.
225 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
226 ` return false;` Exit function and return false;
give back a value.
227 ` }),` Source code line. }),

Page 210 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
228 ` clients_.end());` Executable clients_.end());
statement.
229 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
230 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
231 `` Blank line for Separator between code blocks.
readability.
232 ` // Clean up all connections` Comment Clean up all connections
documenting intent.
233 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
234 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(clients_mtx_);` only one thread
uses shared data
at a time.
235 ` for (auto& c : clients_) if (c && c- Loop over items or for (auto& c : clients_) if (c && c-
>fd>=0) close(c->fd);` until condition >fd>=0) close(c->fd);
changes.
236 ` clients_.clear();` Executable clients_.clear();
statement.
237 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
238 ` if (listen_fd_ >= 0) { close(listen_fd_); Conditional branch if (listen_fd_ >= 0) { close(listen_fd_);
listen_fd_=-1; }` — run code only listen_fd_=-1; }
when condition
true.
239 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
240 `` Blank line for Separator between code blocks.
readability.

Li Source Easy Technical Explanation


n Expla
e natio
n
2 `// Comm ═════════════════════════════════
4 ═════════════════════════════════ ent ═════════════════════════════════
1 ═════════════════════════════════ docum ══════════
══════════` enting
intent.

Page 211 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 `// WebSocket Upgrade` Comm WebSocket Upgrade
4 ent
2 docum
enting
intent.
2 `// Comm ═════════════════════════════════
4 ═════════════════════════════════ ent ═════════════════════════════════
3 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
2 `` Blank Separator between code blocks.
4 line for
4 reada
bility.
2 `bool HttpServer::try_ws_upgrade(Client& c, const Name bool HttpServer::try_ws_upgrade(Client& c, const
4 std::string& req) {` d std::string& req) {
5 consta
nt —
value
should
not
chang
e.
2 ` // Extract Sec-WebSocket-Key` Comm Extract Sec-WebSocket-Key
4 ent
6 docum
enting
intent.
2 ` auto pos = [Link]("Sec-WebSocket-Key:");` Execu auto pos = [Link]("Sec-WebSocket-Key:");
4 table
7 statem
ent.
2 ` if (pos == std::string::npos) pos = [Link]("sec- Condit if (pos == std::string::npos) pos = [Link]("sec-
4 websocket-key:");` ional websocket-key:");
8 branc
h—
run
code
only
when
conditi
on
true.
2 ` if (pos == std::string::npos) return false;` Condit if (pos == std::string::npos) return false;
4 ional
9 branc
h—
run
code
only
when
conditi
on
true.

Page 212 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 `` Blank Separator between code blocks.
5 line for
0 reada
bility.
2 ` pos = [Link](':', pos) + 1;` Execu pos = [Link](':', pos) + 1;
5 table
1 statem
ent.
2 ` while (pos < [Link]() && req[pos]==' ') ++pos;` Loop while (pos < [Link]() && req[pos]==' ') ++pos;
5 over
2 items
or until
conditi
on
chang
es.
2 ` auto end = [Link]("\r\n", pos);` Execu auto end = [Link]("\r\n", pos);
5 table
3 statem
ent.
2 ` std::string key = [Link](pos, end-pos);` Execu std::string key = [Link](pos, end-pos);
5 table
4 statem
ent.
2 ` // trim` Comm trim
5 ent
5 docum
enting
intent.
2 ` while (![Link]() && ([Link]()=='\r'\ \ [Link]()=='\n'\
5
6
2 `` Blank Separator between code blocks.
5 line for
7 reada
bility.
2 ` std::string accept = ws_accept_key(key);` Execu std::string accept = ws_accept_key(key);
5 table
8 statem
ent.
2 ` std::string resp =` Sourc std::string resp =
5 e code
9 line.
2 ` "HTTP/1.1 101 Switching Protocols\r\n"` Sourc "HTTP/1.1 101 Switching Protocols\r\n"
6 e code
0 line.
2 ` "Upgrade: websocket\r\n"` Sourc "Upgrade: websocket\r\n"
6 e code
1 line.
2 ` "Connection: Upgrade\r\n"` Sourc "Connection: Upgrade\r\n"
6 e code
2 line.

Page 213 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` "Sec-WebSocket-Accept: " + accept + "\r\n"` Sourc "Sec-WebSocket-Accept: " + accept + "\r\n"
6 e code
3 line.
2 ` "Access-Control-Allow-Origin: *\r\n"` Sourc "Access-Control-Allow-Origin: *\r\n"
6 e code
4 line.
2 ` "\r\n";` Execu "\r\n";
6 table
5 statem
ent.
2 `` Blank Separator between code blocks.
6 line for
6 reada
bility.
2 ` ssize_t sent = send([Link], resp.c_str(), [Link](), Execu ssize_t sent = send([Link], resp.c_str(), [Link](),
6 MSG_NOSIGNAL);` table MSG_NOSIGNAL);
7 statem
ent.
2 ` if (sent <= 0) return false;` Condit if (sent <= 0) return false;
6 ional
8 branc
h—
run
code
only
when
conditi
on
true.
2 `` Blank Separator between code blocks.
6 line for
9 reada
bility.
2 ` [Link] = true;` Execu [Link] = true;
7 table
0 statem
ent.
2 ` std::cout<<"[WS] Client upgraded Execu std::cout<<"[WS] Client upgraded fd="<<[Link]<<"\n";
7 fd="<<[Link]<<"\n";` table
1 statem
ent.
2 ` return true;` Exit return true;
7 functio
2 n and
give
back a
value.
2 `}` Brace C/C++ syntax structure.
7 or
3 parent
hesis
closin
g/ope

Page 214 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
ning a
block.
2 `` Blank Separator between code blocks.
7 line for
4 reada
bility.
2 `// Comm ═════════════════════════════════
7 ═════════════════════════════════ ent ═════════════════════════════════
5 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
2 `// WebSocket frame send (server→client, no Comm WebSocket frame send (server→client, no masking
7 masking per RFC 6455)` ent per RFC 6455)
6 docum
enting
intent.
2 `// Comm ═════════════════════════════════
7 ═════════════════════════════════ ent ═════════════════════════════════
7 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
2 `` Blank Separator between code blocks.
7 line for
8 reada
bility.
2 `void HttpServer::ws_send_text(Client& c, const Name void HttpServer::ws_send_text(Client& c, const
7 std::string& payload) {` d std::string& payload) {
9 consta
nt —
value
should
not
chang
e.
2 ` if ([Link] < 0 \ \ [Link]) return;`
8
0
2 ` size_t plen = [Link]();` Execu size_t plen = [Link]();
8 table
1 statem
ent.
2 ` std::vector<uint8_t> frame;` Execu std::vector<uint8_t> frame;
8 table
2 statem
ent.
2 ` frame.push_back(0x81); // FIN + opcode=1 (text)` Sourc frame.push_back(0x81); // FIN + opcode=1 (text)
8 e code
3 line.
2 ` if (plen < 126) {` Condit if (plen < 126) {
8 ional
4 branc
h—
run

Page 215 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
code
only
when
conditi
on
true.
2 ` frame.push_back((uint8_t)plen);` Execu frame.push_back((uint8_t)plen);
8 table
5 statem
ent.
2 ` } else if (plen < 65536) {` Condit } else if (plen < 65536) {
8 ional
6 branc
h—
run
code
only
when
conditi
on
true.
2 ` frame.push_back(126);` Execu frame.push_back(126);
8 table
7 statem
ent.
2 ` frame.push_back((uint8_t)(plen >> 8));` Execu frame.push_back((uint8_t)(plen >> 8));
8 table
8 statem
ent.
2 ` frame.push_back((uint8_t)(plen & 0xFF));` Execu frame.push_back((uint8_t)(plen & 0xFF));
8 table
9 statem
ent.
2 ` } else {` Sourc } else {
9 e code
0 line.
2 ` frame.push_back(127);` Execu frame.push_back(127);
9 table
1 statem
ent.
2 ` for (int i = 7; i >= 0; --i)` Loop for (int i = 7; i >= 0; --i)
9 over
2 items
or until
conditi
on
chang
es.
2 ` frame.push_back((uint8_t)(plen >> (i*8)));` Execu frame.push_back((uint8_t)(plen >> (i*8)));
9 table
3 statem
ent.

Page 216 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` }` Brace C/C++ syntax structure.
9 or
4 parent
hesis
closin
g/ope
ning a
block.
2 ` [Link]([Link](), [Link](), Execu [Link]([Link](), [Link](),
9 [Link]());` table [Link]());
5 statem
ent.
2 ` send([Link], [Link](), [Link](), Execu send([Link], [Link](), [Link](),
9 MSG_NOSIGNAL);` table MSG_NOSIGNAL);
6 statem
ent.
2 `}` Brace C/C++ syntax structure.
9 or
7 parent
hesis
closin
g/ope
ning a
block.
2 `` Blank Separator between code blocks.
9 line for
8 reada
bility.
2 `void HttpServer::ws_broadcast(const std::string& Name void HttpServer::ws_broadcast(const std::string&
9 payload) {` d payload) {
9 consta
nt —
value
should
not
chang
e.
3 ` std::lock_guard<std::mutex> lk(clients_mtx_);` Lock a RAII mutex lock.
0 mutex
0 so
only
one
thread
uses
share
d data
at a
time.
3 ` for (auto& cp : clients_) {` Loop for (auto& cp : clients_) {
0 over
1 items
or until
conditi
on
chang
es.

Page 217 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` if (cp && cp->upgraded && !cp->closing)` Condit if (cp && cp->upgraded && !cp->closing)
0 ional
2 branc
h—
run
code
only
when
conditi
on
true.
3 ` ws_send_text(*cp, payload);` Execu ws_send_text(*cp, payload);
0 table
3 statem
ent.
3 ` }` Brace C/C++ syntax structure.
0 or
4 parent
hesis
closin
g/ope
ning a
block.
3 `}` Brace C/C++ syntax structure.
0 or
5 parent
hesis
closin
g/ope
ning a
block.
3 `` Blank Separator between code blocks.
0 line for
6 reada
bility.
3 `// Comm ═════════════════════════════════
0 ═════════════════════════════════ ent ═════════════════════════════════
7 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 `// WebSocket frame receive (client→server, always Comm WebSocket frame receive (client→server, always
0 masked)` ent masked)
8 docum
enting
intent.
3 `// Comm ═════════════════════════════════
0 ═════════════════════════════════ ent ═════════════════════════════════
9 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 `` Blank Separator between code blocks.
1 line for
0 reada
bility.

Page 218 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 `void HttpServer::ws_handle_frames(Client& c) {` Sourc void HttpServer::ws_handle_frames(Client& c) {
1 e code
1 line.
3 ` auto& buf = [Link];` Execu auto& buf = [Link];
1 table
2 statem
ent.
3 ` while ([Link]() >= 2) {` Loop while ([Link]() >= 2) {
1 over
3 items
or until
conditi
on
chang
es.
3 ` uint8_t b0 = (uint8_t)buf[0];` Execu uint8_t b0 = (uint8_t)buf[0];
1 table
4 statem
ent.
3 ` uint8_t b1 = (uint8_t)buf[1];` Execu uint8_t b1 = (uint8_t)buf[1];
1 table
5 statem
ent.
3 ` // bool fin = (b0 & 0x80) != 0;` Comm bool fin = (b0 & 0x80) != 0;
1 ent
6 docum
enting
intent.
3 ` uint8_t opcode = b0 & 0x0F;` Execu uint8_t opcode = b0 & 0x0F;
1 table
7 statem
ent.
3 ` bool masked = (b1 & 0x80) != 0;` Execu bool masked = (b1 & 0x80) != 0;
1 table
8 statem
ent.
3 ` uint64_t plen = b1 & 0x7F;` Execu uint64_t plen = b1 & 0x7F;
1 table
9 statem
ent.
3 `` Blank Separator between code blocks.
2 line for
0 reada
bility.

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` size_t header = 2;` Execut size_t header = 2;
2 able
1 statem
ent.

Page 219 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` if (plen == 126) header += 2;` Conditi if (plen == 126) header += 2;
2 onal
2 branch
— run
code
only
when
conditi
on
true.
3 ` else if (plen == 127) header += 8;` Execut else if (plen == 127) header += 8;
2 able
3 statem
ent.
3 ` if (masked) header += 4;` Conditi if (masked) header += 4;
2 onal
4 branch
— run
code
only
when
conditi
on
true.
3 `` Blank Separator between code blocks.
2 line for
5 readab
ility.
3 ` if ([Link]() < header) break;` Conditi if ([Link]() < header) break;
2 onal
6 branch
— run
code
only
when
conditi
on
true.
3 `` Blank Separator between code blocks.
2 line for
7 readab
ility.
3 ` if (plen == 126) {` Conditi if (plen == 126) {
2 onal
8 branch
— run
code
only
when
conditi
on
true.
3 ` plen = ((uint8_t)buf[2]<<8) \ (uint8_ Executable statement.
2 t)buf[3]
9 ;`

Page 220 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` } else if (plen == 127) {` Conditi } else if (plen == 127) {
3 onal
0 branch
— run
code
only
when
conditi
on
true.
3 ` plen = 0;` Execut plen = 0;
3 able
1 statem
ent.
3 ` for (int i = 0; i < 8; ++i)` Loop for (int i = 0; i < 8; ++i)
3 over
2 items
or until
conditi
on
change
s.
3 ` plen = (plen<<8)\ (uint8_ Executable statement.
3 t)buf[2
3 +i];`
3 ` }` Brace C/C++ syntax structure.
3 or
4 parent
hesis
closing
/openin
ga
block.
3 `` Blank Separator between code blocks.
3 line for
5 readab
ility.
3 ` if ([Link]() < header + plen) break;` Conditi if ([Link]() < header + plen) break;
3 onal
6 branch
— run
code
only
when
conditi
on
true.
3 `` Blank Separator between code blocks.
3 line for
7 readab
ility.
3 ` // Decode payload` Comm Decode payload
3 ent
8 docum

Page 221 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
enting
intent.
3 ` std::string payload([Link]()+header, plen);` Execut std::string payload([Link]()+header, plen);
3 able
9 statem
ent.
3 ` if (masked) {` Conditi if (masked) {
4 onal
0 branch
— run
code
only
when
conditi
on
true.
3 ` const uint8_t* mask = (const Named const uint8_t* mask = (const uint8_t*)[Link]() +
4 uint8_t*)[Link]() + (header-4);` consta (header-4);
1 nt —
value
should
not
change
.
3 ` for (size_t i = 0; i < plen; ++i)` Loop for (size_t i = 0; i < plen; ++i)
4 over
2 items
or until
conditi
on
change
s.
3 ` payload[i] ^= mask[i & 3];` Execut payload[i] ^= mask[i & 3];
4 able
3 statem
ent.
3 ` }` Brace C/C++ syntax structure.
4 or
4 parent
hesis
closing
/openin
ga
block.
3 ` [Link](0, header + plen);` Execut [Link](0, header + plen);
4 able
5 statem
ent.
3 `` Blank Separator between code blocks.
4 line for
6 readab
ility.
3 ` // Handle opcodes` Comm Handle opcodes
4 ent
7 docum

Page 222 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
enting
intent.
3 ` if (opcode == 0x8) { [Link] = true; return; } // Conditi if (opcode == 0x8) { [Link] = true; return; } // close
4 close` onal
8 branch
— run
code
only
when
conditi
on
true.
3 ` if (opcode == 0x9) { // ping → pong` Conditi if (opcode == 0x9) { // ping → pong
4 onal
9 branch
— run
code
only
when
conditi
on
true.
3 ` std::vector<uint8_t> pong = {0x8A, 0x00};` Execut std::vector<uint8_t> pong = {0x8A, 0x00};
5 able
0 statem
ent.
3 ` send([Link], [Link](), [Link](), Execut send([Link], [Link](), [Link](),
5 MSG_NOSIGNAL);` able MSG_NOSIGNAL);
1 statem
ent.
3 ` }` Brace C/C++ syntax structure.
5 or
2 parent
hesis
closing
/openin
ga
block.
3 ` // Text/binary frames: we don't need to act on Comm Text/binary frames: we don't need to act on them
5 them currently` ent currently
3 docum
enting
intent.
3 ` }` Brace C/C++ syntax structure.
5 or
4 parent
hesis
closing
/openin
ga
block.
3 `}` Brace C/C++ syntax structure.
5 or
5 parent
hesis

Page 223 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
closing
/openin
ga
block.
3 `` Blank Separator between code blocks.
5 line for
6 readab
ility.
3 `// Comm ═════════════════════════════════
5 ═════════════════════════════════ ent ═════════════════════════════════
7 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 `// HTTP request handling` Comm HTTP request handling
5 ent
8 docum
enting
intent.
3 `// Comm ═════════════════════════════════
5 ═════════════════════════════════ ent ═════════════════════════════════
9 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 `` Blank Separator between code blocks.
6 line for
0 readab
ility.
3 `bool HttpServer::try_handle_http(Client& c) {` Source bool HttpServer::try_handle_http(Client& c) {
6 code
1 line.
3 ` std::istringstream iss([Link]);` Execut std::istringstream iss([Link]);
6 able
2 statem
ent.
3 ` std::string method, path, ver;` Execut std::string method, path, ver;
6 able
3 statem
ent.
3 ` iss >> method >> path >> ver;` Execut iss >> method >> path >> ver;
6 able
4 statem
ent.
3 `` Blank Separator between code blocks.
6 line for
5 readab
ility.
3 ` // Extract body (after \r\n\r\n)` Comm Extract body (after \r\n\r\n)
6 ent
6 docum
enting
intent.

Page 224 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` std::string body;` Execut std::string body;
6 able
7 statem
ent.
3 ` auto bpos = [Link]("\r\n\r\n");` Execut auto bpos = [Link]("\r\n\r\n");
6 able
8 statem
ent.
3 ` if (bpos != std::string::npos) body = Conditi if (bpos != std::string::npos) body =
6 [Link](bpos+4);` onal [Link](bpos+4);
9 branch
— run
code
only
when
conditi
on
true.
3 `` Blank Separator between code blocks.
7 line for
0 readab
ility.
3 ` std::string resp = dispatch(method, path, body, Execut std::string resp = dispatch(method, path, body,
7 [Link]);` able [Link]);
1 statem
ent.
3 ` ssize_t n = send([Link], resp.c_str(), [Link](), Execut ssize_t n = send([Link], resp.c_str(), [Link](),
7 MSG_NOSIGNAL);` able MSG_NOSIGNAL);
2 statem
ent.
3 ` return n > 0;` Exit return n > 0;
7 functio
3 n and
give
back a
value.
3 `}` Brace C/C++ syntax structure.
7 or
4 parent
hesis
closing
/openin
ga
block.
3 `` Blank Separator between code blocks.
7 line for
5 readab
ility.
3 `std::string HttpServer::dispatch(const std::string& Named std::string HttpServer::dispatch(const std::string&
7 method,` consta method,
6 nt —
value
should
not

Page 225 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
change
.
3 ` const std::string& path,` Named const std::string& path,
7 consta
7 nt —
value
should
not
change
.
3 ` const std::string& /*body*/,` Named const std::string& /*body*/,
7 consta
8 nt —
value
should
not
change
.
3 ` const std::string& /*req*/) {` Named const std::string& /*req*/) {
7 consta
9 nt —
value
should
not
change
.
3 ` // CORS preflight` Comm CORS preflight
8 ent
0 docum
enting
intent.
3 ` if (method == "OPTIONS") {` Conditi if (method == "OPTIONS") {
8 onal
1 branch
— run
code
only
when
conditi
on
true.
3 ` return "HTTP/1.1 204 No Content\r\n"` Exit return "HTTP/1.1 204 No Content\r\n"
8 functio
2 n and
give
back a
value.
3 ` "Access-Control-Allow-Origin: *\r\n"` Source "Access-Control-Allow-Origin: *\r\n"
8 code
3 line.
3 ` "Access-Control-Allow-Methods: GET, Source "Access-Control-Allow-Methods: GET, POST,
8 POST, OPTIONS\r\n"` code OPTIONS\r\n"
4 line.

Page 226 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` "Access-Control-Allow-Headers: Content- Source "Access-Control-Allow-Headers: Content-Type\r\n"
8 Type\r\n"` code
5 line.
3 ` "Content-Length: 0\r\n\r\n";` Execut "Content-Length: 0\r\n\r\n";
8 able
6 statem
ent.
3 ` }` Brace C/C++ syntax structure.
8 or
7 parent
hesis
closing
/openin
ga
block.
3 `` Blank Separator between code blocks.
8 line for
8 readab
ility.
3 ` // API routes` Comm API routes
8 ent
9 docum
enting
intent.
3 ` if (path == "/api/packets") return Conditi if (path == "/api/packets") return api_packets();
9 api_packets();` onal
0 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/alerts") return api_alerts();` Conditi if (path == "/api/alerts") return api_alerts();
9 onal
1 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/summary") return Conditi if (path == "/api/summary") return
9 api_summary();` onal api_summary();
2 branch
— run
code
only
when
conditi
on
true.

Page 227 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` if (path == "/api/flows") return api_flows();` Conditi if (path == "/api/flows") return api_flows();
9 onal
3 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/threat-timeline") return Conditi if (path == "/api/threat-timeline") return
9 api_threat_timeline();` onal api_threat_timeline();
4 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/threat-ips") return Conditi if (path == "/api/threat-ips") return
9 api_threat_ips();` onal api_threat_ips();
5 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/protocol-stats") return Conditi if (path == "/api/protocol-stats") return
9 api_protocol_stats();` onal api_protocol_stats();
6 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/capture/status") return Conditi if (path == "/api/capture/status") return
9 api_capture_status();` onal api_capture_status();
7 branch
— run
code
only
when
conditi
on
true.
3 ` if (path == "/api/interfaces") return Conditi if (path == "/api/interfaces") return
9 api_interfaces();` onal api_interfaces();
8 branch
— run
code
only
when

Page 228 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
conditi
on
true.
3 ` if (path == "/api/config") return Conditi if (path == "/api/config") return
9 api_config_get();` onal api_config_get();
9 branch
— run
code
only
when
conditi
on
true.
4 ` if (path == "/api/io-graph") return Conditi if (path == "/api/io-graph") return
0 api_io_graph();` onal api_io_graph();
0 branch
— run
code
only
when
conditi
on
true.

Li Source Easy Technical Explanation


n Expla
e natio
n
4 ` if (path == "/metrics") return Condit if (path == "/metrics") return api_metrics();
0 api_metrics();` ional
1 branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path == "/api/capture/start")
0 "/api/capture/start") return api_capture_start();` ional return api_capture_start(
2 branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path ==
0 "/api/capture/pause") return api_capture_pause();` ional "/api/capture/pause") return api_capture_pause(
3 branc
h—
run
code

Page 229 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path ==
0 "/api/capture/resume") return api_capture_resume();` ional "/api/capture/resume") return api_capture_resume
4 branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == "/api/config") Condit if (method == "POST" && path == "/api/config")
0 return api_config_save();` ional return api_config_save();
5 branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path ==
0 "/api/baseline/recalculate") return ional "/api/baseline/recalculate") return api_baseline
6 api_baseline_recalc();` branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path ==
0 "/api/baseline/reset") return api_baseline_reset();` ional "/api/baseline/reset") return api_baseline
7 branc
h—
run
code
only
when
conditi
on
true.
4 ` if (method == "POST" && path == Condit if (method == "POST" && path == "/api/capture/stop")
0 "/api/capture/stop") return api_capture_stop();` ional return api_capture_stop();
8 branc
h—
run
code
only
when

Page 230 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
conditi
on
true.
4 `` Blank Separator between code blocks.
0 line for
9 reada
bility.
4 ` // Static files` Comm Static files
1 ent
0 docum
enting
intent.
4 ` return serve_static(path);` Exit return serve_static(path);
1 functio
1 n and
give
back a
value.
4 `}` Brace C/C++ syntax structure.
1 or
2 parent
hesis
closin
g/ope
ning a
block.
4 `` Blank Separator between code blocks.
1 line for
3 reada
bility.
4 `// Comm ═════════════════════════════════
1 ═════════════════════════════════ ent ═════════════════════════════════
4 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
4 `// Static file serving` Comm Static file serving
1 ent
5 docum
enting
intent.
4 `// Comm ═════════════════════════════════
1 ═════════════════════════════════ ent ═════════════════════════════════
6 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
4 `` Blank Separator between code blocks.
1 line for
7 reada
bility.
4 `static std::string mime_type(const std::string& path) Name static std::string mime_type(const std::string& path) {
1 {` d
8 consta
nt —
value

Page 231 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
should
not
chang
e.
4 ` if ([Link]() > 3 && [Link]([Link]()-3) == Condit if ([Link]() > 3 && [Link]([Link]()-3) ==
1 ".js") return "application/javascript";` ional ".js") return "applicatio
9 branc
h—
run
code
only
when
conditi
on
true.
4 ` if ([Link]() > 4 && [Link]([Link]()-4) == Condit if ([Link]() > 4 && [Link]([Link]()-4) ==
2 ".css") return "text/css";` ional ".css") return "text/css";
0 branc
h—
run
code
only
when
conditi
on
true.
4 ` if ([Link]() > 4 && [Link]([Link]()-4) == Condit if ([Link]() > 4 && [Link]([Link]()-4) ==
2 ".svg") return "image/svg+xml";` ional ".svg") return "image/svg+
1 branc
h—
run
code
only
when
conditi
on
true.
4 ` if ([Link]() > 4 && [Link]([Link]()-5) == Condit if ([Link]() > 4 && [Link]([Link]()-5) ==
2 ".html") return "text/html";` ional ".html") return "text/html"
2 branc
h—
run
code
only
when
conditi
on
true.
4 ` if ([Link]() > 4 && [Link]([Link]()-4) == Condit if ([Link]() > 4 && [Link]([Link]()-4) ==
2 ".png") return "image/png";` ional ".png") return "image/png"
3 branc
h—
run
code
only
when
conditi

Page 232 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
on
true.
4 ` if ([Link]() > 4 && [Link]([Link]()-4) == Condit if ([Link]() > 4 && [Link]([Link]()-4) ==
2 ".jpg") return "image/jpeg";` ional ".jpg") return "image/jpeg
4 branc
h—
run
code
only
when
conditi
on
true.
4 ` return "text/plain";` Exit return "text/plain";
2 functio
5 n and
give
back a
value.
4 `}` Brace C/C++ syntax structure.
2 or
6 parent
hesis
closin
g/ope
ning a
block.
4 `` Blank Separator between code blocks.
2 line for
7 reada
bility.
4 `std::string HttpServer::serve_static(const std::string& Name std::string HttpServer::serve_static(const std::string&
2 url_path) {` d url_path) {
8 consta
nt —
value
should
not
chang
e.
4 ` if (static_dir_.empty())` Condit if (static_dir_.empty())
2 ional
9 branc
h—
run
code
only
when
conditi
on
true.
4 ` return make_http(404, "application/json", Exit return make_http(404, "application/json",
3 "{\"error\":\"Not found\"}");` functio "{\"error\":\"Not found\"}");
0 n and
give

Page 233 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
back a
value.
4 `` Blank Separator between code blocks.
3 line for
1 reada
bility.
4 ` std::string fpath = static_dir_ + "/";` Execu std::string fpath = static_dir_ + "/";
3 table
2 statem
ent.
4 ` // Strip query string` Comm Strip query string
3 ent
3 docum
enting
intent.
4 ` auto qpos = url_path.find('?');` Execu auto qpos = url_path.find('?');
3 table
4 statem
ent.
4 ` std::string clean = (qpos != std::string::npos) ? Execu std::string clean = (qpos != std::string::npos) ?
3 url_path.substr(0, qpos) : url_path;` table url_path.substr(0, qpos) : url_path;
5 statem
ent.
4 `` Blank Separator between code blocks.
3 line for
6 reada
bility.
4 ` // Map / to [Link]; for SPA, unmapped paths Comm Map / to [Link]; for SPA, unmapped paths also
3 also get [Link]` ent get [Link]
7 docum
enting
intent.
4 ` if (clean == "/" \ \ [Link]() \
3
8
4 ` ([Link]("/assets/") == std::string::npos &&` Sourc ([Link]("/assets/") == std::string::npos &&
3 e code
9 line.
4 ` [Link](".") == std::string::npos)) {` Sourc [Link](".") == std::string::npos)) {
4 e code
0 line.
4 ` fpath += "[Link]";` Execu fpath += "[Link]";
4 table
1 statem
ent.
4 ` } else {` Sourc } else {
4 e code
2 line.
4 ` // Remove leading slash` Comm Remove leading slash
4 ent
3 docum

Page 234 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
enting
intent.
4 ` fpath += (clean[0]=='/') ? [Link](1) : Execu fpath += (clean[0]=='/') ? [Link](1) : clean;
4 clean;` table
4 statem
ent.
4 ` }` Brace C/C++ syntax structure.
4 or
5 parent
hesis
closin
g/ope
ning a
block.
4 `` Blank Separator between code blocks.
4 line for
6 reada
bility.
4 ` std::ifstream f(fpath, std::ios::binary);` Execu std::ifstream f(fpath, std::ios::binary);
4 table
7 statem
ent.
4 ` if (!f.is_open()) {` Condit if (!f.is_open()) {
4 ional
8 branc
h—
run
code
only
when
conditi
on
true.
4 ` // SPA fallback` Comm SPA fallback
4 ent
9 docum
enting
intent.
4 ` std::ifstream idx(static_dir_ + "/[Link]", Execu std::ifstream idx(static_dir_ + "/[Link]",
5 std::ios::binary);` table std::ios::binary);
0 statem
ent.
4 ` if (idx.is_open()) {` Condit if (idx.is_open()) {
5 ional
1 branc
h—
run
code
only
when
conditi
on
true.

Page 235 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
4 ` std::string Execu std::string
5 content((std::istreambuf_iterator<char>(idx)), {});` table content((std::istreambuf_iterator<char>(idx)), {});
2 statem
ent.
4 ` return make_http(200, "text/html", content);` Exit return make_http(200, "text/html", content);
5 functio
3 n and
give
back a
value.
4 ` }` Brace C/C++ syntax structure.
5 or
4 parent
hesis
closin
g/ope
ning a
block.
4 ` return make_http(404, "text/plain", "Not Exit return make_http(404, "text/plain", "Not found");
5 found");` functio
5 n and
give
back a
value.
4 ` }` Brace C/C++ syntax structure.
5 or
6 parent
hesis
closin
g/ope
ning a
block.
4 ` std::string Execu std::string content((std::istreambuf_iterator<char>(f)),
5 content((std::istreambuf_iterator<char>(f)), {});` table {});
7 statem
ent.
4 ` return make_http(200, mime_type(fpath), Exit return make_http(200, mime_type(fpath), content);
5 content);` functio
8 n and
give
back a
value.
4 `}` Brace C/C++ syntax structure.
5 or
9 parent
hesis
closin
g/ope
ning a
block.
4 `` Blank Separator between code blocks.
6 line for
0 reada
bility.

Page 236 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
4 `std::string HttpServer::make_http(int code, const Name std::string HttpServer::make_http(int code, const
6 std::string& ctype, const std::string& body) {` d std::string& ctype, const std:
1 consta
nt —
value
should
not
chang
e.
4 ` std::string status_text = Execu std::string status_text =
6 (code==200)?"OK":(code==404)?"Not table (code==200)?"OK":(code==404)?"Not
2 Found":"Error";` statem Found":"Error";
ent.
4 ` std::ostringstream ss;` Execu std::ostringstream ss;
6 table
3 statem
ent.
4 ` ss << "HTTP/1.1 " << code << " " << status_text Sourc ss << "HTTP/1.1 " << code << " " << status_text <<
6 << "\r\n"` e code "\r\n"
4 line.
4 ` << "Content-Type: " << ctype << "\r\n"` Sourc << "Content-Type: " << ctype << "\r\n"
6 e code
5 line.
4 ` << "Content-Length: " << [Link]() << "\r\n"` Sourc << "Content-Length: " << [Link]() << "\r\n"
6 e code
6 line.
4 ` << "Access-Control-Allow-Origin: *\r\n"` Sourc << "Access-Control-Allow-Origin: *\r\n"
6 e code
7 line.
4 ` << "Cache-Control: no-cache\r\n"` Sourc << "Cache-Control: no-cache\r\n"
6 e code
8 line.
4 ` << "Connection: close\r\n\r\n"` Sourc << "Connection: close\r\n\r\n"
6 e code
9 line.
4 ` << body;` Execu << body;
7 table
0 statem
ent.
4 ` return [Link]();` Exit return [Link]();
7 functio
1 n and
give
back a
value.
4 `}` Brace C/C++ syntax structure.
7 or
2 parent
hesis
closin
g/ope
ning a
block.

Page 237 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
4 `` Blank Separator between code blocks.
7 line for
3 reada
bility.
4 `// Comm ═════════════════════════════════
7 ═════════════════════════════════ ent ═════════════════════════════════
4 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
4 `// API routes` Comm API routes
7 ent
5 docum
enting
intent.
4 `// Comm ═════════════════════════════════
7 ═════════════════════════════════ ent ═════════════════════════════════
6 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
4 `` Blank Separator between code blocks.
7 line for
7 reada
bility.
4 `std::string HttpServer::api_metrics() {` Sourc std::string HttpServer::api_metrics() {
7 e code
8 line.
4 ` if (!orch_ \ \ !orch_->config().metrics_enabled) {`
7
9
4 ` return make_http(404, "text/plain", "metrics Exit return make_http(404, "text/plain", "metrics
8 disabled\n");` functio disabled\n");
0 n and
give
back a
value.

Li Source Easy Technical Explanation


ne Explanat
ion
48 ` }` Brace or C/C++ syntax structure.
1 parenthes
is
closing/op
ening a
block.
48 ` return make_http(200, "text/plain; Exit return make_http(200, "text/plain; version=0.0.4",
2 version=0.0.4",` function
and give
back a
value.
48 ` MetricsRegistry::instance().render());` Executabl MetricsRegistry::instance().render());
3 e

Page 238 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
statement
.
48 `}` Brace or C/C++ syntax structure.
4 parenthes
is
closing/op
ening a
block.
48 `` Blank line Separator between code blocks.
5 for
readability
.
48 `std::string HttpServer::api_packets() {` Source std::string HttpServer::api_packets() {
6 code line.
48 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
7 mutex so
only one
thread
uses
shared
data at a
time.
48 ` std::string body = "{\"packets\":[";` Executabl std::string body = "{\"packets\":[";
8 e
statement
.
48 ` bool first = true;` Executabl bool first = true;
9 e
statement
.
49 ` for (auto& p : recent_pkts_) {` Loop over for (auto& p : recent_pkts_) {
0 items or
until
condition
changes.
49 ` if (!first) body += ",";` Condition if (!first) body += ",";
1 al branch
— run
code only
when
condition
true.
49 ` body += p;` Executabl body += p;
2 e
statement
.
49 ` first = false;` Executabl first = false;
3 e
statement
.
49 ` }` Brace or C/C++ syntax structure.
4 parenthes
is
closing/op

Page 239 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
ening a
block.
49 ` body += "]}";` Executabl body += "]}";
5 e
statement
.
49 ` return make_http(200, "application/json", Exit return make_http(200, "application/json", body);
6 body);` function
and give
back a
value.
49 `}` Brace or C/C++ syntax structure.
7 parenthes
is
closing/op
ening a
block.
49 `` Blank line Separator between code blocks.
8 for
readability
.
49 `std::string HttpServer::api_alerts() {` Source std::string HttpServer::api_alerts() {
9 code line.
50 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
0 mutex so
only one
thread
uses
shared
data at a
time.
50 ` std::string body = "[";` Executabl std::string body = "[";
1 e
statement
.
50 ` bool first = true;` Executabl bool first = true;
2 e
statement
.
50 ` for (auto& a : recent_alerts_) {` Loop over for (auto& a : recent_alerts_) {
3 items or
until
condition
changes.
50 ` if (!first) body += ",";` Condition if (!first) body += ",";
4 al branch
— run
code only
when
condition
true.
50 ` body += a;` Executabl body += a;
5 e
statement
.

Page 240 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
50 ` first = false;` Executabl first = false;
6 e
statement
.
50 ` }` Brace or C/C++ syntax structure.
7 parenthes
is
closing/op
ening a
block.
50 ` body += "]";` Executabl body += "]";
8 e
statement
.
50 ` return make_http(200, "application/json", Exit return make_http(200, "application/json", body);
9 body);` function
and give
back a
value.
51 `}` Brace or C/C++ syntax structure.
0 parenthes
is
closing/op
ening a
block.
51 `` Blank line Separator between code blocks.
1 for
readability
.
51 `std::string HttpServer::api_summary() {` Source std::string HttpServer::api_summary() {
2 code line.
51 ` if (!orch_) return make_http(200, Condition if (!orch_) return make_http(200, "application/json",
3 "application/json",` al branch
— run
code only
when
condition
true.
51 ` Executabl "{\"activeFlows\":0,\"alertsToday\":0,\"detectionRat
4 "{\"activeFlows\":0,\"alertsToday\":0,\"detectionRate e e\":0,\"topThreatIp\":\"\"}");
\":0,\"topThreatIp\":\"\"}");` statement
.
51 `` Blank line Separator between code blocks.
5 for
readability
.
51 ` // Access orchestrator's public stats` Comment Access orchestrator's public stats
6 documenti
ng intent.
51 ` uint64_t af = orch_->stats_active_flows();` Executabl uint64_t af = orch_->stats_active_flows();
7 e
statement
.

Page 241 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
51 ` uint64_t atot = orch_->stats_alerts_total();` Executabl uint64_t atot = orch_->stats_alerts_total();
8 e
statement
.
51 ` double pps = orch_->stats_pps();` Executabl double pps = orch_->stats_pps();
9 e
statement
.
52 ` std::string top_ip;` Executabl std::string top_ip;
0 e
statement
.
52 ` {` Brace or C/C++ syntax structure.
1 parenthes
is
closing/op
ening a
block.
52 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
2 mutex so
only one
thread
uses
shared
data at a
time.
52 ` int max_cnt = 0;` Executabl int max_cnt = 0;
3 e
statement
.
52 ` for (auto& [ip, e] : threat_ips_) {` Loop over for (auto& [ip, e] : threat_ips_) {
4 items or
until
condition
changes.
52 ` if ([Link] > max_cnt) { max_cnt = Condition if ([Link] > max_cnt) { max_cnt =
5 [Link]; top_ip = ip; }` al branch [Link]; top_ip = ip; }
— run
code only
when
condition
true.
52 ` }` Brace or C/C++ syntax structure.
6 parenthes
is
closing/op
ening a
block.
52 ` }` Brace or C/C++ syntax structure.
7 parenthes
is
closing/op
ening a
block.

Page 242 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
52 `` Blank line Separator between code blocks.
8 for
readability
.
52 ` // FIX: detection rate = alerts / Comment FIX: detection rate = alerts / max(completed_flows,
9 max(completed_flows, 1) capped at 1.0` documenti 1) capped at 1.0
ng intent.
53 ` // Old formula (0.85 + rand) was fabricated Comment Old formula (0.85 + rand) was fabricated and
0 and misleading.` documenti misleading.
ng intent.
53 ` uint64_t completed = orch_- Executabl uint64_t completed = orch_-
1 >stats_completed_flows();` e >stats_completed_flows();
statement
.
53 ` double det_rate = (completed > 0) ? Executabl double det_rate = (completed > 0) ? std::min(1.0,
2 std::min(1.0, (double)atot / (double)completed) : e (double)atot / (double)completed) : 0.0;
0.0;` statement
.
53 `` Blank line Separator between code blocks.
3 for
readability
.
53 ` std::ostringstream ss;` Executabl std::ostringstream ss;
4 e
statement
.
53 ` ss << "{\"activeFlows\":" << af` Source ss << "{\"activeFlows\":" << af
5 code line.
53 ` << ",\"alertsToday\":" << atot` Source << ",\"alertsToday\":" << atot
6 code line.
53 ` << ",\"detectionRate\":" << std::fixed << Source << ",\"detectionRate\":" << std::fixed <<
7 std::setprecision(2) << det_rate` code line. std::setprecision(2) << det_rate
53 ` << ",\"topThreatIp\":\"" << json_esc(top_ip) << Source << ",\"topThreatIp\":\"" << json_esc(top_ip) << "\""
8 "\""` code line.
53 ` << ",\"currentPps\":" << std::fixed << Source << ",\"currentPps\":" << std::fixed <<
9 std::setprecision(1) << pps` code line. std::setprecision(1) << pps
54 ` << "}";` Executabl << "}";
0 e
statement
.
54 ` return make_http(200, "application/json", Exit return make_http(200, "application/json", [Link]());
1 [Link]());` function
and give
back a
value.
54 `}` Brace or C/C++ syntax structure.
2 parenthes
is
closing/op
ening a
block.

Page 243 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
54 `` Blank line Separator between code blocks.
3 for
readability
.
54 `std::string HttpServer::api_flows() {` Source std::string HttpServer::api_flows() {
4 code line.
54 ` if (!orch_) return make_http(200, Condition if (!orch_) return make_http(200, "application/json",
5 "application/json", "[]");` al branch "[]");
— run
code only
when
condition
true.
54 `` Blank line Separator between code blocks.
6 for
readability
.
54 ` auto flows = orch_->get_flow_snapshot();` Executabl auto flows = orch_->get_flow_snapshot();
7 e
statement
.
54 ` std::string body = "[";` Executabl std::string body = "[";
8 e
statement
.
54 ` bool first = true;` Executabl bool first = true;
9 e
statement
.
55 ` int idx = 0;` Executabl int idx = 0;
0 e
statement
.
55 ` for (auto& f : flows) {` Loop over for (auto& f : flows) {
1 items or
until
condition
changes.
55 ` if (idx++ > 200) break; // cap at 200` Condition if (idx++ > 200) break; // cap at 200
2 al branch
— run
code only
when
condition
true.
55 ` if (!first) body += ",";` Condition if (!first) body += ",";
3 al branch
— run
code only
when
condition
true.
55 ` first = false;` Executabl first = false;
4 e

Page 244 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explanat
ion
statement
.
55 `` Blank line Separator between code blocks.
5 for
readability
.
55 ` std::string src_ip = format_ip([Link].src_ip);` Executabl std::string src_ip = format_ip([Link].src_ip);
6 e
statement
.
55 ` std::string dst_ip = format_ip([Link].dst_ip);` Executabl std::string dst_ip = format_ip([Link].dst_ip);
7 e
statement
.
55 ` double dur = (f.last_seen_us - Executabl double dur = (f.last_seen_us - f.first_seen_us) /
8 f.first_seen_us) / 1e6;` e 1e6;
statement
.
55 ` if (dur < 0) dur = 0;` Condition if (dur < 0) dur = 0;
9 al branch
— run
code only
when
condition
true.
56 `` Blank line Separator between code blocks.
0 for
readability
.

Line Source Easy Explanation Technical Explanation


561 ` // Simple threat score based on Comment Simple threat score based on flow
flow features` documenting intent. features
562 ` double score = 0.0;` Executable double score = 0.0;
statement.
563 ` if (f.syn_count > 50 && f.ack_count Conditional branch if (f.syn_count > 50 && f.ack_count <
< f.syn_count / 2) score += 40;` — run code only f.syn_count / 2) score += 40;
when condition true.
564 ` if (f.has_null_flags) score += 30;` Conditional branch if (f.has_null_flags) score += 30;
— run code only
when condition true.
565 ` if (f.has_xmas_flags) score += 30;` Conditional branch if (f.has_xmas_flags) score += 30;
— run code only
when condition true.
566 ` if ([Link] > 1000) score += 20;` Conditional branch if ([Link] > 1000) score += 20;
— run code only
when condition true.
567 ` score = std::min(score, 100.0);` Executable score = std::min(score, 100.0);
statement.
568 `` Blank line for Separator between code blocks.
readability.

Page 245 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


569 ` std::string status = "active";` Executable std::string status = "active";
statement.
570 ` if (score >= 80) status = Conditional branch if (score >= 80) status = "suspicious";
"suspicious";` — run code only
when condition true.
571 ` if (f.is_complete) status = Conditional branch if (f.is_complete) status = "closed";
"closed";` — run code only
when condition true.
572 `` Blank line for Separator between code blocks.
readability.
573 ` std::string proto_str;` Executable std::string proto_str;
statement.
574 ` if ([Link] == 6) proto_str Conditional branch if ([Link] == 6) proto_str =
= "TCP";` — run code only "TCP";
when condition true.
575 ` else if ([Link] == 17) Executable else if ([Link] == 17) proto_str =
proto_str = "UDP";` statement. "UDP";
576 ` else if ([Link] == 1) Executable else if ([Link] == 1) proto_str =
proto_str = "ICMP";` statement. "ICMP";
577 ` else proto_str = Executable else proto_str =
std::to_string([Link]);` statement. std::to_string([Link]);
578 `` Blank line for Separator between code blocks.
readability.
579 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
580 ` ss << "{"` Source code line. ss << "{"
581 ` << "\"id\":\"" << src_ip << "_" << Source code line. << "\"id\":\"" << src_ip << "_" <<
[Link].src_port << "_" << dst_ip << "_" << [Link].src_port << "_" << dst_ip << "_"
[Link].dst_port << "\","` << [Link].dst_port << "\","
582 ` << "\"srcAddr\":\"" << src_ip << Source code line. << "\"srcAddr\":\"" << src_ip << "\","
"\","`
583 ` << "\"srcPort\":" << [Link].src_port Source code line. << "\"srcPort\":" << [Link].src_port << ","
<< ","`
584 ` << "\"dstAddr\":\"" << dst_ip << Source code line. << "\"dstAddr\":\"" << dst_ip << "\","
"\","`
585 ` << "\"dstPort\":" << [Link].dst_port Source code line. << "\"dstPort\":" << [Link].dst_port << ","
<< ","`
586 ` << "\"protocol\":\"" << proto_str Source code line. << "\"protocol\":\"" << proto_str << "\","
<< "\","`
587 ` << "\"packets\":" << Source code line. << "\"packets\":" << f.packet_count <<
f.packet_count << ","` ","
588 ` << "\"bytes\":" << f.byte_count << Source code line. << "\"bytes\":" << f.byte_count << ","
","`
589 ` << "\"duration\":" << std::fixed << Source code line. << "\"duration\":" << std::fixed <<
std::setprecision(1) << dur << ","` std::setprecision(1) << dur << ","
590 ` << "\"threatScore\":" << (int)score Source code line. << "\"threatScore\":" << (int)score << ","
<< ","`
591 ` << "\"status\":\"" << status << "\""` Source code line. << "\"status\":\"" << status << "\""
592 ` << "}";` Executable << "}";
statement.

Page 246 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


593 ` body += [Link]();` Executable body += [Link]();
statement.
594 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
595 ` body += "]";` Executable body += "]";
statement.
596 ` return make_http(200, Exit function and return make_http(200,
"application/json", body);` give back a value. "application/json", body);
597 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
598 `` Blank line for Separator between code blocks.
readability.
599 `std::string Source code line. std::string
HttpServer::api_threat_timeline() {` HttpServer::api_threat_timeline() {
600 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(data_mtx_);` only one thread uses
shared data at a
time.
601 ` std::string body = "[";` Executable std::string body = "[";
statement.
602 ` bool first = true;` Executable bool first = true;
statement.
603 ` for (auto& b : timeline_) {` Loop over items or for (auto& b : timeline_) {
until condition
changes.
604 ` if (!first) body += ",";` Conditional branch if (!first) body += ",";
— run code only
when condition true.
605 ` first = false;` Executable first = false;
statement.
606 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
607 ` ss << "{\"time\":\"" << [Link] << Source code line. ss << "{\"time\":\"" << [Link] << "\","
"\","`
608 ` << "\"critical\":" << [Link] << Source code line. << "\"critical\":" << [Link] << ","
","`
609 ` << "\"high\":" << [Link] << ","` Source code line. << "\"high\":" << [Link] << ","
610 ` << "\"medium\":" << [Link] Source code line. << "\"medium\":" << [Link] << ","
<< ","`
611 ` << "\"low\":" << [Link] << "}";` Executable << "\"low\":" << [Link] << "}";
statement.
612 ` body += [Link]();` Executable body += [Link]();
statement.
613 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
614 ` body += "]";` Executable body += "]";
statement.

Page 247 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


615 ` return make_http(200, Exit function and return make_http(200,
"application/json", body);` give back a value. "application/json", body);
616 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
617 `` Blank line for Separator between code blocks.
readability.
618 `std::string HttpServer::api_threat_ips() {` Source code line. std::string HttpServer::api_threat_ips() {
619 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(data_mtx_);` only one thread uses
shared data at a
time.
620 ` std::string body = "[";` Executable std::string body = "[";
statement.
621 ` bool first = true;` Executable bool first = true;
statement.
622 ` for (auto& [ip, e] : threat_ips_) {` Loop over items or for (auto& [ip, e] : threat_ips_) {
until condition
changes.
623 ` if (!first) body += ",";` Conditional branch if (!first) body += ",";
— run code only
when condition true.
624 ` first = false;` Executable first = false;
statement.
625 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
626 ` ss << "{\"ip\":\"" << json_esc(ip) << Source code line. ss << "{\"ip\":\"" << json_esc(ip) << "\","
"\","`
627 ` << "\"country\":\"Unknown\","` Source code line. << "\"country\":\"Unknown\","
628 ` << "\"countryCode\":\"XX\","` Source code line. << "\"countryCode\":\"XX\","
629 ` << "\"alertCount\":" << Source code line. << "\"alertCount\":" << [Link] <<
[Link] << ","` ","
630 ` << "\"threatScore\":" << std::fixed Executable << "\"threatScore\":" << std::fixed <<
<< std::setprecision(2) << [Link] statement. std::setprecision(2) << [Link] <<
<< "}";` "}";
631 ` body += [Link]();` Executable body += [Link]();
statement.
632 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
633 ` body += "]";` Executable body += "]";
statement.
634 ` return make_http(200, Exit function and return make_http(200,
"application/json", body);` give back a value. "application/json", body);
635 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
636 `` Blank line for Separator between code blocks.
readability.

Page 248 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


637 `std::string Source code line. std::string
HttpServer::api_protocol_stats() {` HttpServer::api_protocol_stats() {
638 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lk(data_mtx_);` only one thread uses
shared data at a
time.
639 ` std::string body = "[";` Executable std::string body = "[";
statement.
640 ` bool first = true;` Executable bool first = true;
statement.

Line Source Easy Explanation Technical Explanation


641 ` for (auto& [proto, pkts] : proto_pkts_) Loop over items or for (auto& [proto, pkts] : proto_pkts_) {
{` until condition
changes.
642 ` if (!first) body += ",";` Conditional branch — if (!first) body += ",";
run code only when
condition true.
643 ` first = false;` Executable first = false;
statement.
644 ` auto bytes = Executable auto bytes = proto_bytes_.count(proto)
proto_bytes_.count(proto) ? statement. ? proto_bytes_.at(proto) : 0ULL;
proto_bytes_.at(proto) : 0ULL;`
645 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
646 ` ss << "{\"name\":\"" << Source code line. ss << "{\"name\":\"" << json_esc(proto)
json_esc(proto) << "\","` << "\","
647 ` << "\"packets\":" << pkts << ","` Source code line. << "\"packets\":" << pkts << ","
648 ` << "\"bytes\":" << bytes << "}";` Executable << "\"bytes\":" << bytes << "}";
statement.
649 ` body += [Link]();` Executable body += [Link]();
statement.
650 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
651 ` body += "]";` Executable body += "]";
statement.
652 ` return make_http(200, Exit function and give return make_http(200,
"application/json", body);` back a value. "application/json", body);
653 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
654 `` Blank line for Separator between code blocks.
readability.
655 `std::string Source code line. std::string
HttpServer::api_capture_start() {` HttpServer::api_capture_start() {
656 ` if (orch_) orch_->resume_capture();` Conditional branch — if (orch_) orch_->resume_capture();
run code only when
condition true.

Page 249 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


657 ` return make_http(200, Exit function and give return make_http(200,
"application/json", back a value. "application/json",
"{\"status\":\"capturing\"}");` "{\"status\":\"capturing\"}");
658 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
659 `` Blank line for Separator between code blocks.
readability.
660 `std::string Source code line. std::string
HttpServer::api_capture_stop() {` HttpServer::api_capture_stop() {
661 ` if (orch_) orch_->pause_capture();` Conditional branch — if (orch_) orch_->pause_capture();
run code only when
condition true.
662 ` return make_http(200, Exit function and give return make_http(200,
"application/json", back a value. "application/json",
"{\"status\":\"stopped\"}");` "{\"status\":\"stopped\"}");
663 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
664 `` Blank line for Separator between code blocks.
readability.
665 `std::string Source code line. std::string
HttpServer::api_capture_pause() {` HttpServer::api_capture_pause() {
666 ` if (orch_) orch_->pause_capture();` Conditional branch — if (orch_) orch_->pause_capture();
run code only when
condition true.
667 ` return make_http(200, Exit function and give return make_http(200,
"application/json", back a value. "application/json",
"{\"status\":\"paused\"}");` "{\"status\":\"paused\"}");
668 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
669 `` Blank line for Separator between code blocks.
readability.
670 `std::string Source code line. std::string
HttpServer::api_capture_resume() {` HttpServer::api_capture_resume() {
671 ` if (orch_) orch_->resume_capture();` Conditional branch — if (orch_) orch_->resume_capture();
run code only when
condition true.
672 ` return make_http(200, Exit function and give return make_http(200,
"application/json", back a value. "application/json",
"{\"status\":\"capturing\"}");` "{\"status\":\"capturing\"}");
673 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
674 `` Blank line for Separator between code blocks.
readability.
675 `std::string Source code line. std::string
HttpServer::api_capture_status() {` HttpServer::api_capture_status() {
676 ` std::string state = "idle";` Executable std::string state = "idle";
statement.

Page 250 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


677 ` double pps = 0, bps = 0;` Executable double pps = 0, bps = 0;
statement.
678 ` uint64_t total = 0;` Executable uint64_t total = 0;
statement.
679 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
680 ` std::lock_guard<std::mutex> Lock a mutex so only RAII mutex lock.
lk(data_mtx_);` one thread uses
shared data at a
time.
681 ` pps = cur_pps_;` Executable pps = cur_pps_;
statement.
682 ` bps = cur_bps_;` Executable bps = cur_bps_;
statement.
683 ` total = total_pkts_;` Executable total = total_pkts_;
statement.
684 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
685 ` if (orch_) {` Conditional branch — if (orch_) {
run code only when
condition true.
686 ` state = orch_->is_capturing() ? Executable state = orch_->is_capturing() ?
"capturing" : "stopped";` statement. "capturing" : "stopped";
687 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
688 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
689 ` ss << "{\"state\":\"" << state << "\","` Source code line. ss << "{\"state\":\"" << state << "\","
690 ` << "\"interface\":\"\","` Source code line. << "\"interface\":\"\","
691 ` << "\"packets\":" << total << ","` Source code line. << "\"packets\":" << total << ","
692 ` << "\"pps\":" << std::fixed << Source code line. << "\"pps\":" << std::fixed <<
std::setprecision(1) << pps << ","` std::setprecision(1) << pps << ","
693 ` << "\"bps\":" << std::fixed << Executable << "\"bps\":" << std::fixed <<
std::setprecision(0) << bps << "}";` statement. std::setprecision(0) << bps << "}";
694 ` return make_http(200, Exit function and give return make_http(200,
"application/json", [Link]());` back a value. "application/json", [Link]());
695 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
696 `` Blank line for Separator between code blocks.
readability.
697 `std::string HttpServer::api_interfaces() Source code line. std::string HttpServer::api_interfaces() {
{`
698 ` // Try to enumerate available network Comment Try to enumerate available network
interfaces` documenting intent. interfaces
699 ` std::string body = "[";` Executable std::string body = "[";
statement.

Page 251 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


700 ` bool first = true;` Executable bool first = true;
statement.
701 `#if defined(__linux__)` Comment if defined(__linux__)
documenting intent.
702 ` // Read /proc/net/dev for interface Comment Read /proc/net/dev for interface names
names` documenting intent.
703 ` std::ifstream f("/proc/net/dev");` Executable std::ifstream f("/proc/net/dev");
statement.
704 ` std::string line;` Executable std::string line;
statement.
705 ` std::getline(f, line); // skip header x2` Source code line. std::getline(f, line); // skip header x2
706 ` std::getline(f, line);` Executable std::getline(f, line);
statement.
707 ` while (std::getline(f, line)) {` Loop over items or while (std::getline(f, line)) {
until condition
changes.
708 ` auto pos = [Link](':');` Executable auto pos = [Link](':');
statement.
709 ` if (pos == std::string::npos) Conditional branch — if (pos == std::string::npos) continue;
continue;` run code only when
condition true.
710 ` std::string iface = [Link](0, Executable std::string iface = [Link](0, pos);
pos);` statement.
711 ` // trim spaces` Comment trim spaces
documenting intent.
712 ` [Link](0, Executable [Link](0, iface.find_first_not_of("
iface.find_first_not_of(" \t"));` statement. \t"));
713 ` [Link](iface.find_last_not_of(" Executable [Link](iface.find_last_not_of(" \t")
\t") + 1);` statement. + 1);
714 ` if ([Link]()) continue;` Conditional branch — if ([Link]()) continue;
run code only when
condition true.
715 ` if (!first) body += ",";` Conditional branch — if (!first) body += ",";
run code only when
condition true.
716 ` body += "\"" + json_esc(iface) + Executable body += "\"" + json_esc(iface) + "\"";
"\"";` statement.
717 ` first = false;` Executable first = false;
statement.
718 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
719 `#endif` Comment endif
documenting intent.
720 ` if (first) {` Conditional branch — if (first) {
run code only when
condition true.

Page 252 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 ` // Fallback list` Comm Fallback list
2 ent
1 docum
enting
intent.
7 ` body += "\"eth0\",\"lo\",\"any\"";` Execu body += "\"eth0\",\"lo\",\"any\"";
2 table
2 statem
ent.
7 ` }` Brace C/C++ syntax structure.
2 or
3 parent
hesis
closin
g/ope
ning a
block.
7 ` body += "]";` Execu body += "]";
2 table
4 statem
ent.
7 ` return make_http(200, "application/json", body);` Exit return make_http(200, "application/json", body);
2 functio
5 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
2 or
6 parent
hesis
closin
g/ope
ning a
block.
7 `` Blank Separator between code blocks.
2 line for
7 reada
bility.
7 `std::string HttpServer::api_config_get() {` Sourc std::string HttpServer::api_config_get() {
2 e code
8 line.
7 ` // Return current detector config snapshot` Comm Return current detector config snapshot
2 ent
9 docum
enting
intent.
7 ` std::ostringstream ss;` Execu std::ostringstream ss;
3 table
0 statem
ent.
7 ` ss << "{"` Sourc ss << "{"
3 e code
1 line.

Page 253 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 ` << "\"detectors\":["` Sourc << "\"detectors\":["
3 e code
2 line.
7 ` << "{\"name\":\"Port Sourc << "{\"name\":\"Port
3 Scanner\",\"enabled\":true,\"threshold\":15,\"descriptio e code Scanner\",\"enabled\":true,\"threshold\":15,\"descripti
3 n\":\"Detects sequential port acc...` line. on\":\"Detects sequentia
7 ` << "{\"name\":\"DDoS Sourc << "{\"name\":\"DDoS
3 Detector\",\"enabled\":true,\"threshold\":10000,\"descri e code Detector\",\"enabled\":true,\"threshold\":10000,\"descr
4 ption\":\"Volumetric packet rate ...` line. iption\":\"Volumetric pa
7 ` << "{\"name\":\"Brute Force Sourc << "{\"name\":\"Brute Force
3 Guard\",\"enabled\":true,\"threshold\":5,\"description\": e code Guard\",\"enabled\":true,\"threshold\":5,\"description\":
5 \"Repeated auth failures\...` line. \"Repeated auth
7 ` << "{\"name\":\"Data Exfil Sourc << "{\"name\":\"Data Exfil
3 Monitor\",\"enabled\":false,\"threshold\":1000000,\"des e code Monitor\",\"enabled\":false,\"threshold\":1000000,\"de
6 cription\":\"Large outbound ...` line. scription\":\"Large
7 ` << "{\"name\":\"C2 Sourc << "{\"name\":\"C2
3 Beacon\",\"enabled\":true,\"threshold\":60,\"descriptio e code Beacon\",\"enabled\":true,\"threshold\":60,\"descriptio
7 n\":\"Periodic connection patterns\"},"` line. n\":\"Periodic connection
7 ` << "{\"name\":\"Lateral Sourc << "{\"name\":\"Lateral
3 Movement\",\"enabled\":true,\"threshold\":20,\"descrip e code Movement\",\"enabled\":true,\"threshold\":20,\"descrip
8 tion\":\"Internal scan sweeps\"}"` line. tion\":\"Internal scan
7 ` << "],"` Sourc << "],"
3 e code
9 line.
7 ` << "\"baselinePackets\":" << total_pkts_ << ","` Sourc << "\"baselinePackets\":" << total_pkts_ << ","
4 e code
0 line.
7 ` << "\"baselineDays\":7,"` Sourc << "\"baselineDays\":7,"
4 e code
1 line.
7 ` << "\"interface\":\"\","` Sourc << "\"interface\":\"\","
4 e code
2 line.
7 ` << "\"captureFilter\":\"\""` Sourc << "\"captureFilter\":\"\""
4 e code
3 line.
7 ` << "}";` Execu << "}";
4 table
4 statem
ent.
7 ` return make_http(200, "application/json", [Link]());` Exit return make_http(200, "application/json", [Link]());
4 functio
5 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
4 or
6 parent
hesis
closin
g/ope

Page 254 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
ning a
block.
7 `` Blank Separator between code blocks.
4 line for
7 reada
bility.
7 `std::string HttpServer::api_config_save() {` Sourc std::string HttpServer::api_config_save() {
4 e code
8 line.
7 ` // Accept and acknowledge config — actual Comm Accept and acknowledge config — actual application
4 application happens at orchestrator level` ent happens at orchestrator level
9 docum
enting
intent.
7 ` return make_http(200, "application/json", Exit return make_http(200, "application/json",
5 "{\"status\":\"saved\"}");` functio "{\"status\":\"saved\"}");
0 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
5 or
1 parent
hesis
closin
g/ope
ning a
block.
7 `` Blank Separator between code blocks.
5 line for
2 reada
bility.
7 `std::string HttpServer::api_baseline_recalc() {` Sourc std::string HttpServer::api_baseline_recalc() {
5 e code
3 line.
7 ` // Trigger baseline recalculation in orchestrator if Comm Trigger baseline recalculation in orchestrator if
5 supported` ent supported
4 docum
enting
intent.
7 ` return make_http(200, "application/json", Exit return make_http(200, "application/json",
5 "{\"status\":\"recalculating\"}");` functio "{\"status\":\"recalculating\"}");
5 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
5 or
6 parent
hesis
closin
g/ope
ning a
block.

Page 255 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 `` Blank Separator between code blocks.
5 line for
7 reada
bility.
7 `std::string HttpServer::api_baseline_reset() {` Sourc std::string HttpServer::api_baseline_reset() {
5 e code
8 line.
7 ` return make_http(200, "application/json", Exit return make_http(200, "application/json",
5 "{\"status\":\"reset\"}");` functio "{\"status\":\"reset\"}");
9 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
6 or
0 parent
hesis
closin
g/ope
ning a
block.
7 `` Blank Separator between code blocks.
6 line for
1 reada
bility.
7 `std::string HttpServer::api_io_graph() {` Sourc std::string HttpServer::api_io_graph() {
6 e code
2 line.
7 ` // Return the last 60 seconds of I/O data` Comm Return the last 60 seconds of I/O data
6 ent
3 docum
enting
intent.
7 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
6 mutex
4 so
only
one
thread
uses
share
d data
at a
time.
7 ` std::string body = "[";` Execu std::string body = "[";
6 table
5 statem
ent.
7 ` bool first = true;` Execu bool first = true;
6 table
6 statem
ent.

Page 256 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 ` for (auto& pt : io_graph_) {` Loop for (auto& pt : io_graph_) {
6 over
7 items
or until
conditi
on
chang
es.
7 ` if (!first) body += ",";` Condit if (!first) body += ",";
6 ional
8 branc
h—
run
code
only
when
conditi
on
true.
7 ` first = false;` Execu first = false;
6 table
9 statem
ent.
7 ` std::ostringstream ss;` Execu std::ostringstream ss;
7 table
0 statem
ent.
7 ` ss << "{\"time\":\"" << json_esc([Link]) << "\","` Sourc ss << "{\"time\":\"" << json_esc([Link]) << "\","
7 e code
1 line.
7 ` << "\"in\":" << pt.bytes_in << ","` Sourc << "\"in\":" << pt.bytes_in << ","
7 e code
2 line.
7 ` << "\"out\":" << pt.bytes_out << "}";` Execu << "\"out\":" << pt.bytes_out << "}";
7 table
3 statem
ent.
7 ` body += [Link]();` Execu body += [Link]();
7 table
4 statem
ent.
7 ` }` Brace C/C++ syntax structure.
7 or
5 parent
hesis
closin
g/ope
ning a
block.
7 ` body += "]";` Execu body += "]";
7 table
6 statem
ent.

Page 257 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 ` return make_http(200, "application/json", body);` Exit return make_http(200, "application/json", body);
7 functio
7 n and
give
back a
value.
7 `}` Brace C/C++ syntax structure.
7 or
8 parent
hesis
closin
g/ope
ning a
block.
7 `` Blank Separator between code blocks.
7 line for
9 reada
bility.
7 `// Comm ═════════════════════════════════
8 ═════════════════════════════════ ent ═════════════════════════════════
0 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
7 `// Push from orchestrator` Comm Push from orchestrator
8 ent
1 docum
enting
intent.
7 `// Comm ═════════════════════════════════
8 ═════════════════════════════════ ent ═════════════════════════════════
2 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
7 `` Blank Separator between code blocks.
8 line for
3 reada
bility.
7 `void HttpServer::push_packet(const PacketInfo& pkt) Name void HttpServer::push_packet(const PacketInfo& pkt)
8 {` d {
4 consta
nt —
value
should
not
chang
e.
7 ` uint64_t no = ++pkt_counter_;` Execu uint64_t no = ++pkt_counter_;
8 table
5 statem
ent.
7 ` std::string json = build_packet_json(pkt, no);` Execu std::string json = build_packet_json(pkt, no);
8 table
6 statem
ent.

Page 258 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 `` Blank Separator between code blocks.
8 line for
7 reada
bility.
7 ` {` Brace C/C++ syntax structure.
8 or
8 parent
hesis
closin
g/ope
ning a
block.
7 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
8 mutex
9 so
only
one
thread
uses
share
d data
at a
time.
7 ` // Protocol stats` Comm Protocol stats
9 ent
0 docum
enting
intent.
7 ` std::string proto = proto_name([Link]);` Execu std::string proto = proto_name([Link]);
9 table
1 statem
ent.
7 ` proto_pkts_[proto]++;` Execu proto_pkts_[proto]++;
9 table
2 statem
ent.
7 ` proto_bytes_[proto] += [Link];` Execu proto_bytes_[proto] += [Link];
9 table
3 statem
ent.
7 `` Blank Separator between code blocks.
9 line for
4 reada
bility.
7 ` recent_pkts_.push_back(json);` Execu recent_pkts_.push_back(json);
9 table
5 statem
ent.
7 ` if (recent_pkts_.size() > MAX_PKTS) Condit if (recent_pkts_.size() > MAX_PKTS)
9 recent_pkts_.pop_front();` ional recent_pkts_.pop_front();
6 branc
h—
run
code
only

Page 259 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
when
conditi
on
true.
7 ` }` Brace C/C++ syntax structure.
9 or
7 parent
hesis
closin
g/ope
ning a
block.
7 `` Blank Separator between code blocks.
9 line for
8 reada
bility.
7 ` ws_broadcast("{\"type\":\"packet\",\"payload\":" + Execu ws_broadcast("{\"type\":\"packet\",\"payload\":" + json
9 json + "}");` table + "}");
9 statem
ent.
8 `}` Brace C/C++ syntax structure.
0 or
0 parent
hesis
closin
g/ope
ning a
block.

Li Source Easy Technical Explanation


n Expla
e natio
n
8 `` Blank Separator between code blocks.
0 line for
1 reada
bility.
8 `void HttpServer::push_alert(const AnomalyEvent& Final Enterprise alert struct.
0 ev) {` alert
2 record
sent to
logs
and
UI.
8 ` std::string json = build_alert_json(ev);` Execu std::string json = build_alert_json(ev);
0 table
3 statem
ent.
8 `` Blank Separator between code blocks.
0 line for
4 reada
bility.

Page 260 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` {` Brace C/C++ syntax structure.
0 or
5 parent
hesis
closin
g/ope
ning a
block.
8 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
0 mutex
6 so
only
one
thread
uses
share
d data
at a
time.
8 ` recent_alerts_.push_back(json);` Execu recent_alerts_.push_back(json);
0 table
7 statem
ent.
8 ` if (recent_alerts_.size() > MAX_ALERTS) Condit if (recent_alerts_.size() > MAX_ALERTS)
0 recent_alerts_.pop_front();` ional recent_alerts_.pop_front();
8 branc
h—
run
code
only
when
conditi
on
true.
8 `` Blank Separator between code blocks.
0 line for
9 reada
bility.
8 ` // Update threat IPs` Comm Update threat IPs
1 ent
0 docum
enting
intent.
8 ` std::string src = format_ip(ev.src_ip);` Execu std::string src = format_ip(ev.src_ip);
1 table
1 statem
ent.
8 ` auto& te = threat_ips_[src];` Execu auto& te = threat_ips_[src];
1 table
2 statem
ent.
8 ` [Link] = src;` Execu [Link] = src;
1 table
3 statem
ent.

Page 261 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` [Link]++;` Execu [Link]++;
1 table
4 statem
ent.
8 ` [Link] = std::max([Link], Execu [Link] = std::max([Link],
1 ev.final_score);` table ev.final_score);
5 statem
ent.
8 `` Blank Separator between code blocks.
1 line for
6 reada
bility.
8 ` // Update timeline` Comm Update timeline
1 ent
7 docum
enting
intent.
8 ` update_timeline_bucket(ev);` Execu update_timeline_bucket(ev);
1 table
8 statem
ent.
8 ` }` Brace C/C++ syntax structure.
1 or
9 parent
hesis
closin
g/ope
ning a
block.
8 `` Blank Separator between code blocks.
2 line for
0 reada
bility.
8 ` ws_broadcast("{\"type\":\"nads_alert\",\"payload\":" Execu ws_broadcast("{\"type\":\"nads_alert\",\"payload\":" +
2 + json + "}");` table json + "}");
1 statem
ent.
8 `}` Brace C/C++ syntax structure.
2 or
2 parent
hesis
closin
g/ope
ning a
block.
8 `` Blank Separator between code blocks.
2 line for
3 reada
bility.
8 `void HttpServer::push_stats(double pps, double bps, Sourc void HttpServer::push_stats(double pps, double bps,
2 uint64_t total) {` e code uint64_t total) {
4 line.

Page 262 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` {` Brace C/C++ syntax structure.
2 or
5 parent
hesis
closin
g/ope
ning a
block.
8 ` std::lock_guard<std::mutex> lk(data_mtx_);` Lock a RAII mutex lock.
2 mutex
6 so
only
one
thread
uses
share
d data
at a
time.
8 ` cur_pps_ = pps; cur_bps_ = bps; total_pkts_ = Execu cur_pps_ = pps; cur_bps_ = bps; total_pkts_ = total;
2 total;` table
7 statem
ent.
8 `` Blank Separator between code blocks.
2 line for
8 reada
bility.
8 ` // Update rolling I/O graph (one bucket per Comm Update rolling I/O graph (one bucket per second)
2 second)` ent
9 docum
enting
intent.
8 ` auto now_us = Sourc auto now_us =
3 std::chrono::duration_cast<std::chrono::microseconds e code std::chrono::duration_cast<std::chrono::microsecond
0 >(` line. s>(
8 ` Execu std::chrono::steady_clock::now().time_since_epoch()
3 std::chrono::steady_clock::now().time_since_epoch()) table ).count();
1 .count();` statem
ent.
8 ` if (now_us - last_io_bucket_us_ >= 1000000LL) Condit if (now_us - last_io_bucket_us_ >= 1000000LL) {
3 {` ional
2 branc
h—
run
code
only
when
conditi
on
true.
8 ` last_io_bucket_us_ = now_us;` Execu last_io_bucket_us_ = now_us;
3 table
3 statem
ent.

Page 263 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` auto tt = std::time(nullptr);` Execu auto tt = std::time(nullptr);
3 table
4 statem
ent.
8 ` char tbuf[10];` Execu char tbuf[10];
3 table
5 statem
ent.
8 ` struct tm ltm;` Execu struct tm ltm;
3 table
6 statem
ent.
8 ` localtime_r(&tt, &ltm);` Execu localtime_r(&tt, &ltm);
3 table
7 statem
ent.
8 ` std::strftime(tbuf, sizeof(tbuf), "%H:%M:%S", Execu std::strftime(tbuf, sizeof(tbuf), "%H:%M:%S", &ltm);
3 &ltm);` table
8 statem
ent.
8 ` IoPoint pt;` Execu IoPoint pt;
3 table
9 statem
ent.
8 ` [Link] = tbuf;` Execu [Link] = tbuf;
4 table
0 statem
ent.
8 ` pt.bytes_in = static_cast<uint64_t>(bps * 0.6 Execu pt.bytes_in = static_cast<uint64_t>(bps * 0.6 / 8.0);
4 / 8.0);` table
1 statem
ent.
8 ` pt.bytes_out = static_cast<uint64_t>(bps * Execu pt.bytes_out = static_cast<uint64_t>(bps * 0.4 / 8.0);
4 0.4 / 8.0);` table
2 statem
ent.
8 ` io_graph_.push_back(pt);` Execu io_graph_.push_back(pt);
4 table
3 statem
ent.
8 ` if (io_graph_.size() > 60) Condit if (io_graph_.size() > 60) io_graph_.pop_front();
4 io_graph_.pop_front();` ional
4 branc
h—
run
code
only
when
conditi
on
true.

Page 264 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` }` Brace C/C++ syntax structure.
4 or
5 parent
hesis
closin
g/ope
ning a
block.
8 ` }` Brace C/C++ syntax structure.
4 or
6 parent
hesis
closin
g/ope
ning a
block.
8 ` std::ostringstream ss;` Execu std::ostringstream ss;
4 table
7 statem
ent.
8 ` ss << "{\"type\":\"stats\",\"payload\":{"` Sourc ss << "{\"type\":\"stats\",\"payload\":{"
4 e code
8 line.
8 ` << "\"pps\":" << std::fixed << std::setprecision(1) Sourc << "\"pps\":" << std::fixed << std::setprecision(1) <<
4 << pps << ","` e code pps << ","
9 line.
8 ` << "\"bps\":" << std::fixed << std::setprecision(0) Sourc << "\"bps\":" << std::fixed << std::setprecision(0) <<
5 << bps << ","` e code bps << ","
0 line.
8 ` << "\"totalPackets\":" << total << "}}";` Execu << "\"totalPackets\":" << total << "}}";
5 table
1 statem
ent.
8 ` ws_broadcast([Link]());` Execu ws_broadcast([Link]());
5 table
2 statem
ent.
8 `}` Brace C/C++ syntax structure.
5 or
3 parent
hesis
closin
g/ope
ning a
block.
8 `` Blank Separator between code blocks.
5 line for
4 reada
bility.
8 `// Comm ═════════════════════════════════
5 ═════════════════════════════════ ent ═════════════════════════════════
5 ═════════════════════════════════ docum ══════════
══════════` enting
intent.

Page 265 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 `// JSON builders` Comm JSON builders
5 ent
6 docum
enting
intent.
8 `// Comm ═════════════════════════════════
5 ═════════════════════════════════ ent ═════════════════════════════════
7 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
8 `` Blank Separator between code blocks.
5 line for
8 reada
bility.
8 `std::string HttpServer::build_packet_json(const Name std::string HttpServer::build_packet_json(const
5 PacketInfo& pkt, uint64_t no) {` d PacketInfo& pkt, uint64_t no) {
9 consta
nt —
value
should
not
chang
e.
8 ` std::string src = format_ip(pkt.src_ip);` Execu std::string src = format_ip(pkt.src_ip);
6 table
0 statem
ent.
8 ` std::string dst = format_ip(pkt.dst_ip);` Execu std::string dst = format_ip(pkt.dst_ip);
6 table
1 statem
ent.
8 ` std::string ts = iso_now(pkt.timestamp_us);` Execu std::string ts = iso_now(pkt.timestamp_us);
6 table
2 statem
ent.
8 ` std::string pname = proto_name([Link]);` Execu std::string pname = proto_name([Link]);
6 table
3 statem
ent.
8 `` Blank Separator between code blocks.
6 line for
4 reada
bility.
8 ` // Build info string` Comm Build info string
6 ent
5 docum
enting
intent.
8 ` std::string info;` Execu std::string info;
6 table
6 statem
ent.

Page 266 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` if ([Link] == 6) info = "TCP " + Condit if ([Link] == 6) info = "TCP " +
6 src+":"+std::to_string(pkt.src_port) + " > " + ional src+":"+std::to_string(pkt.src_port
7 dst+":"+std::to_strin...` branc
h—
run
code
only
when
conditi
on
true.
8 ` else if ([Link] == 17) info = "UDP " + Execu else if ([Link] == 17) info = "UDP " +
6 src+":"+std::to_string(pkt.src_port) + " > " + table src+":"+std::to_string(pkt.src_port) + " > " + dst+":"+
8 dst+":"+std::to_strin...` statem
ent.
8 ` else if ([Link] == 1) info = "ICMP " + src + " Execu else if ([Link] == 1) info = "ICMP " + src + " > "
6 > " + dst;` table + dst;
9 statem
ent.
8 ` else info = pname + " " + src + " > Execu else info = pname + " " + src + " > " +
7 " + dst;` table dst;
0 statem
ent.
8 `` Blank Separator between code blocks.
7 line for
1 reada
bility.
8 ` // Build layers` Comm Build layers
7 ent
2 docum
enting
intent.
8 ` std::string layers = "[{\"name\":\"Internet Sourc std::string layers = "[{\"name\":\"Internet
7 Protocol\",\"fields\":["` e code Protocol\",\"fields\":["
3 line.
8 ` "{\"name\":\"Source\",\"value\":\"" + src + "\"},"` Sourc "{\"name\":\"Source\",\"value\":\"" + src + "\"},"
7 e code
4 line.
8 ` "{\"name\":\"Destination\",\"value\":\"" + dst + Sourc "{\"name\":\"Destination\",\"value\":\"" + dst + "\"},"
7 "\"},"` e code
5 line.
8 ` "{\"name\":\"Protocol\",\"value\":\"" + pname + Sourc "{\"name\":\"Protocol\",\"value\":\"" + pname + "\"},"
7 "\"},"` e code
6 line.
8 ` "{\"name\":\"Length\",\"value\":\"" + Sourc "{\"name\":\"Length\",\"value\":\"" +
7 std::to_string([Link]) + " bytes\"}"` e code std::to_string([Link]) + " bytes\"}"
7 line.
8 ` "]}";` Execu "]}";
7 table
8 statem
ent.

Page 267 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 `` Blank Separator between code blocks.
7 line for
9 reada
bility.
8 ` if ([Link] == 6 \ \ [Link] == 17) {`
8
0

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` layers += ",{\"name\":\"" + pname + Sourc layers += ",{\"name\":\"" + pname + "\",\"fields\":["
8 "\",\"fields\":["` e code
1 line.
8 ` "{\"name\":\"Source Port\",\"value\":\"" + Sourc "{\"name\":\"Source Port\",\"value\":\"" +
8 std::to_string(pkt.src_port) + "\"},"` e code std::to_string(pkt.src_port) + "\"},"
2 line.
8 ` "{\"name\":\"Destination Port\",\"value\":\"" + Sourc "{\"name\":\"Destination Port\",\"value\":\"" +
8 std::to_string(pkt.dst_port) + "\"},"` e code std::to_string(pkt.dst_port) + "\"},"
3 line.
8 ` "{\"name\":\"Payload Size\",\"value\":\"" + Sourc "{\"name\":\"Payload Size\",\"value\":\"" +
8 std::to_string(pkt.payload_size) + " bytes\"}"` e code std::to_string(pkt.payload_size) + " bytes\"}"
4 line.
8 ` "]}";` Execu "]}";
8 table
5 statem
ent.
8 ` }` Brace C/C++ syntax structure.
8 or
6 parent
hesis
closin
g/ope
ning a
block.
8 ` layers += "]";` Execu layers += "]";
8 table
7 statem
ent.
8 `` Blank Separator between code blocks.
8 line for
8 reada
bility.
8 ` std::ostringstream ss;` Execu std::ostringstream ss;
8 table
9 statem
ent.
8 ` ss << "{"` Sourc ss << "{"
9 e code
0 line.

Page 268 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
8 ` << "\"no\":" << no << ","` Sourc << "\"no\":" << no << ","
9 e code
1 line.
8 ` << "\"time\":\"" << ts << "\","` Sourc << "\"time\":\"" << ts << "\","
9 e code
2 line.
8 ` << "\"src\":\"" << src << "\","` Sourc << "\"src\":\"" << src << "\","
9 e code
3 line.
8 ` << "\"dst\":\"" << dst << "\","` Sourc << "\"dst\":\"" << dst << "\","
9 e code
4 line.
8 ` << "\"protocol\":\"" << pname << "\","` Sourc << "\"protocol\":\"" << pname << "\","
9 e code
5 line.
8 ` << "\"length\":" << [Link] << ","` Sourc << "\"length\":" << [Link] << ","
9 e code
6 line.
8 ` << "\"info\":\"" << json_esc(info) << "\","` Sourc << "\"info\":\"" << json_esc(info) << "\","
9 e code
7 line.
8 ` << "\"layers\":" << layers` Sourc << "\"layers\":" << layers
9 e code
8 line.
8 ` << "}";` Execu << "}";
9 table
9 statem
ent.
9 ` return [Link]();` Exit return [Link]();
0 functio
0 n and
give
back a
value.
9 `}` Brace C/C++ syntax structure.
0 or
1 parent
hesis
closin
g/ope
ning a
block.
9 `` Blank Separator between code blocks.
0 line for
2 reada
bility.
9 `std::string HttpServer::build_alert_json(const Final Enterprise alert struct.
0 AnomalyEvent& ev) {` alert
3 record
sent to
logs
and
UI.

Page 269 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
9 ` std::string sev;` Execu std::string sev;
0 table
4 statem
ent.
9 ` switch ([Link]) {` Sourc switch ([Link]) {
0 e code
5 line.
9 ` case Severity::CRITICAL: sev="critical"; break;` Execu case Severity::CRITICAL: sev="critical"; break;
0 table
6 statem
ent.
9 ` case Severity::HIGH: sev="high"; break;` Execu case Severity::HIGH: sev="high"; break;
0 table
7 statem
ent.
9 ` case Severity::MEDIUM: sev="medium"; Execu case Severity::MEDIUM: sev="medium"; break;
0 break;` table
8 statem
ent.
9 ` case Severity::LOW: sev="low"; break;` Execu case Severity::LOW: sev="low"; break;
0 table
9 statem
ent.
9 ` default: sev="low"; break;` Execu default: sev="low"; break;
1 table
0 statem
ent.
9 ` }` Brace C/C++ syntax structure.
1 or
1 parent
hesis
closin
g/ope
ning a
block.
9 `` Blank Separator between code blocks.
1 line for
2 reada
bility.
9 ` std::string src = format_ip(ev.src_ip);` Execu std::string src = format_ip(ev.src_ip);
1 table
3 statem
ent.
9 ` std::string dst = format_ip(ev.dst_ip);` Execu std::string dst = format_ip(ev.dst_ip);
1 table
4 statem
ent.
9 ` std::string ts = iso_now(ev.timestamp_us);` Execu std::string ts = iso_now(ev.timestamp_us);
1 table
5 statem
ent.

Page 270 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
9 ` std::string id = src + "_" + dst + "_" + Execu std::string id = src + "_" + dst + "_" +
1 std::to_string(ev.timestamp_us);` table std::to_string(ev.timestamp_us);
6 statem
ent.
9 `` Blank Separator between code blocks.
1 line for
7 reada
bility.
9 ` std::ostringstream ss;` Execu std::ostringstream ss;
1 table
8 statem
ent.
9 ` ss << "{"` Sourc ss << "{"
1 e code
9 line.
9 ` << "\"id\":\"" << json_esc(id) << "\","` Sourc << "\"id\":\"" << json_esc(id) << "\","
2 e code
0 line.
9 ` << "\"severity\":\"" << sev << "\","` Sourc << "\"severity\":\"" << sev << "\","
2 e code
1 line.
9 ` << "\"category\":\"" << json_esc(ev.attack_type) Sourc << "\"category\":\"" << json_esc(ev.attack_type) <<
2 << "\","` e code "\","
2 line.
9 ` << "\"timestamp\":\"" << ts << "\","` Sourc << "\"timestamp\":\"" << ts << "\","
2 e code
3 line.
9 ` << "\"detector\":\"NADS\","` Sourc << "\"detector\":\"NADS\","
2 e code
4 line.
9 ` << "\"srcAddr\":\"" << src << "\","` Sourc << "\"srcAddr\":\"" << src << "\","
2 e code
5 line.
9 ` << "\"dstAddr\":\"" << dst << "\","` Sourc << "\"dstAddr\":\"" << dst << "\","
2 e code
6 line.
9 ` << "\"description\":\"" << Sourc << "\"description\":\"" << json_esc([Link]) <<
2 json_esc([Link]) << "\","` e code "\","
7 line.
9 ` << "\"confidence\":" << std::fixed << Sourc << "\"confidence\":" << std::fixed <<
2 std::setprecision(0) << ([Link] * 100) << ","` e code std::setprecision(0) << ([Link] * 100) << ","
8 line.
9 ` << "\"finalScore\":" << std::fixed << Sourc << "\"finalScore\":" << std::fixed <<
2 std::setprecision(3) << ev.final_score << ","` e code std::setprecision(3) << ev.final_score << ","
9 line.
9 ` << "\"correlationId\":\"" << Sourc << "\"correlationId\":\"" << json_esc(ev.correlation_id)
3 json_esc(ev.correlation_id) << "\","` e code << "\","
0 line.
9 ` << "\"flowSummary\":\"" << Sourc << "\"flowSummary\":\"" <<
3 json_esc(ev.flow_summary) << "\","` e code json_esc(ev.flow_summary) << "\","
1 line.

Page 271 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
9 ` << "\"acknowledged\":false"` Sourc << "\"acknowledged\":false"
3 e code
2 line.
9 ` << "}";` Execu << "}";
3 table
3 statem
ent.
9 ` return [Link]();` Exit return [Link]();
3 functio
4 n and
give
back a
value.
9 `}` Brace C/C++ syntax structure.
3 or
5 parent
hesis
closin
g/ope
ning a
block.
9 `` Blank Separator between code blocks.
3 line for
6 reada
bility.
9 `// Comm ═════════════════════════════════
3 ═════════════════════════════════ ent ═════════════════════════════════
7 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
9 `// Helpers` Comm Helpers
3 ent
8 docum
enting
intent.
9 `// Comm ═════════════════════════════════
3 ═════════════════════════════════ ent ═════════════════════════════════
9 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
9 `` Blank Separator between code blocks.
4 line for
0 reada
bility.
9 `std::string HttpServer::proto_name(uint8_t proto) Name std::string HttpServer::proto_name(uint8_t proto)
4 const {` d const {
1 consta
nt —
value
should
not
chang
e.

Page 272 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
9 ` switch (proto) {` Sourc switch (proto) {
4 e code
2 line.
9 ` case 1: return "ICMP";` Execu case 1: return "ICMP";
4 table
3 statem
ent.
9 ` case 6: return "TCP";` Execu case 6: return "TCP";
4 table
4 statem
ent.
9 ` case 17: return "UDP";` Execu case 17: return "UDP";
4 table
5 statem
ent.
9 ` case 47: return "GRE";` Execu case 47: return "GRE";
4 table
6 statem
ent.
9 ` case 58: return "ICMPv6";` Execu case 58: return "ICMPv6";
4 table
7 statem
ent.
9 ` default: return "IP(" + std::to_string(proto) + ")";` Execu default: return "IP(" + std::to_string(proto) + ")";
4 table
8 statem
ent.
9 ` }` Brace C/C++ syntax structure.
4 or
9 parent
hesis
closin
g/ope
ning a
block.
9 `}` Brace C/C++ syntax structure.
5 or
0 parent
hesis
closin
g/ope
ning a
block.
9 `` Blank Separator between code blocks.
5 line for
1 reada
bility.
9 `std::string HttpServer::format_ip(uint32_t ip) const {` Name std::string HttpServer::format_ip(uint32_t ip) const {
5 d
2 consta
nt —
value
should
not

Page 273 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
chang
e.
9 ` struct in_addr a; a.s_addr = htonl(ip);` Execu struct in_addr a; a.s_addr = htonl(ip);
5 table
3 statem
ent.
9 ` return inet_ntoa(a);` Exit return inet_ntoa(a);
5 functio
4 n and
give
back a
value.
9 `}` Brace C/C++ syntax structure.
5 or
5 parent
hesis
closin
g/ope
ning a
block.
9 `` Blank Separator between code blocks.
5 line for
6 reada
bility.
9 `std::string HttpServer::iso_now(int64_t wall_us) Name std::string HttpServer::iso_now(int64_t wall_us) const
5 const {` d {
7 consta
nt —
value
should
not
chang
e.
9 ` time_t t = wall_us / 1000000;` Execu time_t t = wall_us / 1000000;
5 table
8 statem
ent.
9 ` struct tm tm_buf;` Execu struct tm tm_buf;
5 table
9 statem
ent.
9 ` gmtime_r(&t, &tm_buf);` Execu gmtime_r(&t, &tm_buf);
6 table
0 statem
ent.

Line Source Easy Technical Explanation


Explanation
961 ` char buf[32];` Executable char buf[32];
statement.
962 ` strftime(buf, sizeof(buf), "%Y-%m- Executable strftime(buf, sizeof(buf), "%Y-
%dT%H:%M:%SZ", &tm_buf);` statement. %m-%dT%H:%M:%SZ",
&tm_buf);

Page 274 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
963 ` return buf;` Exit function and return buf;
give back a value.
964 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
965 `` Blank line for Separator between code blocks.
readability.
966 `void HttpServer::update_timeline_bucket(const Final alert record Enterprise alert struct.
AnomalyEvent& ev) {` sent to logs and UI.
967 ` // 1-minute buckets` Comment 1-minute buckets
documenting intent.
968 ` int64_t bucket_us = (ev.timestamp_us / Executable int64_t bucket_us =
(60LL * 1000000LL)) * (60LL * 1000000LL);` statement. (ev.timestamp_us / (60LL *
1000000LL)) * (60LL *
1000000LL);
969 ` if (bucket_us != last_bucket_us_) {` Conditional branch if (bucket_us != last_bucket_us_)
— run code only {
when condition true.
970 ` TimelineBucket b;` Executable TimelineBucket b;
statement.
971 ` [Link] = iso_now(bucket_us);` Executable [Link] = iso_now(bucket_us);
statement.
972 ` timeline_.push_back(b);` Executable timeline_.push_back(b);
statement.
973 ` if (timeline_.size() > 20) Conditional branch if (timeline_.size() > 20)
timeline_.pop_front();` — run code only timeline_.pop_front();
when condition true.
974 ` last_bucket_us_ = bucket_us;` Executable last_bucket_us_ = bucket_us;
statement.
975 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
976 ` auto& bk = timeline_.back();` Executable auto& bk = timeline_.back();
statement.
977 ` switch ([Link]) {` Source code line. switch ([Link]) {
978 ` case Severity::CRITICAL: [Link]++; Executable case Severity::CRITICAL:
break;` statement. [Link]++; break;
979 ` case Severity::HIGH: [Link]++; Executable case Severity::HIGH:
break;` statement. [Link]++; break;
980 ` case Severity::MEDIUM: [Link]++; Executable case Severity::MEDIUM:
break;` statement. [Link]++; break;
981 ` default: [Link]++; break;` Executable default: [Link]++;
statement. break;
982 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 275 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
983 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
984 `` Blank line for Separator between code blocks.
readability.
985 `std::string HttpServer::json_esc(const Named constant — std::string
std::string& s) {` value should not HttpServer::json_esc(const
change. std::string& s) {
986 ` std::string out;` Executable std::string out;
statement.
987 ` [Link]([Link]() + 4);` Executable [Link]([Link]() + 4);
statement.
988 ` for (unsigned char c : s) {` Loop over items or for (unsigned char c : s) {
until condition
changes.
989 ` switch (c) {` Source code line. switch (c) {
990 ` case '"': out += "\\\""; break;` Executable case '"': out += "\\\""; break;
statement.
991 ` case '\\': out += "\\\\"; break;` Executable case '\\': out += "\\\\"; break;
statement.
992 ` case '\n': out += "\\n"; break;` Executable case '\n': out += "\\n"; break;
statement.
993 ` case '\r': out += "\\r"; break;` Executable case '\r': out += "\\r"; break;
statement.
994 ` case '\t': out += "\\t"; break;` Executable case '\t': out += "\\t"; break;
statement.
995 ` default:` Source code line. default:
996 ` if (c < 0x20) { char buf[8]; Conditional branch if (c < 0x20) { char buf[8];
snprintf(buf,8,"\\u%04x",c); out+=buf; }` — run code only snprintf(buf,8,"\\u%04x",c);
when condition true. out+=buf; }
997 ` else out += (char)c;` Executable else out += (char)c;
statement.
998 ` break;` Executable break;
statement.
999 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
1000 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
1001 ` return out;` Exit function and return out;
give back a value.
1002 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 276 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
1003 `` Blank line for Separator between code blocks.
readability.
1004 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/l7_parser.cpp
Total lines: 69

Line Source Easy Explanation Technical Explanation


1 `#include "l7_parser.h"` Import another header #include "l7_parser.h"
file into this
compilation unit.
2 `#include <cmath>` Import another header #include <cmath>
file into this
compilation unit.
3 `#include <cstring>` Import another header #include <cstring>
file into this
compilation unit.
4 `#include <array>` Import another header #include <array>
file into this
compilation unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `double dns_name_entropy(const Named constant — double dns_name_entropy(const
uint8_t* data, size_t len) {` value should not uint8_t* data, size_t len) {
change.
9 ` if (len == 0) return 0.0;` Conditional branch — if (len == 0) return 0.0;
run code only when
condition true.
10 ` std::array<uint64_t, 256> hist{};` Executable statement. std::array<uint64_t, 256> hist{};
11 ` for (size_t i = 0; i < len; ++i) Loop over items or for (size_t i = 0; i < len; ++i)
hist[data[i]]++;` until condition hist[data[i]]++;
changes.
12 ` double H = 0.0;` Executable statement. double H = 0.0;
13 ` for (auto c : hist) {` Loop over items or for (auto c : hist) {
until condition
changes.
14 ` if (!c) continue;` Conditional branch — if (!c) continue;
run code only when
condition true.

Page 277 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


15 ` double p = static_cast<double>(c) Executable statement. double p = static_cast<double>(c) /
/ static_cast<double>(len);` static_cast<double>(len);
16 ` H -= p * std::log2(p);` Executable statement. H -= p * std::log2(p);
17 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
18 ` return H;` Exit function and give return H;
back a value.
19 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
20 `` Blank line for Separator between code blocks.
readability.
21 `static bool starts_with(const uint8_t* p, Named constant — static bool starts_with(const uint8_t* p,
size_t n, const char* s) {` value should not size_t n, const char* s) {
change.
22 ` size_t slen = std::strlen(s);` Executable statement. size_t slen = std::strlen(s);
23 ` if (n < slen) return false;` Conditional branch — if (n < slen) return false;
run code only when
condition true.
24 ` return std::memcmp(p, s, slen) == Exit function and give return std::memcmp(p, s, slen) == 0;
0;` back a value.
25 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
26 `` Blank line for Separator between code blocks.
readability.
27 `void parse_l7_hints(PacketInfo& pkt, Source code line. void parse_l7_hints(PacketInfo& pkt,
size_t max_inspect) {` size_t max_inspect) {
28 ` if (pkt.payload_size == 0 \ \ `
29 ` pkt.payload_offset + Byte index where Replaces old payload_ptr.
pkt.payload_size > payload starts inside
pkt.raw_bytes.size()) {` raw_bytes (safe after
move).
30 ` return;` Exit function and give return;
back a value.
31 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
32 `` Blank line for Separator between code blocks.
readability.
33 ` const uint8_t* pl = Byte index where Replaces old payload_ptr.
pkt.raw_bytes.data() + payload starts inside
pkt.payload_offset;` raw_bytes (safe after
move).
34 ` size_t n = Executable statement. size_t n =
std::min<size_t>(pkt.payload_size, std::min<size_t>(pkt.payload_size,
max_inspect);` max_inspect);
35 `` Blank line for Separator between code blocks.
readability.

Page 278 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


36 ` if ([Link] == PROTO_TCP) {` Conditional branch — if ([Link] == PROTO_TCP) {
run code only when
condition true.
37 ` if (pkt.dst_port == 80 \ \ pkt.dst_port == 8080 \
38 ` if (starts_with(pl, n, "GET ") \ \ starts_with(pl, n, "POST ") \
39 ` starts_with(pl, n, "HTTP/")) {` Source code line. starts_with(pl, n, "HTTP/")) {
40 ` pkt.l7.is_http = true;` Executable statement. pkt.l7.is_http = true;
41 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
42 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
43 ` if (pkt.dst_port == 443 \ \ pkt.src_port == 443) {`
44 ` if (n >= 5 && pl[0] == 0x16 && Conditional branch — if (n >= 5 && pl[0] == 0x16 && pl[1] ==
pl[1] == 0x03) {` run code only when 0x03) {
condition true.
45 ` pkt.l7.is_tls = true;` Executable statement. pkt.l7.is_tls = true;
46 ` // ClientHello record type Comment ClientHello record type 0x01 at pl[5]
0x01 at pl[5] when handshake` documenting intent. when handshake
47 ` if (n >= 6 && pl[5] == 0x01) {` Conditional branch — if (n >= 6 && pl[5] == 0x01) {
run code only when
condition true.
48 ` pkt.l7.ja3_placeholder = Executable statement. pkt.l7.ja3_placeholder =
"tls_client_hello";` "tls_client_hello";
49 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
50 ` } else if (n >= 2) {` Conditional branch — } else if (n >= 2) {
run code only when
condition true.
51 ` pkt.l7.malformed_tls = true;` Executable statement. pkt.l7.malformed_tls = true;
52 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
53 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
54 ` if (pkt.l7.is_http && pkt.dst_port != Conditional branch — if (pkt.l7.is_http && pkt.dst_port != 80
80 && pkt.dst_port != 8080 &&` run code only when && pkt.dst_port != 8080 &&
condition true.
55 ` pkt.src_port != 80 && Source code line. pkt.src_port != 80 && pkt.src_port !=
pkt.src_port != 8080) {` 8080) {
56 ` Executable statement. pkt.l7.http_on_non_standard_port =
pkt.l7.http_on_non_standard_port = true;
true;`
57 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

Page 279 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


58 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
59 `` Blank line for Separator between code blocks.
readability.
60 ` if ([Link] == PROTO_UDP && \ pkt.src_port == 53) && n > 12) {`
(pkt.dst_port == 53 \
61 ` pkt.l7.is_dns = true;` Executable statement. pkt.l7.is_dns = true;
62 ` pkt.l7.dns_entropy = Executable statement. pkt.l7.dns_entropy =
dns_name_entropy(pl + 12, n > 12 ? n - dns_name_entropy(pl + 12, n > 12 ? n
12 : 0);` - 12 : 0);
63 ` if (pkt.l7.dns_entropy > 4.0 && n > Conditional branch — if (pkt.l7.dns_entropy > 4.0 && n > 80)
80) {` run code only when {
condition true.
64 ` pkt.l7.dns_tunnel_suspect = Executable statement. pkt.l7.dns_tunnel_suspect = true;
true;`
65 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
66 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
67 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
68 `` Blank line for Separator between code blocks.
readability.
69 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/logistic_fusion.cpp
Total lines: 80

Line Source Easy Technical Explanation


Explanation
1 `#include "logistic_fusion.h"` Import another #include "logistic_fusion.h"
header file into this
compilation unit.
2 `#include <fstream>` Import another #include <fstream>
header file into this
compilation unit.
3 `#include <sstream>` Import another #include <sstream>
header file into this
compilation unit.
4 `#include <algorithm>` Import another #include <algorithm>
header file into this
compilation unit.

Page 280 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
5 `#include <cmath>` Import another #include <cmath>
header file into this
compilation unit.
6 `` Blank line for Separator between code blocks.
readability.
7 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
8 `` Blank line for Separator between code blocks.
readability.
9 `LogisticFusion::LogisticFusion(const Combine multiple Fusion / correlation logic.
Config& cfg) : lr_(cfg.fusion_learning_rate) {` detector scores.
10 ` weights_["statistical"] = 1.0;` Executable weights_["statistical"] = 1.0;
statement.
11 ` weights_["volume"] = 1.2;` Executable weights_["volume"] = 1.2;
statement.
12 ` weights_["protocol"] = 1.0;` Executable weights_["protocol"] = 1.0;
statement.
13 ` weights_["baseline"] = 0.8;` Executable weights_["baseline"] = 0.8;
statement.
14 ` weights_["graph"] = 0.7;` Executable weights_["graph"] = 0.7;
statement.
15 ` weights_["temporal"] = 0.6;` Executable weights_["temporal"] = 0.6;
statement.
16 ` weights_["entropy"] = 0.4;` Executable weights_["entropy"] = 0.4;
statement.
17 ` load_weights(cfg.fusion_weights_path);` Combine multiple Fusion / correlation logic.
detector scores.
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
19 `` Blank line for Separator between code blocks.
readability.
20 `double LogisticFusion::sigmoid(double z) Named constant double
const noexcept {` — value should LogisticFusion::sigmoid(double z)
not change. const noexcept {
21 ` if (z >= 0.0) {` Conditional branch if (z >= 0.0) {
— run code only
when condition
true.
22 ` double ez = std::exp(-z);` Executable double ez = std::exp(-z);
statement.
23 ` return 1.0 / (1.0 + ez);` Exit function and return 1.0 / (1.0 + ez);
give back a value.
24 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 281 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
25 ` double ez = std::exp(z);` Executable double ez = std::exp(z);
statement.
26 ` return ez / (1.0 + ez);` Exit function and return ez / (1.0 + ez);
give back a value.
27 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
28 `` Blank line for Separator between code blocks.
readability.
29 `double LogisticFusion::dot(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results) const detector score
{` result.
30 ` double z = bias_;` Executable double z = bias_;
statement.
31 ` for (const auto& d : results) {` Loop over items or for (const auto& d : results) {
until condition
changes.
32 ` auto it = Executable auto it =
weights_.find(d.detector_name);` statement. weights_.find(d.detector_name);
33 ` if (it != weights_.end()) z += it->second Conditional branch if (it != weights_.end()) z += it-
* [Link];` — run code only >second * [Link];
when condition
true.
34 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
35 ` return z;` Exit function and return z;
give back a value.
36 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
37 `` Blank line for Separator between code blocks.
readability.
38 `FusionResult LogisticFusion::fuse(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results) {` detector score
result.
39 ` FusionResult r;` Combine multiple Fusion / correlation logic.
detector scores.
40 ` r.detector_results = results;` Executable r.detector_results = results;
statement.
41 ` r.final_score = sigmoid(dot(results));` Executable r.final_score = sigmoid(dot(results));
statement.
42 ` r.is_anomaly = r.final_score >= 0.5;` Executable r.is_anomaly = r.final_score >= 0.5;
statement.
43 ` return r;` Exit function and return r;
give back a value.
44 `}` Brace or C/C++ syntax structure.
parenthesis

Page 282 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
45 `` Blank line for Separator between code blocks.
readability.
46 `void LogisticFusion::online_update(const Build or return a score 0-1, flags, detail string.
std::vector<DetectorResult>& results, bool detector score
label_alert) {` result.
47 ` double y = label_alert ? 1.0 : 0.0;` Executable double y = label_alert ? 1.0 : 0.0;
statement.
48 ` double p = sigmoid(dot(results));` Executable double p = sigmoid(dot(results));
statement.
49 ` double err = p - y;` Executable double err = p - y;
statement.
50 ` bias_ -= lr_ * err;` Executable bias_ -= lr_ * err;
statement.
51 ` for (const auto& d : results) {` Loop over items or for (const auto& d : results) {
until condition
changes.
52 ` auto it = Executable auto it =
weights_.find(d.detector_name);` statement. weights_.find(d.detector_name);
53 ` if (it == weights_.end()) continue;` Conditional branch if (it == weights_.end()) continue;
— run code only
when condition
true.
54 ` it->second -= lr_ * err * [Link];` Executable it->second -= lr_ * err * [Link];
statement.
55 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
56 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
57 `` Blank line for Separator between code blocks.
readability.
58 `bool LogisticFusion::load_weights(const Named constant bool
std::string& path) {` — value should LogisticFusion::load_weights(const
not change. std::string& path) {
59 ` std::ifstream in(path);` Executable std::ifstream in(path);
statement.
60 ` if (!in) return false;` Conditional branch if (!in) return false;
— run code only
when condition
true.
61 ` std::string key;` Executable std::string key;
statement.
62 ` double val = 0.0;` Executable double val = 0.0;
statement.

Page 283 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
63 ` while (in >> key >> val) {` Loop over items or while (in >> key >> val) {
until condition
changes.
64 ` if (key == "bias") bias_ = val;` Conditional branch if (key == "bias") bias_ = val;
— run code only
when condition
true.
65 ` else weights_[key] = val;` Executable else weights_[key] = val;
statement.
66 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
67 ` return true;` Exit function and return true;
give back a value.
68 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
69 `` Blank line for Separator between code blocks.
readability.
70 `bool LogisticFusion::save_weights(const Named constant bool
std::string& path) const {` — value should LogisticFusion::save_weights(const
not change. std::string& path) const {
71 ` std::ofstream out(path);` Executable std::ofstream out(path);
statement.
72 ` if (!out) return false;` Conditional branch if (!out) return false;
— run code only
when condition
true.
73 ` out << "bias " << bias_ << "\n";` Executable out << "bias " << bias_ << "\n";
statement.
74 ` for (const auto& kv : weights_) {` Loop over items or for (const auto& kv : weights_) {
until condition
changes.
75 ` out << [Link] << " " << [Link] << Executable out << [Link] << " " << [Link] <<
"\n";` statement. "\n";
76 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
77 ` return true;` Exit function and return true;
give back a value.
78 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
79 `` Blank line for Separator between code blocks.
readability.
80 `} // namespace nads` End of nads } // namespace nads
namespace.

Page 284 of 629


NADS Complete Technical Reference

File: nads/src/[Link]
Total lines: 105

Line Source Easy Explanation Technical Explanation


1 `// [Link] - CLI entry point for Comment documenting [Link] - CLI entry point for
NADS` intent. NADS
2 `#include "orchestrator.h"` Import another header file #include "orchestrator.h"
into this compilation unit.
3 `#include "config_loader.h"` Import another header file #include "config_loader.h"
into this compilation unit.
4 `#include <iostream>` Import another header file #include <iostream>
into this compilation unit.
5 `#include <csignal>` Import another header file #include <csignal>
into this compilation unit.
6 `#include <cstring>` Import another header file #include <cstring>
into this compilation unit.
7 `#include <atomic>` Import another header file #include <atomic>
into this compilation unit.
8 `` Blank line for readability. Separator between code blocks.
9 `using namespace nads;` Executable statement. using namespace nads;
10 `` Blank line for readability. Separator between code blocks.
11 `static std::atomic<bool> Counter safe to read/write Lock-free atomic variable.
g_stop{false};` from multiple threads.
12 `static Orchestrator* g_orch = Executable statement. static Orchestrator* g_orch =
nullptr;` nullptr;
13 `` Blank line for readability. Separator between code blocks.
14 `static void signal_handler(int Source code line. static void signal_handler(int
signum) {` signum) {
15 ` (void)signum;` Executable statement. (void)signum;
16 ` g_stop = true;` Executable statement. g_stop = true;
17 ` if (g_orch) g_orch->stop();` Conditional branch — run if (g_orch) g_orch->stop();
code only when condition
true.
18 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
19 `` Blank line for readability. Separator between code blocks.
20 `static void print_banner() {` Source code line. static void print_banner() {
21 ` std::cout << R"(` Source code line. std::cout << R"(
22 ` _ _ _ ____ ____` Source code line. _ _ _ ____ ____
23 ` \ \\ \
24 ` \ \\ \
25 ` \ \ \ \
26 ` \ _\ \_/_/ \_\____/\

Page 285 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


27 ` Network Anomaly Detection Source code line. Network Anomaly Detection
System v1.0` System v1.0
28 `)" << "\n";` Executable statement. )" << "\n";
29 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
30 `` Blank line for readability. Separator between code blocks.
31 `static void print_usage(const char* Named constant — value static void print_usage(const char*
argv0) {` should not change. argv0) {
32 ` std::cout << "Usage: " << argv0 Source code line. std::cout << "Usage: " << argv0 <<
<< " [options]\n"` " [options]\n"
33 ` << " -i <iface> Network Source code line. << " -i <iface> Network
interface (default: lo)\n"` interface (default: lo)\n"
34 ` << " -f <bpf> BPF filter Source code line. << " -f <bpf> BPF filter
(default: none)\n"` (default: none)\n"
35 ` << " -t <thresh> Alert Source code line. << " -t <thresh> Alert threshold
threshold 0.0-1.0 (default: 0.7)\n"` 0.0-1.0 (default: 0.7)\n"
36 ` << " -w <seconds> Flow Source code line. << " -w <seconds> Flow expiry
expiry timeout (default: 60)\n"` timeout (default: 60)\n"
37 ` << " -o <file> Log file Source code line. << " -o <file> Log file (default:
(default: [Link])\n"` [Link])\n"
38 ` << " -j <file> JSON Source code line. << " -j <file> JSON output
output (default: [Link])\n"` (default: [Link])\n"
39 ` << " -c <file> Config file Source code line. << " -c <file> Config file
(key=value lines)\n"` (key=value lines)\n"
40 ` << " -r Read-only Source code line. << " -r Read-only mode\n"
mode\n"`
41 ` << " -q Quiet (no Source code line. << " -q Quiet (no live
live dashboard)\n"` dashboard)\n"
42 ` << " -v Verbose\n"` Source code line. << " -v Verbose\n"
43 ` << " -p <port> Web API Source code line. << " -p <port> Web API port
port (default: 8080)\n"` (default: 8080)\n"
44 ` << " -h Help\n";` Executable statement. << " -h Help\n";
45 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
46 `` Blank line for readability. Separator between code blocks.
47 `int main(int argc, char** argv) {` Source code line. int main(int argc, char** argv) {
48 ` Config cfg;` Executable statement. Config cfg;
49 `` Blank line for readability. Separator between code blocks.
50 ` for (int i = 1; i < argc; ++i) {` Loop over items or until for (int i = 1; i < argc; ++i) {
condition changes.
51 ` std::string a = argv[i];` Executable statement. std::string a = argv[i];
52 ` auto need = [&](const char* Named constant — value auto need = [&](const char* opt) ->
opt) -> const char* {` should not change. const char* {
53 ` if (i + 1 >= argc) {` Conditional branch — run if (i + 1 >= argc) {
code only when condition
true.

Page 286 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


54 ` std::cerr << "Missing value Executable statement. std::cerr << "Missing value for " <<
for " << opt << "\n";` opt << "\n";
55 ` std::exit(2);` Executable statement. std::exit(2);
56 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
57 ` return argv[++i];` Exit function and give back a return argv[++i];
value.
58 ` };` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
59 ` if (a == "-h" \ \ a == "--help") { print_banner();
print_usage(argv[0]); return 0; }`
60 ` else if (a == "-i") [Link] = Executable statement. else if (a == "-i") [Link] =
need("-i");` need("-i");
61 ` else if (a == "-f") cfg.bpf_filter = Executable statement. else if (a == "-f") cfg.bpf_filter =
need("-f");` need("-f");
62 ` else if (a == "-t") Executable statement. else if (a == "-t")
cfg.alert_threshold = cfg.alert_threshold =
std::stod(need("-t"));` std::stod(need("-t"));
63 ` else if (a == "-w") Executable statement. else if (a == "-w")
cfg.flow_timeout_sec = cfg.flow_timeout_sec =
std::stoi(need("-w"));` std::stoi(need("-w"));
64 ` else if (a == "-o") cfg.output_log Executable statement. else if (a == "-o") cfg.output_log =
= need("-o");` need("-o");
65 ` else if (a == "-j") Executable statement. else if (a == "-j") cfg.json_output =
cfg.json_output = need("-j");` need("-j");
66 ` else if (a == "-c") Executable statement. else if (a == "-c")
load_config_file(cfg, need("-c"));` load_config_file(cfg, need("-c"));
67 ` else if (a == "-r") cfg.read_only Executable statement. else if (a == "-r") cfg.read_only =
= true;` true;
68 ` else if (a == "-q") Executable statement. else if (a == "-q")
cfg.no_dashboard = true;` cfg.no_dashboard = true;
69 ` else if (a == "-v") [Link] = Executable statement. else if (a == "-v") [Link] =
true;` true;
70 ` else if (a == "-p") Executable statement. else if (a == "-p")
cfg.web_server_port = cfg.web_server_port =
std::stoi(need("-p"));` std::stoi(need("-p"));
71 ` else {` Source code line. else {
72 ` std::cerr << "Unknown Executable statement. std::cerr << "Unknown option: " <<
option: " << a << "\n";` a << "\n";
73 ` print_usage(argv[0]);` Executable statement. print_usage(argv[0]);
74 ` return 2;` Exit function and give back a return 2;
value.
75 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
76 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
77 `` Blank line for readability. Separator between code blocks.
78 ` std::string verr;` Executable statement. std::string verr;

Page 287 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


79 ` if (!validate_config(cfg, &verr)) {` Conditional branch — run if (!validate_config(cfg, &verr)) {
code only when condition
true.
80 ` std::cerr << "Config validation Executable statement. std::cerr << "Config validation
failed: " << verr << "\n";` failed: " << verr << "\n";

Line Source Easy Explanation Technical Explanation


81 ` return 2;` Exit function and give return 2;
back a value.
82 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
83 `` Blank line for readability. Separator between code blocks.
84 ` print_banner();` Executable statement. print_banner();
85 ` std::cout << "Starting on interface: " Source code line. std::cout << "Starting on interface: "
<< [Link]` << [Link]
86 ` << " threshold=" << Source code line. << " threshold=" <<
cfg.alert_threshold` cfg.alert_threshold
87 ` << " adaptive=" << Source code line. << " adaptive=" <<
(cfg.adaptive_thresholds ? "on" : "off")` (cfg.adaptive_thresholds ? "on" :
"off")
88 ` << " fusion=" << Combine multiple Fusion / correlation logic.
cfg.fusion_type << "\n";` detector scores.
89 `` Blank line for readability. Separator between code blocks.
90 ` Orchestrator orch(cfg);` Executable statement. Orchestrator orch(cfg);
91 ` g_orch = &orch;` Executable statement. g_orch = &orch;
92 ` std::signal(SIGINT, Executable statement. std::signal(SIGINT, signal_handler);
signal_handler);`
93 ` std::signal(SIGTERM, Executable statement. std::signal(SIGTERM,
signal_handler);` signal_handler);
94 `` Blank line for readability. Separator between code blocks.
95 ` if (![Link]()) {` Conditional branch — run if (![Link]()) {
code only when condition
true.
96 ` std::cerr << "Failed to start: " << Executable statement. std::cerr << "Failed to start: " <<
orch.last_error() << "\n";` orch.last_error() << "\n";
97 ` std::cerr << "Hint: capture Executable statement. std::cerr << "Hint: capture requires
requires CAP_NET_RAW. Run with CAP_NET_RAW. Run with sudo,
sudo, or:\n";` or:\n";
98 ` std::cerr << " sudo setcap Executable statement. std::cerr << " sudo setcap
cap_net_raw+eip ./nads\n";` cap_net_raw+eip ./nads\n";
99 ` return 1;` Exit function and give return 1;
back a value.
100 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
101 `` Blank line for readability. Separator between code blocks.
102 ` [Link]();` Executable statement. [Link]();
103 ` orch.print_summary();` Executable statement. orch.print_summary();

Page 288 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


104 ` return 0;` Exit function and give return 0;
back a value.
105 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.

File: nads/src/metrics_registry.cpp
Total lines: 49

Line Source Easy Technical Explanation


Explanation
1 `#include "metrics_registry.h"` Import another #include "metrics_registry.h"
header file into
this compilation
unit.
2 `#include <sstream>` Import another #include <sstream>
header file into
this compilation
unit.
3 `#include <iomanip>` Import another #include <iomanip>
header file into
this compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `MetricsRegistry& Source code MetricsRegistry&
MetricsRegistry::instance() {` line. MetricsRegistry::instance() {
8 ` static MetricsRegistry reg;` Executable static MetricsRegistry reg;
statement.
9 ` return reg;` Exit function return reg;
and give back a
value.
10 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
11 `` Blank line for Separator between code blocks.
readability.
12 `void MetricsRegistry::inc(const Named constant void MetricsRegistry::inc(const std::string&
std::string& name, double by) {` — value should name, double by) {
not change.
13 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread

Page 289 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
uses shared
data at a time.
14 ` counters_[name] += by;` Executable counters_[name] += by;
statement.
15 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
16 `` Blank line for Separator between code blocks.
readability.
17 `void MetricsRegistry::set_gauge(const Named constant void MetricsRegistry::set_gauge(const
std::string& name, double value) {` — value should std::string& name, double value) {
not change.
18 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared
data at a time.
19 ` gauges_[name] = value;` Executable gauges_[name] = value;
statement.
20 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
21 `` Blank line for Separator between code blocks.
readability.
22 `void Named constant void
MetricsRegistry::set_labeled_gauge(const — value should MetricsRegistry::set_labeled_gauge(const
std::string& name,` not change. std::string& name,
23 ` const Named constant const std::string& label_key,
std::string& label_key,` — value should
not change.
24 ` const Named constant const std::string& label_val,
std::string& label_val,` — value should
not change.
25 ` double value) {` Source code double value) {
line.
26 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared
data at a time.
27 ` labeled_gauges_[name + "{" + Executable labeled_gauges_[name + "{" + label_key +
label_key + "=\"" + label_val + "\"}"] = statement. "=\"" + label_val + "\"}"] = value;
value;`
28 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
29 `` Blank line for Separator between code blocks.
readability.
30 `std::string MetricsRegistry::render() const Named constant std::string MetricsRegistry::render() const {
{` — value should
not change.

Page 290 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
31 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(mtx_);` only one thread
uses shared
data at a time.
32 ` std::ostringstream out;` Executable std::ostringstream out;
statement.
33 ` out << std::fixed << Executable out << std::fixed << std::setprecision(4);
std::setprecision(4);` statement.
34 ` for (const auto& kv : counters_) {` Loop over items for (const auto& kv : counters_) {
or until condition
changes.
35 ` out << "# TYPE " << [Link] << " Executable out << "# TYPE " << [Link] << "
counter\n";` statement. counter\n";
36 ` out << [Link] << " " << [Link] << Executable out << [Link] << " " << [Link] << "\n";
"\n";` statement.
37 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
38 ` for (const auto& kv : gauges_) {` Loop over items for (const auto& kv : gauges_) {
or until condition
changes.
39 ` out << "# TYPE " << [Link] << " Executable out << "# TYPE " << [Link] << " gauge\n";
gauge\n";` statement.
40 ` out << [Link] << " " << [Link] << Executable out << [Link] << " " << [Link] << "\n";
"\n";` statement.
41 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
42 ` for (const auto& kv : labeled_gauges_) Loop over items for (const auto& kv : labeled_gauges_) {
{` or until condition
changes.
43 ` out << "# TYPE Executable out << "# TYPE nads_detector_score
nads_detector_score gauge\n";` statement. gauge\n";
44 ` out << [Link] << " " << [Link] << Executable out << [Link] << " " << [Link] << "\n";
"\n";` statement.
45 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
46 ` return [Link]();` Exit function return [Link]();
and give back a
value.
47 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
48 `` Blank line for Separator between code blocks.
readability.
49 `} // namespace nads` End of nads } // namespace nads
namespace.

Page 291 of 629


NADS Complete Technical Reference

File: nads/src/[Link]
Total lines: 502

Lin Source Easy Technical Explanation


e Explanatio
n
1 `// [Link] - master controller wiring all Comment [Link] - master controller
components together` documenting wiring all components together
intent.
2 `// FIXED: rate_sampler_loop now calls volume_det_- Comment FIXED: rate_sampler_loop now calls
>detect() every second and` documenting volume_det_->detect() every second
intent. and
3 `// fires alerts immediately for flood conditions, without Comment fires alerts immediately for flood
waiting for` documenting conditions, without waiting for
intent.
4 `// flows to expire (which could take Comment flows to expire (which could take
flow_timeout_sec=30+ seconds).` documenting flow_timeout_sec=30+ seconds).
intent.
5 `#include "orchestrator.h"` Import #include "orchestrator.h"
another
header file
into this
compilation
unit.
6 `#include "metrics_registry.h"` Import #include "metrics_registry.h"
another
header file
into this
compilation
unit.
7 `#include <iostream>` Import #include <iostream>
another
header file
into this
compilation
unit.
8 `#include <chrono>` Import #include <chrono>
another
header file
into this
compilation
unit.
9 `#include <thread>` Import #include <thread>
another
header file
into this
compilation
unit.
10 `#include <iomanip>` Import #include <iomanip>
another
header file
into this

Page 292 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
compilation
unit.
11 `#include <unordered_set>` Import #include <unordered_set>
another
header file
into this
compilation
unit.
12 `#include <sstream>` Import #include <sstream>
another
header file
into this
compilation
unit.
13 `` Blank line for Separator between code blocks.
readability.
14 `namespace nads` Start a namespace nads
named code
region so
names do
not clash
globally.
15 `{` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
16 `` Blank line for Separator between code blocks.
readability.
17 ` Orchestrator::Orchestrator(const Config &cfg)` Named Orchestrator::Orchestrator(const
constant — Config &cfg)
value should
not change.
18 ` : cfg_(cfg), queue_(200000)` Source code : cfg_(cfg), queue_(200000)
line.
19 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
20 ` capture_ = Own a Heap object with unique ownership.
std::make_unique<PacketCapture>(cfg_.interface, module
cfg_.bpf_filter, queue_, stats_);` object; auto-
deleted
when done.
21 ` parser_ = std::make_unique<PacketParser>();` Own a Heap object with unique ownership.
module
object; auto-
deleted
when done.
22 ` flow_table_ = Own a Heap object with unique ownership.
std::make_unique<FlowTable>(cfg_.flow_timeout_sec);` module
object; auto-
deleted
when done.

Page 293 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
23 ` stat_det_ = std::make_unique<StatisticalDetector>();` Own a Heap object with unique ownership.
module
object; auto-
deleted
when done.
24 ` stat_det_->configure(cfg_);` Executable stat_det_->configure(cfg_);
statement.
25 ` volume_det_ = Own a Heap object with unique ownership.
std::make_unique<VolumeDetector>(cfg_);` module
object; auto-
deleted
when done.
26 ` proto_det_ = std::make_unique<ProtocolAnalyzer>();` Own a Heap object with unique ownership.
module
object; auto-
deleted
when done.
27 ` baseline_ = Own a Heap object with unique ownership.
std::make_unique<BaselineEngine>(cfg_);` module
object; auto-
deleted
when done.
28 ` correlation_ = Own a Heap object with unique ownership.
std::make_unique<CorrelationEngine>(cfg_.correlation_win module
dow_sec);` object; auto-
deleted
when done.
29 ` advanced_ = Own a Heap object with unique ownership.
std::make_unique<AdvancedDetectors>(cfg_);` module
object; auto-
deleted
when done.
30 ` graph_det_ = std::make_unique<GraphDetector>();` Own a Heap object with unique ownership.
module
object; auto-
deleted
when done.
31 ` temporal_det_ = Own a Heap object with unique ownership.
std::make_unique<TemporalDetector>();` module
object; auto-
deleted
when done.
32 ` entropy_det_ = Own a Heap object with unique ownership.
std::make_unique<EntropyProfiler>();` module
object; auto-
deleted
when done.
33 ` classifier_ = std::make_unique<ThreatClassifier>();` Own a Heap object with unique ownership.
module
object; auto-
deleted
when done.
34 ` fusion_ = std::make_unique<FusionEngine>(cfg_);` Own a Heap object with unique ownership.
module
object; auto-

Page 294 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
deleted
when done.
35 ` alerts_ = Own a Heap object with unique ownership.
std::make_unique<AlertSystem>(cfg_.output_log, module
cfg_.json_output);` object; auto-
deleted
when done.
36 ` display_ = Own a Heap object with unique ownership.
std::make_unique<ConsoleDisplay>(stats_, *alerts_, cfg_);` module
object; auto-
deleted
when done.
37 ` http_server_ = Own a Heap object with unique ownership.
std::make_unique<HttpServer>(cfg_.web_server_port, module
this);` object; auto-
deleted
when done.
38 ` stats_.start_time_us.store(wall_us());` Thread-safe std::memory_order relaxed typical.
update or
read of a
statistic.
39 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
40 `` Blank line for Separator between code blocks.
readability.
41 ` Orchestrator::~Orchestrator()` Source code Orchestrator::~Orchestrator()
line.
42 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
43 ` stop();` Executable stop();
statement.
44 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
45 `` Blank line for Separator between code blocks.
readability.
46 ` bool Orchestrator::start()` Source code bool Orchestrator::start()
line.
47 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
48 ` if (!capture_->open())` Conditional if (!capture_->open())
branch —
run code
only when
condition
true.

Page 295 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
49 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
50 ` last_error_ = capture_->last_error();` Executable last_error_ = capture_->last_error();
statement.
51 ` return false;` Exit function return false;
and give
back a
value.
52 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
53 ` running_ = true;` Executable running_ = true;
statement.
54 ` capture_->start();` Executable capture_->start();
statement.
55 ` analysis_thread_ = Executable analysis_thread_ =
std::thread(&Orchestrator::analysis_loop, this);` statement. std::thread(&Orchestrator::analysis_lo
op, this);
56 ` sweeper_thread_ = Executable sweeper_thread_ =
std::thread(&Orchestrator::sweeper_loop, this);` statement. std::thread(&Orchestrator::sweeper_lo
op, this);
57 ` sampler_thread_ = Executable sampler_thread_ =
std::thread(&Orchestrator::rate_sampler_loop, this);` statement. std::thread(&Orchestrator::rate_sampl
er_loop, this);
58 ` display_->start();` Executable display_->start();
statement.
59 ` http_server_->start();` Executable http_server_->start();
statement.
60 ` return true;` Exit function return true;
and give
back a
value.
61 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
62 `` Blank line for Separator between code blocks.
readability.
63 ` void Orchestrator::stop()` Source code void Orchestrator::stop()
line.
64 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
65 ` if (!running_.exchange(false))` Conditional if (!running_.exchange(false))
branch —
run code
only when

Page 296 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
condition
true.
66 ` return;` Exit function return;
and give
back a
value.
67 ` if (capture_)` Conditional if (capture_)
branch —
run code
only when
condition
true.
68 ` capture_->stop();` Executable capture_->stop();
statement.
69 ` queue_.stop();` Executable queue_.stop();
statement.
70 ` if (analysis_thread_.joinable())` Conditional if (analysis_thread_.joinable())
branch —
run code
only when
condition
true.
71 ` analysis_thread_.join();` Executable analysis_thread_.join();
statement.
72 ` if (sweeper_thread_.joinable())` Conditional if (sweeper_thread_.joinable())
branch —
run code
only when
condition
true.
73 ` sweeper_thread_.join();` Executable sweeper_thread_.join();
statement.
74 ` if (sampler_thread_.joinable())` Conditional if (sampler_thread_.joinable())
branch —
run code
only when
condition
true.
75 ` sampler_thread_.join();` Executable sampler_thread_.join();
statement.
76 ` if (display_)` Conditional if (display_)
branch —
run code
only when
condition
true.
77 ` display_->stop();` Executable display_->stop();
statement.
78 ` if (http_server_)` Conditional if (http_server_)
branch —
run code
only when

Page 297 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
condition
true.
79 ` http_server_->stop();` Executable http_server_->stop();
statement.
80 ` if (alerts_)` Conditional if (alerts_)
branch —
run code
only when
condition
true.

Li Source Easy Technical Explanation


n Explan
e ation
81 ` alerts_->shutdown();` Executa alerts_->shutdown();
ble
stateme
nt.
82 ` }` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
83 `` Blank Separator between code blocks.
line for
readabil
ity.
84 ` void Orchestrator::wait()` Source void Orchestrator::wait()
code
line.
85 ` {` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
86 ` while (running_.load())` Thread- std::memory_order relaxed typical.
safe
update
or read
of a
statistic.
87 ` {` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.

Page 298 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
88 ` Executa std::this_thread::sleep_for(std::chrono::milliseconds(
std::this_thread::sleep_for(std::chrono::milliseconds( ble 100));
100));` stateme
nt.
89 ` }` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
90 ` }` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
91 `` Blank Separator between code blocks.
line for
readabil
ity.
92 ` void Orchestrator::analysis_loop()` Source void Orchestrator::analysis_loop()
code
line.
93 ` {` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
94 ` std::unordered_set<uint32_t> seen_hosts;` Executa std::unordered_set<uint32_t> seen_hosts;
ble
stateme
nt.
95 ` while (running_.load())` Thread- std::memory_order relaxed typical.
safe
update
or read
of a
statistic.
96 ` {` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
97 ` PacketInfo pkt;` Executa PacketInfo pkt;
ble
stateme
nt.
98 ` if (!queue_.pop(pkt, 200))` Conditio if (!queue_.pop(pkt, 200))
nal

Page 299 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
branch
— run
code
only
when
conditio
n true.
99 ` continue;` Executa continue;
ble
stateme
nt.
10 `` Blank Separator between code blocks.
0 line for
readabil
ity.
10 ` if (!parser_->parse(pkt))` Conditio if (!parser_->parse(pkt))
1 nal
branch
— run
code
only
when
conditio
n true.
10 ` {` Brace C/C++ syntax structure.
2 or
parenth
esis
closing/
opening
a block.
10 ` Thread- std::memory_order relaxed typical.
3 stats_.total_packets_processed.fetch_add(1, safe
std::memory_order_relaxed);` update
or read
of a
statistic.
10 ` continue;` Executa continue;
4 ble
stateme
nt.
10 ` }` Brace C/C++ syntax structure.
5 or
parenth
esis
closing/
opening
a block.
10 ` // Comme ────────────────────────────────
6 ───────────────────────────────── nt ──────────────────────────────
─────────────────────────────` docume
nting
intent.
10 ` // Count packets per source IP for volume Comme Count packets per source IP for volume alert
7 alert attribution` nt attribution
docume

Page 300 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
nting
intent.
10 ` int64_t now_sec = pkt.timestamp_us / Executa int64_t now_sec = pkt.timestamp_us / 1000000;
8 1000000;` ble
stateme
nt.
10 ` {` Brace C/C++ syntax structure.
9 or
parenth
esis
closing/
opening
a block.
11 ` std::lock_guard<std::mutex> Lock a RAII mutex lock.
0 lock(second_counts_mutex_);` mutex
so only
one
thread
uses
shared
data at
a time.
11 ` if (now_sec != last_second_)` Conditio if (now_sec != last_second_)
1 nal
branch
— run
code
only
when
conditio
n true.
11 ` {` Brace C/C++ syntax structure.
2 or
parenth
esis
closing/
opening
a block.
11 ` last_second_ = now_sec;` Executa last_second_ = now_sec;
3 ble
stateme
nt.
11 ` second_pkt_counts_.clear();` Executa second_pkt_counts_.clear();
4 ble
stateme
nt.
11 ` }` Brace C/C++ syntax structure.
5 or
parenth
esis
closing/
opening
a block.
11 ` second_pkt_counts_[pkt.src_ip]++;` Executa second_pkt_counts_[pkt.src_ip]++;
6 ble

Page 301 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
stateme
nt.
11 ` }` Brace C/C++ syntax structure.
7 or
parenth
esis
closing/
opening
a block.
11 `` Blank Separator between code blocks.
8 line for
readabil
ity.
11 ` // Broadcast packet to frontend (throttled: Comme Broadcast packet to frontend (throttled: every 5th
9 every 5th packet)` nt packet)
docume
nting
intent.
12 ` if (http_server_ && Conditio if (http_server_ && pkt_broadcast_counter_++ % 5
0 pkt_broadcast_counter_++ % 5 == 0)` nal == 0)
branch
— run
code
only
when
conditio
n true.
12 ` {` Brace C/C++ syntax structure.
1 or
parenth
esis
closing/
opening
a block.
12 ` http_server_->push_packet(pkt);` Executa http_server_->push_packet(pkt);
2 ble
stateme
nt.
12 ` }` Brace C/C++ syntax structure.
3 or
parenth
esis
closing/
opening
a block.
12 `` Blank Separator between code blocks.
4 line for
readabil
ity.
12 ` volume_det_->on_packet(pkt);` Executa volume_det_->on_packet(pkt);
5 ble
stateme
nt.
12 ` if (advanced_) advanced_->on_packet(pkt);` Conditio if (advanced_) advanced_->on_packet(pkt);
6 nal

Page 302 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
branch
— run
code
only
when
conditio
n true.
12 `` Blank Separator between code blocks.
7 line for
readabil
ity.
12 ` // Update flow table` Comme Update flow table
8 nt
docume
nting
intent.
12 ` bool is_new_flow = false;` Executa bool is_new_flow = false;
9 ble
stateme
nt.
13 ` FlowRecord &rec = flow_table_->touch(pkt, Executa FlowRecord &rec = flow_table_->touch(pkt,
0 &is_new_flow);` ble &is_new_flow);
stateme
nt.
13 ` (void)rec;` Executa (void)rec;
1 ble
stateme
nt.
13 ` if (is_new_flow)` Conditio if (is_new_flow)
2 nal
branch
— run
code
only
when
conditio
n true.
13 ` {` Brace C/C++ syntax structure.
3 or
parenth
esis
closing/
opening
a block.
13 ` volume_det_->on_new_flow();` Executa volume_det_->on_new_flow();
4 ble
stateme
nt.
13 ` stats_.active_flows.store(flow_table_- Thread- std::memory_order relaxed typical.
5 >size());` safe
update
or read
of a
statistic.

Page 303 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
13 ` DetectorResult gres = graph_det_- Build or score 0-1, flags, detail string.
6 >on_new_flow(pkt.src_ip, pkt.dst_ip, return a
pkt.timestamp_us);` detector
score
result.
13 ` if ([Link] >= 0.85)` Conditio if ([Link] >= 0.85)
7 nal
branch
— run
code
only
when
conditio
n true.
13 ` {` Brace C/C++ syntax structure.
8 or
parenth
esis
closing/
opening
a block.
13 ` std::vector<DetectorResult> results = Build or score 0-1, flags, detail string.
9 {gres};` return a
detector
score
result.
14 ` FusionResult fr = fusion_- Combin Fusion / correlation logic.
0 >fuse(results);` e
multiple
detector
scores.
14 ` if (fr.final_score >= Conditio if (fr.final_score >= cfg_.alert_threshold)
1 cfg_.alert_threshold)` nal
branch
— run
code
only
when
conditio
n true.
14 ` {` Brace C/C++ syntax structure.
2 or
parenth
esis
closing/
opening
a block.
14 ` auto klass = classifier_->classify(rec, Executa auto klass = classifier_->classify(rec, results,
3 results, fr.final_score);` ble fr.final_score);
stateme
nt.
14 ` AnomalyEvent ev{};` Final Enterprise alert struct.
4 alert
record
sent to

Page 304 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
logs
and UI.
14 ` ev.timestamp_us = wall_us();` Executa ev.timestamp_us = wall_us();
5 ble
stateme
nt.
14 ` ev.src_ip = pkt.src_ip;` Executa ev.src_ip = pkt.src_ip;
6 ble
stateme
nt.
14 ` ev.dst_ip = pkt.dst_ip;` Executa ev.dst_ip = pkt.dst_ip;
7 ble
stateme
nt.
14 ` ev.src_port = pkt.src_port;` Executa ev.src_port = pkt.src_port;
8 ble
stateme
nt.
14 ` ev.dst_port = pkt.dst_port;` Executa ev.dst_port = pkt.dst_port;
9 ble
stateme
nt.
15 ` [Link] = [Link];` Executa [Link] = [Link];
0 ble
stateme
nt.
15 ` ev.attack_type = klass.attack_type;` Executa ev.attack_type = klass.attack_type;
1 ble
stateme
nt.
15 ` [Link] = [Link];` Executa [Link] = [Link];
2 ble
stateme
nt.
15 ` [Link] = [Link];` Executa [Link] = [Link];
3 ble
stateme
nt.
15 ` ev.final_score = fr.final_score;` Executa ev.final_score = fr.final_score;
4 ble
stateme
nt.
15 ` [Link] = [Link];` Executa [Link] = [Link];
5 ble
stateme
nt.
15 ` [Link] = Executa [Link] = [Link];
6 [Link];` ble
stateme
nt.
15 ` ev.detector_results = results;` Executa ev.detector_results = results;
7 ble

Page 305 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
stateme
nt.
15 ` if (alerts_->send(ev))` Conditio if (alerts_->send(ev))
8 nal
branch
— run
code
only
when
conditio
n true.
15 ` {` Brace C/C++ syntax structure.
9 or
parenth
esis
closing/
opening
a block.
16 ` stats_.alerts_total.fetch_add(1);` Thread- std::memory_order relaxed typical.
0 safe
update
or read
of a
statistic.

Lin Source Easy Technical Explanation


e Explanatio
n
161 ` if ([Link] == Conditional if ([Link] == Severity::CRITICAL)
Severity::CRITICAL)` branch —
run code
only when
condition
true.
162 ` Thread-safe std::memory_order relaxed typical.
stats_.alerts_critical.fetch_add(1);` update or
read of a
statistic.
163 ` else if ([Link] == Source code else if ([Link] == Severity::HIGH)
Severity::HIGH)` line.
164 ` Thread-safe std::memory_order relaxed typical.
stats_.alerts_high.fetch_add(1);` update or
read of a
statistic.
165 ` else if ([Link] == Source code else if ([Link] == Severity::MEDIUM)
Severity::MEDIUM)` line.
166 ` Thread-safe std::memory_order relaxed typical.
stats_.alerts_medium.fetch_add(1);` update or
read of a
statistic.
167 ` if (http_server_)` Conditional if (http_server_)
branch —
run code
only when

Page 306 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
condition
true.
168 ` http_server_- Executable http_server_->push_alert(ev);
>push_alert(ev);` statement.
169 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
170 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
171 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
172 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
173 `` Blank line for Separator between code blocks.
readability.
174 ` if (seen_hosts.insert(pkt.src_ip).second)` Conditional if (seen_hosts.insert(pkt.src_ip).second)
branch —
run code
only when
condition
true.
175 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
176 ` Thread-safe std::memory_order relaxed typical.
stats_.total_hosts.store(seen_hosts.size());` update or
read of a
statistic.
177 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
178 ` if (display_ && !cfg_.no_dashboard)` Conditional if (display_ && !cfg_.no_dashboard)
branch —
run code
only when
condition
true.
179 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
180 ` display_->update_top_talker(pkt.src_ip, Executable display_->update_top_talker(pkt.src_ip,
[Link]);` statement. [Link]);

Page 307 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
181 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
182 `` Blank line for Separator between code blocks.
readability.
183 ` Thread-safe std::memory_order relaxed typical.
stats_.total_packets_processed.fetch_add(1);` update or
read of a
statistic.
184 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
185 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
186 `` Blank line for Separator between code blocks.
readability.
187 ` void Orchestrator::sweeper_loop()` Source code void Orchestrator::sweeper_loop()
line.
188 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
189 ` while (running_.load())` Thread-safe std::memory_order relaxed typical.
update or
read of a
statistic.
190 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
191 ` for (int i = 0; i < 50 && running_.load(); Thread-safe std::memory_order relaxed typical.
++i)` update or
read of a
statistic.
192 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
193 ` Executable std::this_thread::sleep_for(std::chrono::milliseco
std::this_thread::sleep_for(std::chrono::millisecon statement. nds(100));
ds(100));`
194 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
195 ` if (!running_.load())` Thread-safe std::memory_order relaxed typical.
update or
read of a
statistic.

Page 308 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
196 ` break;` Executable break;
statement.
197 ` auto expired = flow_table_- Executable auto expired = flow_table_-
>sweep_expired(now_us());` statement. >sweep_expired(now_us());
198 ` Thread-safe std::memory_order relaxed typical.
stats_.completed_flows.fetch_add([Link]()); update or
` read of a
statistic.
199 ` for (auto &f : expired)` Loop over for (auto &f : expired)
items or until
condition
changes.
200 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
201 ` Executable process_completed_flow(std::move(f));
process_completed_flow(std::move(f));` statement.
202 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
203 ` stats_.active_flows.store(flow_table_- Thread-safe std::memory_order relaxed typical.
>size());` update or
read of a
statistic.
204 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
205 ` auto expired = flow_table_- Executable auto expired = flow_table_-
>sweep_expired(now_us() + 365LL * 24 * 3600 * statement. >sweep_expired(now_us() + 365LL * 24 * 3600
1000000LL);` * 1000000LL);
206 ` for (auto &f : expired)` Loop over for (auto &f : expired)
items or until
condition
changes.
207 ` process_completed_flow(std::move(f));` Executable process_completed_flow(std::move(f));
statement.
208 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
209 `` Blank line for Separator between code blocks.
readability.
210 ` void Orchestrator::update_metrics(double pps, Source code void Orchestrator::update_metrics(double pps,
double bps)` line. double bps)
211 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.

Page 309 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
212 ` if (!cfg_.metrics_enabled) return;` Conditional if (!cfg_.metrics_enabled) return;
branch —
run code
only when
condition
true.
213 ` auto& m = MetricsRegistry::instance();` Executable auto& m = MetricsRegistry::instance();
statement.
214 ` m.set_gauge("nads_capture_pps", pps);` Executable m.set_gauge("nads_capture_pps", pps);
statement.
215 ` m.set_gauge("nads_capture_bps", bps);` Executable m.set_gauge("nads_capture_bps", bps);
statement.
216 ` m.set_gauge("nads_flows_active", Thread-safe std::memory_order relaxed typical.
static_cast<double>(stats_.active_flows.load()));` update or
read of a
statistic.
217 ` m.set_gauge("nads_flows_completed_total", Thread-safe std::memory_order relaxed typical.
static_cast<double>(stats_.completed_flows.load( update or
)));` read of a
statistic.
218 ` m.set_gauge("nads_alerts_total", Thread-safe std::memory_order relaxed typical.
static_cast<double>(stats_.alerts_total.load()));` update or
read of a
statistic.
219 ` Thread-safe std::memory_order relaxed typical.
m.set_gauge("nads_packets_captured_total", update or
static_cast<double>(stats_.total_packets_capture read of a
[Link]()));` statistic.
220 ` Thread-safe std::memory_order relaxed typical.
m.set_gauge("nads_packets_dropped_total", update or
static_cast<double>(stats_.total_packets_droppe read of a
[Link]()));` statistic.
221 ` m.set_gauge("nads_queue_depth", Thread-safe std::memory_order relaxed typical.
static_cast<double>(stats_.queue_size.load()));` update or
read of a
statistic.
222 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
223 `` Blank line for Separator between code blocks.
readability.
224 ` void Source code void
Orchestrator::process_completed_flow(FlowRecor line. Orchestrator::process_completed_flow(FlowRec
d flow)` ord flow)
225 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
226 ` std::vector<DetectorResult> results;` Build or score 0-1, flags, detail string.
return a
detector
score result.

Page 310 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
227 ` results.push_back(stat_det_->detect(flow));` Executable results.push_back(stat_det_->detect(flow));
statement.
228 ` results.push_back(proto_det_- Executable results.push_back(proto_det_->analyze(flow));
>analyze(flow));` statement.
229 ` results.push_back(baseline_- Executable results.push_back(baseline_->analyze(flow));
>analyze(flow));` statement.
230 ` results.push_back(temporal_det_- Executable results.push_back(temporal_det_->detect(flow));
>detect(flow));` statement.
231 ` results.push_back(entropy_det_- Executable results.push_back(entropy_det_->score(flow));
>score(flow));` statement.
232 ` results.push_back(volume_det_->detect());` Executable results.push_back(volume_det_->detect());
statement.
233 ` DetectorResult graph_res = graph_det_- Build or score 0-1, flags, detail string.
>on_new_flow([Link].src_ip, [Link].dst_ip, return a
flow.last_seen_us);` detector
score result.
234 ` results.push_back(graph_res);` Executable results.push_back(graph_res);
statement.
235 `` Blank line for Separator between code blocks.
readability.
236 ` if (advanced_) {` Conditional if (advanced_) {
branch —
run code
only when
condition
true.
237 ` for (auto& ar : advanced_- Loop over for (auto& ar : advanced_->analyze_flow(flow)) {
>analyze_flow(flow)) {` items or until
condition
changes.
238 ` results.push_back(std::move(ar));` Executable results.push_back(std::move(ar));
statement.
239 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
240 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.

Li Source Easy Technical Explanation


n Expla
e natio
n
2 `` Blank Separator between code blocks.
4 line for
1 reada
bility.

Page 311 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` for (const auto& dr : results) {` Loop for (const auto& dr : results) {
4 over
2 items
or until
conditi
on
chang
es.
2 ` correlation_->record([Link].src_ip, dr, Execu correlation_->record([Link].src_ip, dr,
4 flow.last_seen_us);` table flow.last_seen_us);
3 statem
ent.
2 ` if (cfg_.metrics_enabled && [Link] > 0.0) {` Condit if (cfg_.metrics_enabled && [Link] > 0.0) {
4 ional
4 branc
h—
run
code
only
when
conditi
on
true.
2 ` Sourc MetricsRegistry::instance().set_labeled_gauge(
4 MetricsRegistry::instance().set_labeled_gauge(` e code
5 line.
2 ` "nads_detector_score", "detector", Execu "nads_detector_score", "detector", dr.detector_name,
4 dr.detector_name, [Link]);` table [Link]);
6 statem
ent.
2 ` }` Brace C/C++ syntax structure.
4 or
7 parent
hesis
closin
g/ope
ning a
block.
2 ` }` Brace C/C++ syntax structure.
4 or
8 parent
hesis
closin
g/ope
ning a
block.
2 `` Blank Separator between code blocks.
4 line for
9 reada
bility.
2 ` FusionResult fr = fusion_->fuse(results);` Combi Fusion / correlation logic.
5 ne
0 multipl
e
detect

Page 312 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
or
scores
.
2 ` double cboost = correlation_- Execu double cboost = correlation_-
5 >correlation_boost([Link].src_ip, table >correlation_boost([Link].src_ip,
1 flow.last_seen_us);` statem flow.last_seen_us);
ent.
2 ` fr.final_score = std::min(1.0, fr.final_score + Execu fr.final_score = std::min(1.0, fr.final_score + cboost);
5 cboost);` table
2 statem
ent.
2 `` Blank Separator between code blocks.
5 line for
3 reada
bility.
2 ` if (fr.final_score < cfg_.alert_threshold)` Condit if (fr.final_score < cfg_.alert_threshold)
5 ional
4 branc
h—
run
code
only
when
conditi
on
true.
2 ` return;` Exit return;
5 functio
5 n and
give
back a
value.
2 `` Blank Separator between code blocks.
5 line for
6 reada
bility.
2 ` auto klass = classifier_->classify(flow, results, Execu auto klass = classifier_->classify(flow, results,
5 fr.final_score);` table fr.final_score);
7 statem
ent.
2 `` Blank Separator between code blocks.
5 line for
8 reada
bility.
2 ` AnomalyEvent ev{};` Final Enterprise alert struct.
5 alert
9 record
sent to
logs
and
UI.
2 ` ev.timestamp_us = wall_us();` Execu ev.timestamp_us = wall_us();
6 table
0

Page 313 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
statem
ent.
2 ` ev.src_ip = [Link].src_ip;` Execu ev.src_ip = [Link].src_ip;
6 table
1 statem
ent.
2 ` ev.dst_ip = [Link].dst_ip;` Execu ev.dst_ip = [Link].dst_ip;
6 table
2 statem
ent.
2 ` ev.src_port = [Link].src_port;` Execu ev.src_port = [Link].src_port;
6 table
3 statem
ent.
2 ` ev.dst_port = [Link].dst_port;` Execu ev.dst_port = [Link].dst_port;
6 table
4 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
6 table
5 statem
ent.
2 ` ev.attack_type = klass.attack_type;` Execu ev.attack_type = klass.attack_type;
6 table
6 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
6 table
7 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
6 table
8 statem
ent.
2 ` ev.final_score = fr.final_score;` Execu ev.final_score = fr.final_score;
6 table
9 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
7 table
0 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
7 table
1 statem
ent.
2 ` ev.detector_results = results;` Execu ev.detector_results = results;
7 table
2 statem
ent.

Page 314 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` ev.mitre_techniques = klass.mitre_techniques;` Execu ev.mitre_techniques = klass.mitre_techniques;
7 table
3 statem
ent.
2 ` ev.mitre_tactics = klass.mitre_tactics;` Execu ev.mitre_tactics = klass.mitre_tactics;
7 table
4 statem
ent.
2 ` [Link] = [Link];` Execu [Link] = [Link];
7 table
5 statem
ent.
2 ` ev.correlation_boost = cboost;` Execu ev.correlation_boost = cboost;
7 table
6 statem
ent.
2 ` ev.correlation_id = correlation_- Execu ev.correlation_id = correlation_-
7 >last_correlation_id([Link].src_ip);` table >last_correlation_id([Link].src_ip);
7 statem
ent.
2 ` ev.webhook_url = cfg_.webhook_url;` Execu ev.webhook_url = cfg_.webhook_url;
7 table
8 statem
ent.
2 ` ev.kafka_topic = ""; // placeholder` Sourc ev.kafka_topic = ""; // placeholder
7 e code
9 line.
2 ` std::ostringstream fs;` Execu std::ostringstream fs;
8 table
0 statem
ent.
2 ` fs << "pkts=" << flow.packet_count << " bytes=" Sourc fs << "pkts=" << flow.packet_count << " bytes=" <<
8 << flow.byte_count` e code flow.byte_count
1 line.
2 ` << " dur_s=" << ((flow.last_seen_us - Execu << " dur_s=" << ((flow.last_seen_us -
8 flow.first_seen_us) / 1e6);` table flow.first_seen_us) / 1e6);
2 statem
ent.
2 ` ev.flow_summary = [Link]();` Execu ev.flow_summary = [Link]();
8 table
3 statem
ent.
2 `` Blank Separator between code blocks.
8 line for
4 reada
bility.
2 ` if (alerts_->send(ev))` Condit if (alerts_->send(ev))
8 ional
5 branc
h—
run
code
only

Page 315 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
when
conditi
on
true.
2 ` {` Brace C/C++ syntax structure.
8 or
6 parent
hesis
closin
g/ope
ning a
block.
2 ` stats_.alerts_total.fetch_add(1);` Threa std::memory_order relaxed typical.
8 d-safe
7 updat
e or
read
of a
statisti
c.
2 ` if ([Link] == Severity::CRITICAL)` Condit if ([Link] == Severity::CRITICAL)
8 ional
8 branc
h—
run
code
only
when
conditi
on
true.
2 ` stats_.alerts_critical.fetch_add(1);` Threa std::memory_order relaxed typical.
8 d-safe
9 updat
e or
read
of a
statisti
c.
2 ` else if ([Link] == Severity::HIGH)` Sourc else if ([Link] == Severity::HIGH)
9 e code
0 line.
2 ` stats_.alerts_high.fetch_add(1);` Threa std::memory_order relaxed typical.
9 d-safe
1 updat
e or
read
of a
statisti
c.
2 ` else if ([Link] == Severity::MEDIUM)` Sourc else if ([Link] == Severity::MEDIUM)
9 e code
2 line.

Page 316 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` stats_.alerts_medium.fetch_add(1);` Threa std::memory_order relaxed typical.
9 d-safe
3 updat
e or
read
of a
statisti
c.
2 ` if (http_server_)` Condit if (http_server_)
9 ional
4 branc
h—
run
code
only
when
conditi
on
true.
2 ` http_server_->push_alert(ev);` Execu http_server_->push_alert(ev);
9 table
5 statem
ent.
2 ` }` Brace C/C++ syntax structure.
9 or
6 parent
hesis
closin
g/ope
ning a
block.
2 ` }` Brace C/C++ syntax structure.
9 or
7 parent
hesis
closin
g/ope
ning a
block.
2 `` Blank Separator between code blocks.
9 line for
8 reada
bility.
2 ` // Comm ═════════════════════════════════
9 ═════════════════════════════════ ent ═════════════════════════════════
9 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 ` // FIX: rate_sampler_loop now runs volume Comm FIX: rate_sampler_loop now runs volume detection
0 detection every second and fires` ent every second and fires
0 docum
enting
intent.

Page 317 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` // alerts immediately — does NOT wait for flow Comm alerts immediately — does NOT wait for flow expiry.
0 expiry.` ent
1 docum
enting
intent.
3 ` // This is the key fix: packet floods keep flows Comm This is the key fix: packet floods keep flows ALIVE so
0 ALIVE so they never` ent they never
2 docum
enting
intent.
3 ` // expire → old code never called volume_det_- Comm expire → old code never called volume_det_-
0 >detect() during a flood.` ent >detect() during a flood.
3 docum
enting
intent.
3 ` // Comm ═════════════════════════════════
0 ═════════════════════════════════ ent ═════════════════════════════════
4 ═════════════════════════════════ docum ══════════
══════════` enting
intent.
3 ` void Orchestrator::rate_sampler_loop()` Sourc void Orchestrator::rate_sampler_loop()
0 e code
5 line.
3 ` {` Brace C/C++ syntax structure.
0 or
6 parent
hesis
closin
g/ope
ning a
block.
3 ` uint64_t last_packets = 0;` Execu uint64_t last_packets = 0;
0 table
7 statem
ent.
3 ` uint64_t last_bytes = 0;` Execu uint64_t last_bytes = 0;
0 table
8 statem
ent.
3 ` int64_t last_us = wall_us();` Execu int64_t last_us = wall_us();
0 table
9 statem
ent.
3 `` Blank Separator between code blocks.
1 line for
0 reada
bility.
3 ` // Synthetic FlowRecord for the rate-based alert Comm Synthetic FlowRecord for the rate-based alert path
1 path` ent
1 docum
enting
intent.

Page 318 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
3 ` FlowRecord dummy_flow{};` Execu FlowRecord dummy_flow{};
1 table
2 statem
ent.
3 `` Blank Separator between code blocks.
1 line for
3 reada
bility.
3 ` while (running_.load())` Threa std::memory_order relaxed typical.
1 d-safe
4 updat
e or
read
of a
statisti
c.
3 ` {` Brace C/C++ syntax structure.
1 or
5 parent
hesis
closin
g/ope
ning a
block.
3 ` Execu std::this_thread::sleep_for(std::chrono::seconds(1));
1 std::this_thread::sleep_for(std::chrono::seconds(1));` table
6 statem
ent.
3 ` int64_t now = wall_us();` Execu int64_t now = wall_us();
1 table
7 statem
ent.
3 ` double dt_s = (now - last_us) / 1e6;` Execu double dt_s = (now - last_us) / 1e6;
1 table
8 statem
ent.
3 ` if (dt_s < 0.1)` Condit if (dt_s < 0.1)
1 ional
9 branc
h—
run
code
only
when
conditi
on
true.
3 ` continue;` Execu continue;
2 table
0 statem
ent.

Page 319 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
321 `` Blank line for Separator between code blocks.
readability.
322 ` uint64_t cur_p = Thread-safe std::memory_order relaxed typical.
stats_.total_packets_captured.load();` update or
read of a
statistic.
323 ` uint64_t cur_b = Thread-safe std::memory_order relaxed typical.
stats_.total_bytes.load();` update or
read of a
statistic.
324 ` double pps = (cur_p - last_packets) / Executable double pps = (cur_p - last_packets) / dt_s;
dt_s;` statement.
325 ` double bps = (cur_b - last_bytes) * 8.0 / Executable double bps = (cur_b - last_bytes) * 8.0 / dt_s;
dt_s;` statement.
326 ` stats_.current_pps.store(pps);` Thread-safe std::memory_order relaxed typical.
update or
read of a
statistic.
327 ` stats_.current_bps.store(bps);` Thread-safe std::memory_order relaxed typical.
update or
read of a
statistic.
328 ` update_metrics(pps, bps);` Executable update_metrics(pps, bps);
statement.
329 ` if (http_server_)` Conditional if (http_server_)
branch — run
code only
when
condition
true.
330 ` http_server_->push_stats(pps, bps, Thread-safe std::memory_order relaxed typical.
stats_.total_packets_captured.load());` update or
read of a
statistic.
331 `` Blank line for Separator between code blocks.
readability.
332 ` last_packets = cur_p;` Executable last_packets = cur_p;
statement.
333 ` last_bytes = cur_b;` Executable last_bytes = cur_b;
statement.
334 ` last_us = now;` Executable last_us = now;
statement.
335 ` if (display_)` Conditional if (display_)
branch — run
code only
when
condition
true.
336 ` display_->push_bps_sample(bps);` Executable display_->push_bps_sample(bps);
statement.
337 `` Blank line for Separator between code blocks.
readability.

Page 320 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
338 ` // ── REAL-TIME VOLUME ANOMALY Comment ── REAL-TIME VOLUME ANOMALY CHECK
CHECK documenting ──────────────────────────────
────────────────────────────── intent. ────
────`
339 ` // Run the volume detector once per Comment Run the volume detector once per second. This
second. This catches floods even` documenting catches floods even
intent.
340 ` // when flows stay alive and never reach Comment when flows stay alive and never reach the
the sweeper.` documenting sweeper.
intent.
341 ` DetectorResult vol_res = volume_det_- Build or score 0-1, flags, detail string.
>detect();` return a
detector
score result.
342 ` // if (vol_res.score >= Comment if (vol_res.score >= cfg_.alert_threshold)
cfg_.alert_threshold)` documenting
intent.
343 ` // {` Comment {
documenting
intent.
344 ` // // Build a minimal detector result set Comment Build a minimal detector result set for fusion
for fusion` documenting
intent.
345 ` // std::vector<DetectorResult> results Comment std::vector<DetectorResult> results = {vol_res};
= {vol_res};` documenting
intent.
346 `` Blank line for Separator between code blocks.
readability.
347 ` // // Also ask graph detector for current Comment Also ask graph detector for current state (no
state (no new edge, just re-check)` documenting new edge, just re-check)
intent.
348 ` // // Skip graph here to avoid double- Comment Skip graph here to avoid double-counting;
counting; volume alone is sufficient.` documenting volume alone is sufficient.
intent.
349 `` Blank line for Separator between code blocks.
readability.
350 ` // FusionResult fr = fusion_- Comment FusionResult fr = fusion_->fuse(results);
>fuse(results);` documenting
intent.
351 `` Blank line for Separator between code blocks.
readability.
352 ` // // Rate-limit: don't re-fire same Comment Rate-limit: don't re-fire same volume alert within
volume alert within 3 seconds` documenting 3 seconds
intent.
353 ` // int64_t now2 = wall_us();` Comment int64_t now2 = wall_us();
documenting
intent.
354 ` // if (now2 - last_volume_alert_us_ >= Comment if (now2 - last_volume_alert_us_ >= 3000000LL)
3000000LL)` documenting
intent.

Page 321 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
355 ` // {` Comment {
documenting
intent.
356 ` // auto klass = classifier_- Comment auto klass = classifier_->classify(dummy_flow,
>classify(dummy_flow, results, fr.final_score);` documenting results, fr.final_score);
intent.
357 `` Blank line for Separator between code blocks.
readability.
358 ` // AnomalyEvent ev{};` Comment AnomalyEvent ev{};
documenting
intent.
359 ` // // Skip alert if both IPs are zero Comment Skip alert if both IPs are zero (aggregate flood
(aggregate flood without attribution)` documenting without attribution)
intent.
360 ` // if (ev.src_ip == 0 && ev.dst_ip == Comment if (ev.src_ip == 0 && ev.dst_ip == 0)
0)` documenting
intent.
361 ` // {` Comment {
documenting
intent.
362 ` // // Option A: skip entirely` Comment Option A: skip entirely
documenting
intent.
363 ` // continue;` Comment continue;
documenting
intent.
364 ` // // Option B: downgrade Comment Option B: downgrade severity
severity` documenting
intent.
365 ` // // [Link] = Comment [Link] = Severity::MEDIUM;
Severity::MEDIUM;` documenting
intent.
366 ` // // [Link] *= 0.5;` Comment [Link] *= 0.5;
documenting
intent.
367 ` // }` Comment }
documenting
intent.
368 ` // ev.timestamp_us = now2;` Comment ev.timestamp_us = now2;
documenting
intent.
369 ` // ev.src_ip = 0; // unknown during Comment ev.src_ip = 0; // unknown during aggregate flood
aggregate flood` documenting
intent.
370 ` // ev.dst_ip = 0;` Comment ev.dst_ip = 0;
documenting
intent.
371 ` // ev.src_port = 0;` Comment ev.src_port = 0;
documenting
intent.

Page 322 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
372 ` // ev.dst_port = 0;` Comment ev.dst_port = 0;
documenting
intent.
373 ` // [Link] = 0;` Comment [Link] = 0;
documenting
intent.
374 ` // ev.attack_type = Comment ev.attack_type = klass.attack_type;
klass.attack_type;` documenting
intent.
375 ` // [Link] = [Link];` Comment [Link] = [Link];
documenting
intent.
376 ` // [Link] = Comment [Link] = [Link];
[Link];` documenting
intent.
377 ` // ev.final_score = fr.final_score;` Comment ev.final_score = fr.final_score;
documenting
intent.
378 ` // [Link] = Comment [Link] = [Link]()
[Link]()` documenting
intent.
379 ` // ? "Volumetric Comment ? "Volumetric anomaly: " + vol_res.detail
anomaly: " + vol_res.detail` documenting
intent.
380 ` // : [Link];` Comment : [Link];
documenting
intent.
381 ` // [Link] = Comment [Link] = [Link];
[Link];` documenting
intent.
382 ` // ev.detector_results = results;` Comment ev.detector_results = results;
documenting
intent.
383 `` Blank line for Separator between code blocks.
readability.
384 ` // if (alerts_->send(ev))` Comment if (alerts_->send(ev))
documenting
intent.
385 ` // {` Comment {
documenting
intent.
386 ` // Comment stats_.alerts_total.fetch_add(1);
stats_.alerts_total.fetch_add(1);` documenting
intent.
387 ` // if ([Link] == Comment if ([Link] == Severity::CRITICAL)
Severity::CRITICAL)` documenting
intent.
388 ` // Comment stats_.alerts_critical.fetch_add(1);
stats_.alerts_critical.fetch_add(1);` documenting
intent.

Page 323 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
389 ` // else if ([Link] == Comment else if ([Link] == Severity::HIGH)
Severity::HIGH)` documenting
intent.
390 ` // Comment stats_.alerts_high.fetch_add(1);
stats_.alerts_high.fetch_add(1);` documenting
intent.
391 ` // else if ([Link] == Comment else if ([Link] == Severity::MEDIUM)
Severity::MEDIUM)` documenting
intent.
392 ` // Comment stats_.alerts_medium.fetch_add(1);
stats_.alerts_medium.fetch_add(1);` documenting
intent.
393 ` // if (http_server_)` Comment if (http_server_)
documenting
intent.
394 ` // http_server_- Comment http_server_->push_alert(ev);
>push_alert(ev);` documenting
intent.
395 ` // last_volume_alert_us_ = Comment last_volume_alert_us_ = now2;
now2;` documenting
intent.
396 ` // }` Comment }
documenting
intent.
397 ` // }` Comment }
documenting
intent.
398 ` // }` Comment }
documenting
intent.
399 ` if (vol_res.score >= Conditional if (vol_res.score >= cfg_.alert_threshold)
cfg_.alert_threshold)` branch — run
code only
when
condition
true.
400 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Line Source Easy Explanation Technical Explanation


401 ` // Build a minimal detector result Comment Build a minimal detector result set for
set for fusion` documenting intent. fusion
402 ` std::vector<DetectorResult> Build or return a score 0-1, flags, detail string.
results = {vol_res};` detector score result.
403 `` Blank line for Separator between code blocks.
readability.
404 ` // Find top source IP from last Comment Find top source IP from last second's
second's counts` documenting intent. counts

Page 324 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


405 ` uint32_t top_ip = 0;` Executable uint32_t top_ip = 0;
statement.
406 ` uint64_t max_cnt = 0;` Executable uint64_t max_cnt = 0;
statement.
407 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
408 ` std::lock_guard<std::mutex> Lock a mutex so RAII mutex lock.
lock(second_counts_mutex_);` only one thread uses
shared data at a
time.
409 ` for (const auto &[ip, cnt] : Loop over items or for (const auto &[ip, cnt] :
second_pkt_counts_)` until condition second_pkt_counts_)
changes.
410 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
411 ` if (cnt > max_cnt)` Conditional branch if (cnt > max_cnt)
— run code only
when condition true.
412 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
413 ` max_cnt = cnt;` Executable max_cnt = cnt;
statement.
414 ` top_ip = ip;` Executable top_ip = ip;
statement.
415 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
416 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
417 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
418 `` Blank line for Separator between code blocks.
readability.
419 ` FusionResult fr = fusion_- Combine multiple Fusion / correlation logic.
>fuse(results);` detector scores.
420 `` Blank line for Separator between code blocks.
readability.
421 ` // Rate-limit: don't re-fire same Comment Rate-limit: don't re-fire same volume
volume alert within 3 seconds` documenting intent. alert within 3 seconds
422 ` int64_t now2 = wall_us();` Executable int64_t now2 = wall_us();
statement.
423 ` if (now2 - last_volume_alert_us_ Conditional branch if (now2 - last_volume_alert_us_ >=
>= 3000000LL)` — run code only 3000000LL)
when condition true.
424 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

Page 325 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


425 ` auto klass = classifier_- Executable auto klass = classifier_-
>classify(dummy_flow, results, statement. >classify(dummy_flow, results,
fr.final_score);` fr.final_score);
426 `` Blank line for Separator between code blocks.
readability.
427 ` AnomalyEvent ev{};` Final alert record Enterprise alert struct.
sent to logs and UI.
428 ` ev.timestamp_us = now2;` Executable ev.timestamp_us = now2;
statement.
429 ` ev.src_ip = top_ip; // ← use Source code line. ev.src_ip = top_ip; // ← use the top
the top source IP` source IP
430 ` ev.dst_ip = 0; // destination Source code line. ev.dst_ip = 0; // destination still
still unknown` unknown
431 ` ev.src_port = 0;` Executable ev.src_port = 0;
statement.
432 ` ev.dst_port = 0;` Executable ev.dst_port = 0;
statement.
433 ` [Link] = 0;` Executable [Link] = 0;
statement.
434 ` ev.attack_type = Executable ev.attack_type = klass.attack_type;
klass.attack_type;` statement.
435 ` [Link] = [Link];` Executable [Link] = [Link];
statement.
436 ` [Link] = Executable [Link] = [Link];
[Link];` statement.
437 ` ev.final_score = Executable ev.final_score = fr.final_score;
fr.final_score;` statement.
438 ` [Link] = Source code line. [Link] =
[Link]()` [Link]()
439 ` ? "Volumetric Source code line. ? "Volumetric anomaly: " +
anomaly: " + vol_res.detail` vol_res.detail
440 ` : Executable : [Link];
[Link];` statement.
441 ` [Link] = Executable [Link] =
[Link];` statement. [Link];
442 ` ev.detector_results = results;` Executable ev.detector_results = results;
statement.
443 `` Blank line for Separator between code blocks.
readability.
444 ` // Optional: skip alert if still no Comment Optional: skip alert if still no IP (i.e.,
IP (i.e., second_pkt_counts_ was empty)` documenting intent. second_pkt_counts_ was empty)
445 ` if (ev.src_ip == 0 && ev.dst_ip Conditional branch if (ev.src_ip == 0 && ev.dst_ip == 0)
== 0)` — run code only
when condition true.
446 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
447 ` // No source IP known → Comment No source IP known → either skip or
either skip or downgrade` documenting intent. downgrade

Page 326 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


448 ` // continue; // uncomment Comment continue; // uncomment to skip
to skip entirely` documenting intent. entirely
449 ` [Link] = Source code line. [Link] = Severity::MEDIUM; // or
Severity::MEDIUM; // or downgrade` downgrade
450 ` [Link] *= 0.5;` Executable [Link] *= 0.5;
statement.
451 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
452 `` Blank line for Separator between code blocks.
readability.
453 ` if (alerts_->send(ev))` Conditional branch if (alerts_->send(ev))
— run code only
when condition true.
454 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
455 ` Thread-safe update std::memory_order relaxed typical.
stats_.alerts_total.fetch_add(1);` or read of a statistic.
456 ` if ([Link] == Conditional branch if ([Link] ==
Severity::CRITICAL)` — run code only Severity::CRITICAL)
when condition true.
457 ` Thread-safe update std::memory_order relaxed typical.
stats_.alerts_critical.fetch_add(1);` or read of a statistic.
458 ` else if ([Link] == Source code line. else if ([Link] ==
Severity::HIGH)` Severity::HIGH)
459 ` Thread-safe update std::memory_order relaxed typical.
stats_.alerts_high.fetch_add(1);` or read of a statistic.
460 ` else if ([Link] == Source code line. else if ([Link] ==
Severity::MEDIUM)` Severity::MEDIUM)
461 ` Thread-safe update std::memory_order relaxed typical.
stats_.alerts_medium.fetch_add(1);` or read of a statistic.
462 ` if (http_server_)` Conditional branch if (http_server_)
— run code only
when condition true.
463 ` http_server_- Executable http_server_->push_alert(ev);
>push_alert(ev);` statement.
464 ` last_volume_alert_us_ = Executable last_volume_alert_us_ = now2;
now2;` statement.
465 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
466 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
467 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
468 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

Page 327 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


469 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
470 `` Blank line for Separator between code blocks.
readability.
471 ` void Orchestrator::print_summary()` Source code line. void Orchestrator::print_summary()
472 ` {` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
473 ` int64_t now = wall_us();` Executable int64_t now = wall_us();
statement.
474 ` int64_t start = Thread-safe update std::memory_order relaxed typical.
stats_.start_time_us.load();` or read of a statistic.
475 ` double dur_s = (now - start) / 1e6;` Executable double dur_s = (now - start) / 1e6;
statement.
476 ` if (dur_s <= 0)` Conditional branch if (dur_s <= 0)
— run code only
when condition true.
477 ` dur_s = 1;` Executable dur_s = 1;
statement.
478 ` std::cout << Executable std::cout <<
"\n=================== NADS Final statement. "\n=================== NADS
Report ===================\n";` Final Report
===================\n";
479 ` std::cout << "Runtime: " << Executable std::cout << "Runtime: " <<
std::fixed << std::setprecision(1) << dur_s statement. std::fixed << std::setprecision(1) <<
<< " s\n";` dur_s << " s\n";
480 ` std::cout << "Packets captured: " << Thread-safe update std::memory_order relaxed typical.
stats_.total_packets_captured.load() << or read of a statistic.
"\n";`

Li Source Easy Technical Explanation


ne Explana
tion
48 ` std::cout << "Packets processed: " << Thread- std::memory_order relaxed typical.
1 stats_.total_packets_processed.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << "Packets dropped: " << Thread- std::memory_order relaxed typical.
2 stats_.total_packets_dropped.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << "Total bytes: " << Thread- std::memory_order relaxed typical.
3 stats_.total_bytes.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << "Active flows: " << Executabl std::cout << "Active flows: " << flow_table_-
4 flow_table_->size() << "\n";` e >size() << "\n";
statement
.

Page 328 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
48 ` std::cout << "Completed flows: " << Thread- std::memory_order relaxed typical.
5 stats_.completed_flows.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << "Hosts seen: " << Thread- std::memory_order relaxed typical.
6 stats_.total_hosts.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << "Alerts total: " << Thread- std::memory_order relaxed typical.
7 stats_.alerts_total.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << " CRITICAL: " << Thread- std::memory_order relaxed typical.
8 stats_.alerts_critical.load() << "\n";` safe
update or
read of a
statistic.
48 ` std::cout << " HIGH: " << Thread- std::memory_order relaxed typical.
9 stats_.alerts_high.load() << "\n";` safe
update or
read of a
statistic.
49 ` std::cout << " MEDIUM: " << Thread- std::memory_order relaxed typical.
0 stats_.alerts_medium.load() << "\n";` safe
update or
read of a
statistic.
49 ` std::cout << "Average pps: " << Thread- std::memory_order relaxed typical.
1 static_cast<uint64_t>(stats_.total_packets_capture safe
[Link]() / dur_s) << ...` update or
read of a
statistic.
49 ` std::cout << "Log file: " << Executabl std::cout << "Log file: " << cfg_.output_log <<
2 cfg_.output_log << "\n";` e "\n";
statement
.
49 ` std::cout << "JSON file: " << Executabl std::cout << "JSON file: " << cfg_.json_output
3 cfg_.json_output << "\n";` e << "\n";
statement
.
49 ` std::cout << Executabl std::cout <<
4 "====================================== e "======================================
===================\n";` statement ===================\n";
.
49 ` }` Brace or C/C++ syntax structure.
5 parenthes
is
closing/o
pening a
block.
49 `` Blank line Separator between code blocks.
6 for

Page 329 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
readabilit
y.
49 ` std::vector<FlowRecord> Source std::vector<FlowRecord>
7 Orchestrator::get_flow_snapshot() const` code line. Orchestrator::get_flow_snapshot() const
49 ` {` Brace or C/C++ syntax structure.
8 parenthes
is
closing/o
pening a
block.
49 ` return flow_table_->get_all_flows();` Exit return flow_table_->get_all_flows();
9 function
and give
back a
value.
50 ` }` Brace or C/C++ syntax structure.
0 parenthes
is
closing/o
pening a
block.
50 `` Blank line Separator between code blocks.
1 for
readabilit
y.
50 `} // namespace nads` End of } // namespace nads
2 nads
namespa
ce.

File: nads/src/[Link]
Total lines: 119

Line Source Easy Explanation Technical Explanation


1 `// [Link] - extracts 5-tuple and Comment [Link] - extracts 5-tuple and
metadata from raw bytes` documenting intent. metadata from raw bytes
2 `#include "parser.h"` Import another header #include "parser.h"
file into this
compilation unit.
3 `#include "l7_parser.h"` Import another header #include "l7_parser.h"
file into this
compilation unit.
4 `#include <arpa/inet.h> // ntohs, ntohl` Import another header #include <arpa/inet.h> // ntohs, ntohl
file into this
compilation unit.
5 `` Blank line for Separator between code blocks.
readability.

Page 330 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


6 `namespace nads {` Start a named code namespace nads {
region so names do
not clash globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `bool PacketParser::parse(PacketInfo& Source code line. bool PacketParser::parse(PacketInfo&
pkt) {` pkt) {
9 ` [Link] = false;` Executable statement. [Link] = false;
10 ` if (pkt.raw_bytes.size() < 20) return Conditional branch — if (pkt.raw_bytes.size() < 20) return
false;` run code only when false;
condition true.
11 `` Blank line for Separator between code blocks.
readability.
12 ` const uint8_t* data = Named constant — const uint8_t* data =
pkt.raw_bytes.data();` value should not pkt.raw_bytes.data();
change.
13 ` size_t avail = pkt.raw_bytes.size();` Executable statement. size_t avail = pkt.raw_bytes.size();
14 ` size_t offset = 0;` Executable statement. size_t offset = 0;
15 `` Blank line for Separator between code blocks.
readability.
16 ` // Handle link layer` Comment Handle link layer
documenting intent.
17 ` // DLT_EN10MB (1): 14-byte Comment DLT_EN10MB (1): 14-byte Ethernet
Ethernet` documenting intent.
18 ` // DLT_NULL (0): 4-byte BSD Comment DLT_NULL (0): 4-byte BSD loopback
loopback header (family number)` documenting intent. header (family number)
19 ` // DLT_LINUX_SLL (113): 16-byte Comment DLT_LINUX_SLL (113): 16-byte Linux
Linux cooked` documenting intent. cooked
20 ` if (link_type_ == 1) {` Conditional branch — if (link_type_ == 1) {
run code only when
condition true.
21 ` if (avail < 14) return false;` Conditional branch — if (avail < 14) return false;
run code only when
condition true.
22 ` const auto* eth = Named constant — const auto* eth =
reinterpret_cast<const value should not reinterpret_cast<const
EthernetHeader*>(data);` change. EthernetHeader*>(data);
23 ` uint16_t etype = ntohs(eth- Executable statement. uint16_t etype = ntohs(eth-
>ether_type);` >ether_type);
24 ` if (etype != 0x0800) return false; Conditional branch — if (etype != 0x0800) return false; // not
// not IPv4` run code only when IPv4
condition true.
25 ` offset = 14;` Executable statement. offset = 14;
26 ` } else if (link_type_ == 0) {` Conditional branch — } else if (link_type_ == 0) {
run code only when
condition true.
27 ` if (avail < 4) return false;` Conditional branch — if (avail < 4) return false;
run code only when
condition true.

Page 331 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


28 ` // family is little-endian on host` Comment family is little-endian on host
documenting intent.
29 ` uint32_t family = Named constant — uint32_t family =
*reinterpret_cast<const value should not *reinterpret_cast<const
uint32_t*>(data);` change. uint32_t*>(data);
30 ` if (family != 2) return false; // Conditional branch — if (family != 2) return false; // AF_INET
AF_INET only` run code only when only
condition true.
31 ` offset = 4;` Executable statement. offset = 4;
32 ` } else if (link_type_ == 113) {` Conditional branch — } else if (link_type_ == 113) {
run code only when
condition true.
33 ` if (avail < 16) return false;` Conditional branch — if (avail < 16) return false;
run code only when
condition true.
34 ` const uint16_t* etype_p = Named constant — const uint16_t* etype_p =
reinterpret_cast<const uint16_t*>(data value should not reinterpret_cast<const uint16_t*>(data
+ 14);` change. + 14);
35 ` uint16_t etype = ntohs(*etype_p);` Executable statement. uint16_t etype = ntohs(*etype_p);
36 ` if (etype != 0x0800) return false;` Conditional branch — if (etype != 0x0800) return false;
run code only when
condition true.
37 ` offset = 16;` Executable statement. offset = 16;
38 ` } else {` Source code line. } else {
39 ` // Unknown link type: try parsing Comment Unknown link type: try parsing as raw
as raw IP` documenting intent. IP
40 ` offset = 0;` Executable statement. offset = 0;
41 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
42 `` Blank line for Separator between code blocks.
readability.
43 ` if (avail < offset + 20) return false;` Conditional branch — if (avail < offset + 20) return false;
run code only when
condition true.
44 `` Blank line for Separator between code blocks.
readability.
45 ` const auto* ip = Named constant — const auto* ip = reinterpret_cast<const
reinterpret_cast<const IPHeader*>(data value should not IPHeader*>(data + offset);
+ offset);` change.
46 ` int version = (ip->version_ihl >> 4) & Executable statement. int version = (ip->version_ihl >> 4) &
0x0F;` 0x0F;
47 ` int ip_hdr_len = (ip->version_ihl & Executable statement. int ip_hdr_len = (ip->version_ihl &
0x0F) * 4;` 0x0F) * 4;
48 ` if (version != 4 \ \ ip_hdr_len < 20) return false;`
49 ` if (avail < offset + Conditional branch — if (avail < offset +
static_cast<size_t>(ip_hdr_len)) return run code only when static_cast<size_t>(ip_hdr_len)) return
false;` condition true. false;
50 `` Blank line for Separator between code blocks.
readability.

Page 332 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


51 ` pkt.src_ip = ip->src_ip; // keep Source code line. pkt.src_ip = ip->src_ip; // keep
network byte order; ip_to_string handles network byte order; ip_to_string
it` handles it
52 ` pkt.dst_ip = ip->dst_ip;` Executable statement. pkt.dst_ip = ip->dst_ip;
53 ` [Link] = ip->protocol;` Executable statement. [Link] = ip->protocol;
54 `` Blank line for Separator between code blocks.
readability.
55 ` size_t l4_off = offset + ip_hdr_len;` Executable statement. size_t l4_off = offset + ip_hdr_len;
56 ` uint16_t total = ntohs(ip- Executable statement. uint16_t total = ntohs(ip->total_length);
>total_length);`
57 ` uint16_t cap_len = Source code line. uint16_t cap_len =
static_cast<uint16_t>(` static_cast<uint16_t>(
58 ` std::min<size_t>(pkt.cap_length ? Executable statement. std::min<size_t>(pkt.cap_length ?
pkt.cap_length : avail, avail));` pkt.cap_length : avail, avail));
59 ` if (total > cap_len) total = cap_len;` Conditional branch — if (total > cap_len) total = cap_len;
run code only when
condition true.
60 ` size_t l4_size = (total > ip_hdr_len) ? Executable statement. size_t l4_size = (total > ip_hdr_len) ?
(total - ip_hdr_len) : 0;` (total - ip_hdr_len) : 0;
61 `` Blank line for Separator between code blocks.
readability.
62 ` if ([Link] == PROTO_TCP) {` Conditional branch — if ([Link] == PROTO_TCP) {
run code only when
condition true.
63 ` if (avail < l4_off + 20) return false;` Conditional branch — if (avail < l4_off + 20) return false;
run code only when
condition true.
64 ` const auto* tcp = Named constant — const auto* tcp =
reinterpret_cast<const value should not reinterpret_cast<const
TCPHeader*>(data + l4_off);` change. TCPHeader*>(data + l4_off);
65 ` pkt.src_port = ntohs(tcp- Executable statement. pkt.src_port = ntohs(tcp->src_port);
>src_port);`
66 ` pkt.dst_port = ntohs(tcp- Executable statement. pkt.dst_port = ntohs(tcp->dst_port);
>dst_port);`
67 ` pkt.tcp_flags = tcp->flags;` Executable statement. pkt.tcp_flags = tcp->flags;
68 ` int tcp_hdr_len = ((tcp- Executable statement. int tcp_hdr_len = ((tcp->data_offset >>
>data_offset >> 4) & 0x0F) * 4;` 4) & 0x0F) * 4;
69 ` if (tcp_hdr_len < 20) tcp_hdr_len Conditional branch — if (tcp_hdr_len < 20) tcp_hdr_len = 20;
= 20;` run code only when
condition true.
70 ` size_t pl_off = l4_off + Executable statement. size_t pl_off = l4_off + tcp_hdr_len;
tcp_hdr_len;`
71 ` if (pl_off <= avail) {` Conditional branch — if (pl_off <= avail) {
run code only when
condition true.
72 ` pkt.payload_offset = Byte index where Replaces old payload_ptr.
static_cast<uint32_t>(pl_off);` payload starts inside
raw_bytes (safe after
move).

Page 333 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


73 ` size_t pl_size = (l4_size > Source code line. size_t pl_size = (l4_size >
static_cast<size_t>(tcp_hdr_len))` static_cast<size_t>(tcp_hdr_len))
74 ` ? l4_size - Executable statement. ? l4_size - tcp_hdr_len : 0;
tcp_hdr_len : 0;`
75 ` // clamp by available capture` Comment clamp by available capture
documenting intent.
76 ` if (pl_off + pl_size > avail) Conditional branch — if (pl_off + pl_size > avail) pl_size =
pl_size = avail - pl_off;` run code only when avail - pl_off;
condition true.
77 ` pkt.payload_size = Executable statement. pkt.payload_size =
static_cast<uint16_t>(pl_size);` static_cast<uint16_t>(pl_size);
78 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
79 ` parse_l7_hints(pkt);` Executable statement. parse_l7_hints(pkt);
80 ` [Link] = true;` Executable statement. [Link] = true;

Line Source Easy Technical Explanation


Explanation
81 ` return true;` Exit function return true;
and give back
a value.
82 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
83 `` Blank line for Separator between code blocks.
readability.
84 ` if ([Link] == PROTO_UDP) {` Conditional if ([Link] == PROTO_UDP) {
branch — run
code only when
condition true.
85 ` if (avail < l4_off + 8) return false;` Conditional if (avail < l4_off + 8) return false;
branch — run
code only when
condition true.
86 ` const auto* udp = reinterpret_cast<const Named const auto* udp = reinterpret_cast<const
UDPHeader*>(data + l4_off);` constant — UDPHeader*>(data + l4_off);
value should
not change.
87 ` pkt.src_port = ntohs(udp->src_port);` Executable pkt.src_port = ntohs(udp->src_port);
statement.
88 ` pkt.dst_port = ntohs(udp->dst_port);` Executable pkt.dst_port = ntohs(udp->dst_port);
statement.
89 ` pkt.tcp_flags = 0;` Executable pkt.tcp_flags = 0;
statement.
90 ` size_t pl_off = l4_off + 8;` Executable size_t pl_off = l4_off + 8;
statement.
91 ` if (pl_off <= avail) {` Conditional if (pl_off <= avail) {
branch — run
code only when
condition true.

Page 334 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
92 ` pkt.payload_offset = Byte index Replaces old payload_ptr.
static_cast<uint32_t>(pl_off);` where payload
starts inside
raw_bytes
(safe after
move).
93 ` uint16_t udp_total = ntohs(udp- Executable uint16_t udp_total = ntohs(udp->length);
>length);` statement.
94 ` size_t pl_size = (udp_total > 8) ? Executable size_t pl_size = (udp_total > 8) ? udp_total - 8
udp_total - 8 : 0;` statement. : 0;
95 ` if (pl_off + pl_size > avail) pl_size = Conditional if (pl_off + pl_size > avail) pl_size = avail -
avail - pl_off;` branch — run pl_off;
code only when
condition true.
96 ` pkt.payload_size = Executable pkt.payload_size =
static_cast<uint16_t>(pl_size);` statement. static_cast<uint16_t>(pl_size);
97 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
98 ` parse_l7_hints(pkt);` Executable parse_l7_hints(pkt);
statement.
99 ` [Link] = true;` Executable [Link] = true;
statement.
100 ` return true;` Exit function return true;
and give back
a value.
101 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
102 `` Blank line for Separator between code blocks.
readability.
103 ` if ([Link] == PROTO_ICMP) {` Conditional if ([Link] == PROTO_ICMP) {
branch — run
code only when
condition true.
104 ` pkt.src_port = 0;` Executable pkt.src_port = 0;
statement.
105 ` pkt.dst_port = 0;` Executable pkt.dst_port = 0;
statement.
106 ` pkt.tcp_flags = 0;` Executable pkt.tcp_flags = 0;
statement.
107 ` if (l4_off < avail) {` Conditional if (l4_off < avail) {
branch — run
code only when
condition true.
108 ` pkt.payload_offset = Byte index Replaces old payload_ptr.
static_cast<uint32_t>(l4_off);` where payload
starts inside
raw_bytes
(safe after
move).

Page 335 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
109 ` size_t pl_size = avail - l4_off;` Executable size_t pl_size = avail - l4_off;
statement.
110 ` pkt.payload_size = Executable pkt.payload_size =
static_cast<uint16_t>(std::min<size_t>(pl_size, statement. static_cast<uint16_t>(std::min<size_t>(pl_size,
l4_size));` l4_size));
111 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
112 ` [Link] = true;` Executable [Link] = true;
statement.
113 ` return true;` Exit function return true;
and give back
a value.
114 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
115 `` Blank line for Separator between code blocks.
readability.
116 ` return false;` Exit function return false;
and give back
a value.
117 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
118 `` Blank line for Separator between code blocks.
readability.
119 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/protocol_analyzer.cpp
Total lines: 86

Lin Source Easy Technical Explanation


e Explanation
1 `// protocol_analyzer.cpp - rule-based Comment protocol_analyzer.cpp - rule-based
TCP/UDP/DNS abuse detection` documenting TCP/UDP/DNS abuse detection
intent.
2 `#include "protocol_analyzer.h"` Import another #include "protocol_analyzer.h"
header file
into this
compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file
into this

Page 336 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region
so names do
not clash
globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `DetectorResult ProtocolAnalyzer::analyze(const Build or return score 0-1, flags, detail string.
FlowRecord& flow) {` a detector
score result.
8 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
9 ` res.detector_name = "protocol";` Executable res.detector_name = "protocol";
statement.
10 `` Blank line for Separator between code blocks.
readability.
11 ` double score = 0.0;` Executable double score = 0.0;
statement.
12 `` Blank line for Separator between code blocks.
readability.
13 ` if ([Link] == PROTO_TCP) {` Conditional if ([Link] == PROTO_TCP) {
branch — run
code only
when
condition true.
14 ` // SYN flood pattern` Comment SYN flood pattern
documenting
intent.
15 ` if (flow.syn_count > 10 && flow.ack_count Conditional if (flow.syn_count > 10 && flow.ack_count == 0)
== 0) {` branch — run {
code only
when
condition true.
16 ` score = std::max(score, 0.85);` Executable score = std::max(score, 0.85);
statement.
17 ` [Link].push_back("SYN_NO_ACK");` Executable [Link].push_back("SYN_NO_ACK");
statement.
18 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
19 ` // NULL scan` Comment NULL scan
documenting
intent.
20 ` if (flow.has_null_flags) {` Conditional if (flow.has_null_flags) {
branch — run
code only

Page 337 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
when
condition true.
21 ` score = std::max(score, 0.9);` Executable score = std::max(score, 0.9);
statement.
22 ` [Link].push_back("NULL_SCAN");` Executable [Link].push_back("NULL_SCAN");
statement.
23 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
24 ` // XMAS scan` Comment XMAS scan
documenting
intent.
25 ` if (flow.has_xmas_flags) {` Conditional if (flow.has_xmas_flags) {
branch — run
code only
when
condition true.
26 ` score = std::max(score, 0.9);` Executable score = std::max(score, 0.9);
statement.
27 ` [Link].push_back("XMAS_SCAN");` Executable [Link].push_back("XMAS_SCAN");
statement.
28 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
29 ` // Port scan: SYN then RST shortly after` Comment Port scan: SYN then RST shortly after
documenting
intent.
30 ` if (flow.syn_count > 0 && flow.rst_count > Conditional if (flow.syn_count > 0 && flow.rst_count > 0 &&
0 &&` branch — run
code only
when
condition true.
31 ` flow.packet_count <= 4 && Source code flow.packet_count <= 4 &&
!flow.has_full_handshake) {` line. !flow.has_full_handshake) {
32 ` score = std::max(score, 0.6);` Executable score = std::max(score, 0.6);
statement.
33 ` Executable [Link].push_back("HALF_OPEN_SCAN");
[Link].push_back("HALF_OPEN_SCAN");` statement.
34 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
35 ` // RST flood` Comment RST flood
documenting
intent.
36 ` if (flow.rst_count > 50) {` Conditional if (flow.rst_count > 50) {
branch — run
code only
when
condition true.

Page 338 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
37 ` score = std::max(score, 0.7);` Executable score = std::max(score, 0.7);
statement.
38 ` [Link].push_back("RST_FLOOD");` Executable [Link].push_back("RST_FLOOD");
statement.
39 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
40 ` // High SYN/ACK ratio in completed flow` Comment High SYN/ACK ratio in completed flow
documenting
intent.
41 ` if (flow.syn_ack_ratio > 5.0 && Conditional if (flow.syn_ack_ratio > 5.0 && flow.syn_count >
flow.syn_count > 20) {` branch — run 20) {
code only
when
condition true.
42 ` score = std::max(score, 0.8);` Executable score = std::max(score, 0.8);
statement.
43 ` Executable [Link].push_back("SYN_ACK_RATIO_HIGH"
[Link].push_back("SYN_ACK_RATIO_HIGH" statement. );
);`
44 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
45 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
46 ` else if ([Link] == PROTO_UDP) {` Source code else if ([Link] == PROTO_UDP) {
line.
47 ` if ([Link].dst_port == 53 \ \ [Link].src_port == 53) {`
48 ` if ([Link] > 4.5 && Conditional if ([Link] > 4.5 && flow.mean_pkt_size >
flow.mean_pkt_size > 300) {` branch — run 300) {
code only
when
condition true.
49 ` score = std::max(score, 0.75);` Executable score = std::max(score, 0.75);
statement.
50 ` Executable [Link].push_back("DNS_HIGH_ENTROPY");
[Link].push_back("DNS_HIGH_ENTROPY");` statement.
51 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
52 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
53 ` // DNS-specific (port 53)` Comment DNS-specific (port 53)
documenting
intent.

Page 339 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
54 ` if ([Link].dst_port == 53 \ \ [Link].src_port == 53) {`
55 ` // Very large mean packet size on DNS Comment Very large mean packet size on DNS =
= amplification answer` documenting amplification answer
intent.
56 ` if (flow.mean_pkt_size > 800) {` Conditional if (flow.mean_pkt_size > 800) {
branch — run
code only
when
condition true.
57 ` score = std::max(score, 0.7);` Executable score = std::max(score, 0.7);
statement.
58 ` Executable [Link].push_back("DNS_LARGE_RESPONS
[Link].push_back("DNS_LARGE_RESPONS statement. E");
E");`
59 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
60 ` // Burst of DNS traffic` Comment Burst of DNS traffic
documenting
intent.
61 ` if ([Link] > 100.0) {` Conditional if ([Link] > 100.0) {
branch — run
code only
when
condition true.
62 ` score = std::max(score, 0.6);` Executable score = std::max(score, 0.6);
statement.
63 ` Executable [Link].push_back("DNS_HIGH_RATE");
[Link].push_back("DNS_HIGH_RATE");` statement.
64 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
65 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
66 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
67 ` else if ([Link] == PROTO_ICMP) Source code else if ([Link] == PROTO_ICMP) {
{` line.
68 ` if ([Link] > 500.0) {` Conditional if ([Link] > 500.0) {
branch — run
code only
when
condition true.
69 ` score = std::max(score, 0.8);` Executable score = std::max(score, 0.8);
statement.
70 ` [Link].push_back("ICMP_FLOOD");` Executable [Link].push_back("ICMP_FLOOD");
statement.

Page 340 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
71 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
72 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
73 `` Blank line for Separator between code blocks.
readability.
74 ` [Link] = score;` Executable [Link] = score;
statement.
75 ` res.is_anomaly = score > 0.6;` Executable res.is_anomaly = score > 0.6;
statement.
76 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
77 ` ss << "syn=" << flow.syn_count` Source code ss << "syn=" << flow.syn_count
line.
78 ` << " ack=" << flow.ack_count` Source code << " ack=" << flow.ack_count
line.
79 ` << " rst=" << flow.rst_count` Source code << " rst=" << flow.rst_count
line.
80 ` << " null=" << flow.null_flag_count` Source code << " null=" << flow.null_flag_count
line.

Line Source Easy Explanation Technical Explanation


81 ` << " xmas=" << Executable statement. << " xmas=" <<
flow.xmas_flag_count;` flow.xmas_flag_count;
82 ` [Link] = [Link]();` Executable statement. [Link] = [Link]();
83 ` return res;` Exit function and give back a return res;
value.
84 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
85 `` Blank line for readability. Separator between code
blocks.
86 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/src/running_stats.cpp
Total lines: 5

Line Source Easy Explanation Technical Explanation


1 `#include "running_stats.h"` Import another header file into #include "running_stats.h"
this compilation unit.
2 `` Blank line for readability. Separator between code blocks.

Page 341 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


3 `namespace nads {` Start a named code region so namespace nads {
names do not clash globally.
4 `// Header-only hot path; translation Comment documenting intent. Header-only hot path; translation
unit for linkage consistency.` unit for linkage consistency.
5 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.

File: nads/src/stat_detector.cpp
Total lines: 53

Lin Source Easy Technical Explanation


e Explanation
1 `#include "stat_detector.h"` Import another #include "stat_detector.h"
header file into
this
compilation
unit.
2 `#include <sstream>` Import another #include <sstream>
header file into
this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
5 `` Blank line for Separator between code blocks.
readability.
6 `void StatisticalDetector::configure(const Config& cfg) Named void StatisticalDetector::configure(const
{` constant — Config& cfg) {
value should
not change.
7 ` use_adaptive_ = cfg.adaptive_thresholds;` Executable use_adaptive_ = cfg.adaptive_thresholds;
statement.
8 ` size_t w = Executable size_t w =
static_cast<size_t>(cfg.percentile_window);` statement. static_cast<size_t>(cfg.percentile_window
);
9 ` bps_ = AdaptiveBaseline(cfg.ewma_alpha, w);` Executable bps_ =
statement. AdaptiveBaseline(cfg.ewma_alpha, w);
10 ` pps_ = AdaptiveBaseline(cfg.ewma_alpha, w);` Executable pps_ =
statement. AdaptiveBaseline(cfg.ewma_alpha, w);
11 ` size_ = AdaptiveBaseline(cfg.ewma_alpha, w);` Executable size_ =
statement. AdaptiveBaseline(cfg.ewma_alpha, w);
12 ` duration_ = AdaptiveBaseline(cfg.ewma_alpha, Executable duration_ =
w);` statement. AdaptiveBaseline(cfg.ewma_alpha, w);

Page 342 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
13 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
14 `` Blank line for Separator between code blocks.
readability.
15 `DetectorResult StatisticalDetector::detect(const Build or return score 0-1, flags, detail string.
FlowRecord& flow) {` a detector
score result.
16 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
17 ` res.detector_name = "statistical";` Executable res.detector_name = "statistical";
statement.
18 `` Blank line for Separator between code blocks.
readability.
19 ` double dur_s = (flow.last_seen_us - Executable double dur_s = (flow.last_seen_us -
flow.first_seen_us) / 1e6;` statement. flow.first_seen_us) / 1e6;
20 ` double max_score = 0.0;` Executable double max_score = 0.0;
statement.
21 ` double sb = 0, sp = 0, ss = 0, sd = 0;` Executable double sb = 0, sp = 0, ss = 0, sd = 0;
statement.
22 `` Blank line for Separator between code blocks.
readability.
23 ` if (use_adaptive_) {` Conditional if (use_adaptive_) {
branch — run
code only
when condition
true.
24 ` sb = bps_.score([Link]);` Executable sb = bps_.score([Link]);
statement.
25 ` sp = pps_.score([Link]);` Executable sp = pps_.score([Link]);
statement.
26 ` ss = size_.score(flow.mean_pkt_size);` Executable ss = size_.score(flow.mean_pkt_size);
statement.
27 ` sd = duration_.score(dur_s);` Executable sd = duration_.score(dur_s);
statement.
28 ` max_score = std::max({sb, sp, ss, sd});` Executable max_score = std::max({sb, sp, ss, sd});
statement.
29 ` bps_.observe([Link]);` Executable bps_.observe([Link]);
statement.
30 ` pps_.observe([Link]);` Executable pps_.observe([Link]);
statement.
31 ` size_.observe(flow.mean_pkt_size);` Executable size_.observe(flow.mean_pkt_size);
statement.
32 ` duration_.observe(dur_s);` Executable duration_.observe(dur_s);
statement.
33 ` } else {` Source code } else {
line.

Page 343 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
34 ` if (bps_legacy_.ready()) sb = Compare Z-score or normalized score.
normalize_z(bps_legacy_.zscore([Link]), value to
THRESHOLD);` learned
baseline
statistically.
35 ` if (pps_legacy_.ready()) sp = Compare Z-score or normalized score.
normalize_z(pps_legacy_.zscore([Link]), value to
THRESHOLD);` learned
baseline
statistically.
36 ` if (size_legacy_.ready()) ss = Compare Z-score or normalized score.
normalize_z(size_legacy_.zscore(flow.mean_pkt_siz value to
e), THRESHOLD);` learned
baseline
statistically.
37 ` if (duration_legacy_.ready()) sd = Compare Z-score or normalized score.
normalize_z(duration_legacy_.zscore(dur_s), value to
THRESHOLD);` learned
baseline
statistically.
38 ` max_score = std::max({sb, sp, ss, sd});` Executable max_score = std::max({sb, sp, ss, sd});
statement.
39 ` bps_legacy_.update([Link]);` Executable bps_legacy_.update([Link]);
statement.
40 ` pps_legacy_.update([Link]);` Executable pps_legacy_.update([Link]);
statement.
41 ` size_legacy_.update(flow.mean_pkt_size);` Executable size_legacy_.update(flow.mean_pkt_size)
statement. ;
42 ` duration_legacy_.update(dur_s);` Executable duration_legacy_.update(dur_s);
statement.
43 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
44 `` Blank line for Separator between code blocks.
readability.
45 ` [Link] = max_score;` Executable [Link] = max_score;
statement.
46 ` res.is_anomaly = max_score > 0.6;` Executable res.is_anomaly = max_score > 0.6;
statement.
47 ` std::ostringstream oss;` Executable std::ostringstream oss;
statement.
48 ` oss << "bps=" << sb << " pps=" << sp << " size=" Executable oss << "bps=" << sb << " pps=" << sp << "
<< ss << " dur=" << sd;` statement. size=" << ss << " dur=" << sd;
49 ` [Link] = [Link]();` Executable [Link] = [Link]();
statement.
50 ` return res;` Exit function return res;
and give back
a value.
51 `}` Brace or C/C++ syntax structure.
parenthesis

Page 344 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
closing/openin
g a block.
52 `` Blank line for Separator between code blocks.
readability.
53 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/temporal_detector.cpp
Total lines: 41

Line Source Easy Technical Explanation


Explanation
1 `// temporal_detector.cpp - flags beacon-like Comment temporal_detector.cpp - flags beacon-like
(perfectly regular) timing` documenting (perfectly regular) timing
intent.
2 `#include "temporal_detector.h"` Import another #include "temporal_detector.h"
header file into
this compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file into
this compilation
unit.
4 `#include <cmath>` Import another #include <cmath>
header file into
this compilation
unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
7 `` Blank line for Separator between code blocks.
readability.
8 `DetectorResult Build or return score 0-1, flags, detail string.
TemporalDetector::detect(const FlowRecord& a detector
flow) {` score result.
9 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
10 ` res.detector_name = "temporal";` Executable res.detector_name = "temporal";
statement.
11 `` Blank line for Separator between code blocks.
readability.
12 ` if (flow.iat_buffer.size() < 5 \ \ flow.mean_iat <= 0) {`

Page 345 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
13 ` [Link] = 0.0;` Executable [Link] = 0.0;
statement.
14 ` return res;` Exit function return res;
and give back
a value.
15 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
16 `` Blank line for Separator between code blocks.
readability.
17 ` double cv = flow.stddev_iat / Executable double cv = flow.stddev_iat / flow.mean_iat;
flow.mean_iat;` statement.
18 ` double score = 0.0;` Executable double score = 0.0;
statement.
19 `` Blank line for Separator between code blocks.
readability.
20 ` if (cv < 0.05 && flow.packet_count > 8) {` Conditional if (cv < 0.05 && flow.packet_count > 8) {
branch — run
code only when
condition true.
21 ` score = 0.9; // extremely regular -> Source code score = 0.9; // extremely regular ->
almost certainly automated` line. almost certainly automated
22 ` Executable [Link].push_back("BEACON_PATTERN");
[Link].push_back("BEACON_PATTERN");` statement.
23 ` } else if (cv < 0.1 && flow.packet_count > Conditional } else if (cv < 0.1 && flow.packet_count > 8) {
8) {` branch — run
code only when
condition true.
24 ` score = 0.7;` Executable score = 0.7;
statement.
25 ` Executable [Link].push_back("REGULAR_TIMING");
[Link].push_back("REGULAR_TIMING");` statement.
26 ` } else if (cv < 0.2 && flow.packet_count > Conditional } else if (cv < 0.2 && flow.packet_count > 16)
16) {` branch — run {
code only when
condition true.
27 ` score = 0.4;` Executable score = 0.4;
statement.
28 ` Executable [Link].push_back("LIKELY_PERIODIC");
[Link].push_back("LIKELY_PERIODIC");` statement.
29 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
30 `` Blank line for Separator between code blocks.
readability.
31 ` [Link] = score;` Executable [Link] = score;
statement.
32 ` res.is_anomaly = score > 0.6;` Executable res.is_anomaly = score > 0.6;
statement.

Page 346 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
33 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
34 ` ss << "cv=" << std::round(cv*1000)/1000` Source code ss << "cv=" << std::round(cv*1000)/1000
line.
35 ` << " mean_iat_ms=" << Source code << " mean_iat_ms=" <<
static_cast<int>(flow.mean_iat / 1000)` line. static_cast<int>(flow.mean_iat / 1000)
36 ` << " n=" << flow.iat_buffer.size();` Executable << " n=" << flow.iat_buffer.size();
statement.
37 ` [Link] = [Link]();` Executable [Link] = [Link]();
statement.
38 ` return res;` Exit function return res;
and give back
a value.
39 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
40 `` Blank line for Separator between code blocks.
readability.
41 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/threat_classifier.cpp
Total lines: 202

Line Source Easy Technical Explanation


Explanation
1 `// threat_classifier.cpp - rule-based attack Comment threat_classifier.cpp - rule-based attack
naming` documenting naming
intent.
2 `#include "threat_classifier.h"` Import another #include "threat_classifier.h"
header file into
this compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file into
this compilation
unit.
4 `#include <unordered_set>` Import another #include <unordered_set>
header file into
this compilation
unit.
5 `` Blank line for Separator between code blocks.
readability.
6 `namespace nads` Start a named namespace nads
code region so

Page 347 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
names do not
clash globally.
7 `{` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
8 `` Blank line for Separator between code blocks.
readability.
9 ` static bool has_flag(const Build or return score 0-1, flags, detail string.
std::vector<DetectorResult> &results,` a detector
score result.
10 ` const std::string &want)` Named const std::string &want)
constant —
value should
not change.
11 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
12 ` for (const auto &r : results)` Loop over for (const auto &r : results)
items or until
condition
changes.
13 ` for (const auto &f : [Link])` Loop over for (const auto &f : [Link])
items or until
condition
changes.
14 ` if (f == want)` Conditional if (f == want)
branch — run
code only when
condition true.
15 ` return true;` Exit function return true;
and give back
a value.
16 ` return false;` Exit function return false;
and give back
a value.
17 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
18 `` Blank line for Separator between code blocks.
readability.
19 ` static double scoreof(const Build or return score 0-1, flags, detail string.
std::vector<DetectorResult> &results,` a detector
score result.
20 ` const std::string &name)` Named const std::string &name)
constant —
value should
not change.
21 ` {` Brace or C/C++ syntax structure.
parenthesis

Page 348 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
22 ` for (const auto &r : results)` Loop over for (const auto &r : results)
items or until
condition
changes.
23 ` if (r.detector_name == name)` Conditional if (r.detector_name == name)
branch — run
code only when
condition true.
24 ` return [Link];` Exit function return [Link];
and give back
a value.
25 ` return 0.0;` Exit function return 0.0;
and give back
a value.
26 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
27 `` Blank line for Separator between code blocks.
readability.
28 ` static void fill_mitre(ThreatClassification& Source code static void fill_mitre(ThreatClassification& c)
c)` line.
29 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
30 ` if (c.attack_type.find("SYN Flood") != Conditional if (c.attack_type.find("SYN Flood") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
31 ` Executable c.mitre_techniques.push_back("T1498");
c.mitre_techniques.push_back("T1498");` statement.
32 ` c.mitre_tactics.push_back("Impact");` Executable c.mitre_tactics.push_back("Impact");
statement.
33 ` } else if (c.attack_type.find("Scan") != Conditional } else if (c.attack_type.find("Scan") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
34 ` Executable c.mitre_techniques.push_back("T1046");
c.mitre_techniques.push_back("T1046");` statement.
35 ` Executable c.mitre_tactics.push_back("Discovery");
c.mitre_tactics.push_back("Discovery");` statement.
36 ` } else if (c.attack_type.find("Beacon") != Conditional } else if (c.attack_type.find("Beacon") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
37 ` Executable c.mitre_techniques.push_back("T1071");
c.mitre_techniques.push_back("T1071");` statement.

Page 349 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
38 ` Executable c.mitre_tactics.push_back("Command and
c.mitre_tactics.push_back("Command and statement. Control");
Control");`
39 ` } else if (c.attack_type.find("Lateral") != Conditional } else if (c.attack_type.find("Lateral") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
40 ` Executable c.mitre_techniques.push_back("T1021");
c.mitre_techniques.push_back("T1021");` statement.
41 ` c.mitre_tactics.push_back("Lateral Executable c.mitre_tactics.push_back("Lateral
Movement");` statement. Movement");
42 ` } else if (c.attack_type.find("Brute") != Conditional } else if (c.attack_type.find("Brute") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
43 ` Executable c.mitre_techniques.push_back("T1110");
c.mitre_techniques.push_back("T1110");` statement.
44 ` Executable c.mitre_tactics.push_back("Credential
c.mitre_tactics.push_back("Credential statement. Access");
Access");`
45 ` } else if (c.attack_type.find("DNS") != Conditional } else if (c.attack_type.find("DNS") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
46 ` Executable c.mitre_techniques.push_back("T1071.004");
c.mitre_techniques.push_back("T1071.004");` statement.
47 ` Executable c.mitre_tactics.push_back("Command and
c.mitre_tactics.push_back("Command and statement. Control");
Control");`
48 ` } else if (c.attack_type.find("Tunnel") != Conditional } else if (c.attack_type.find("Tunnel") !=
std::string::npos) {` branch — run std::string::npos) {
code only when
condition true.
49 ` Executable c.mitre_techniques.push_back("T1572");
c.mitre_techniques.push_back("T1572");` statement.
50 ` Executable c.mitre_tactics.push_back("Command and
c.mitre_tactics.push_back("Command and statement. Control");
Control");`
51 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
52 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
53 `` Blank line for Separator between code blocks.
readability.
54 ` static Severity grade(double s)` Source code static Severity grade(double s)
line.
55 ` {` Brace or C/C++ syntax structure.
parenthesis

Page 350 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
56 ` if (s >= 0.9)` Conditional if (s >= 0.9)
branch — run
code only when
condition true.
57 ` return Severity::CRITICAL;` Exit function return Severity::CRITICAL;
and give back
a value.
58 ` if (s >= 0.75)` Conditional if (s >= 0.75)
branch — run
code only when
condition true.
59 ` return Severity::HIGH;` Exit function return Severity::HIGH;
and give back
a value.
60 ` if (s >= 0.5)` Conditional if (s >= 0.5)
branch — run
code only when
condition true.
61 ` return Severity::MEDIUM;` Exit function return Severity::MEDIUM;
and give back
a value.
62 ` if (s >= 0.3)` Conditional if (s >= 0.3)
branch — run
code only when
condition true.
63 ` return Severity::LOW;` Exit function return Severity::LOW;
and give back
a value.
64 ` return Severity::INFO;` Exit function return Severity::INFO;
and give back
a value.
65 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
66 `` Blank line for Separator between code blocks.
readability.
67 ` ThreatClassification Source code ThreatClassification
ThreatClassifier::classify(` line. ThreatClassifier::classify(
68 ` const FlowRecord &flow,` Named const FlowRecord &flow,
constant —
value should
not change.
69 ` const std::vector<DetectorResult> Build or return score 0-1, flags, detail string.
&results,` a detector
score result.
70 ` double final_score)` Source code double final_score)
line.
71 ` {` Brace or C/C++ syntax structure.
parenthesis

Page 351 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
72 ` ThreatClassification c;` Executable ThreatClassification c;
statement.
73 ` [Link] = final_score;` Executable [Link] = final_score;
statement.
74 ` [Link] = grade(final_score);` Executable [Link] = grade(final_score);
statement.
75 `` Blank line for Separator between code blocks.
readability.
76 ` auto finish = [&](ThreatClassification Source code auto finish = [&](ThreatClassification out) ->
out) -> ThreatClassification {` line. ThreatClassification {
77 ` fill_mitre(out);` Executable fill_mitre(out);
statement.
78 ` for (const auto& r : results) {` Loop over for (const auto& r : results) {
items or until
condition
changes.
79 ` if ([Link] > 0.25) {` Conditional if ([Link] > 0.25) {
branch — run
code only when
condition true.
80 ` std::ostringstream ev;` Executable std::ostringstream ev;
statement.

Line Source Easy Technical Explanation


Explanation
81 ` ev << r.detector_name << Executable ev << r.detector_name << "=" <<
"=" << [Link];` statement. [Link];
82 ` Executable [Link].push_back([Link]());
[Link].push_back([Link]());` statement.
83 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
84 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
85 ` return out;` Exit function and return out;
give back a value.
86 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
87 `` Blank line for Separator between code blocks.
readability.
88 ` // Rule 1: SYN Flood DDoS` Comment Rule 1: SYN Flood DDoS
documenting intent.
89 ` if ((has_flag(results, \ has_flag(results,
"SYN_NO_ACK") \ "SYN_ACK_RATIO_HIGH")) &&`

Page 352 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
90 ` scoreof(results, "volume") > 0.7)` Source code line. scoreof(results, "volume") > 0.7)
91 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
92 ` c.attack_type = "SYN Flood Executable c.attack_type = "SYN Flood DDoS";
DDoS";` statement.
93 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
94 ` [Link] = "Massive SYN Source code line. [Link] = "Massive SYN packets
packets with no ACK responses indicate with no ACK responses indicate a SYN
a SYN flood "` flood "
95 ` "attack consuming Executable "attack consuming server connection
server connection resources.";` statement. resources.";
96 ` [Link] = "Enable Source code line. [Link] = "Enable SYN
SYN cookies; rate-limit incoming SYNs; cookies; rate-limit incoming SYNs;
consider "` consider "
97 ` "blocking source IP Executable "blocking source IP at the firewall.";
at the firewall.";` statement.
98 ` return finish(c);` Exit function and return finish(c);
give back a value.
99 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
100 `` Blank line for Separator between code blocks.
readability.
101 ` // Rule 2: NULL / XMAS scan` Comment Rule 2: NULL / XMAS scan
documenting intent.
102 ` if (has_flag(results, "NULL_SCAN") \ has_flag(results, "XMAS_SCAN"))`
\
103 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
104 ` c.attack_type = has_flag(results, Executable c.attack_type = has_flag(results,
"NULL_SCAN") ? "TCP NULL Scan" : statement. "NULL_SCAN") ? "TCP NULL Scan" :
"TCP XMAS Scan";` "TCP XMAS Scan";
105 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
106 ` [Link] = "Stealth port scan Executable [Link] = "Stealth port scan / OS
/ OS fingerprinting using malformed TCP statement. fingerprinting using malformed TCP
flags.";` flags.";
107 ` [Link] = "Block Executable [Link] = "Block source IP.
source IP. Inspect firewall logs for related statement. Inspect firewall logs for related
probes.";` probes.";
108 ` return finish(c);` Exit function and return finish(c);
give back a value.
109 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 353 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
110 `` Blank line for Separator between code blocks.
readability.
111 ` // Rule 3: Half-open / SYN port Comment Rule 3: Half-open / SYN port scan
scan` documenting intent.
112 ` if (has_flag(results, \ has_flag(results, "DEGREE_SPIKE"))`
"HALF_OPEN_SCAN") \
113 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
114 ` c.attack_type = "TCP Port Executable c.attack_type = "TCP Port Scan";
Scan";` statement.
115 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
116 ` [Link] = "Source host Source code line. [Link] = "Source host opening
opening connections to many connections to many destinations /
destinations / ports "` ports "
117 ` "without completing Executable "without completing handshake.";
handshake.";` statement.
118 ` [Link] = "Quarantine Executable [Link] = "Quarantine the
the source host; review for statement. source host; review for compromise.";
compromise.";`
119 ` return finish(c);` Exit function and return finish(c);
give back a value.
120 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
121 `` Blank line for Separator between code blocks.
readability.
122 ` // Rule 4: ICMP flood / sweep` Comment Rule 4: ICMP flood / sweep
documenting intent.
123 ` if (has_flag(results, Conditional branch if (has_flag(results, "ICMP_FLOOD"))
"ICMP_FLOOD"))` — run code only
when condition true.
124 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
125 ` c.attack_type = "ICMP Flood / Executable c.attack_type = "ICMP Flood / Ping
Ping Sweep";` statement. Sweep";
126 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
127 ` [Link] = "High volume of Executable [Link] = "High volume of ICMP
ICMP packets indicates a flood or statement. packets indicates a flood or sweep.";
sweep.";`
128 ` [Link] = "Rate-limit Executable [Link] = "Rate-limit ICMP
ICMP at the perimeter.";` statement. at the perimeter.";

Page 354 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
129 ` return finish(c);` Exit function and return finish(c);
give back a value.
130 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
131 `` Blank line for Separator between code blocks.
readability.
132 ` // Rule 5: DNS amplification / Comment Rule 5: DNS amplification / abuse
abuse` documenting intent.
133 ` if (has_flag(results, \ has_flag(results, "DNS_HIGH_RATE"))`
"DNS_LARGE_RESPONSE") \
134 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
135 ` c.attack_type = "DNS Anomaly / Executable c.attack_type = "DNS Anomaly /
Amplification";` statement. Amplification";
136 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
137 ` [Link] = "Unusual DNS Executable [Link] = "Unusual DNS response
response sizes or query rate. Possible statement. sizes or query rate. Possible
amplification.";` amplification.";
138 ` [Link] = "Inspect Executable [Link] = "Inspect DNS logs;
DNS logs; rate-limit recursive queries.";` statement. rate-limit recursive queries.";
139 ` return finish(c);` Exit function and return finish(c);
give back a value.
140 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
141 `` Blank line for Separator between code blocks.
readability.
142 ` // Rule 6: Beacon (regular C&C Comment Rule 6: Beacon (regular C&C check-in)
check-in)` documenting intent.
143 ` if (has_flag(results, \ has_flag(results,
"BEACON_PATTERN") \ "REGULAR_TIMING"))`
144 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
145 ` c.attack_type = "C&C Beacon Executable c.attack_type = "C&C Beacon Pattern";
Pattern";` statement.
146 ` [Link] = Severity::CRITICAL;` Executable [Link] = Severity::CRITICAL;
statement.
147 ` [Link] = "Highly regular Source code line. [Link] = "Highly regular outbound
outbound communication suggests communication suggests automated "
automated "`
148 ` "command-and-control Executable "command-and-control beaconing
beaconing (malware).";` statement. (malware).";

Page 355 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
149 ` [Link] = "Isolate Source code line. [Link] = "Isolate host;
host; capture full PCAP for forensic capture full PCAP for forensic analysis;
analysis; check "` check "
150 ` "for persistence Executable "for persistence mechanisms.";
mechanisms.";` statement.
151 ` return finish(c);` Exit function and return finish(c);
give back a value.
152 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
153 `` Blank line for Separator between code blocks.
readability.
154 ` // Rule 7: Per-host bandwidth Comment Rule 7: Per-host bandwidth deviation
deviation` documenting intent.
155 ` if (has_flag(results, Conditional branch if (has_flag(results,
"HOST_BPS_DEVIATION") && — run code only "HOST_BPS_DEVIATION") &&
scoreof(results, "baseline") > 0.7)` when condition true. scoreof(results, "baseline") > 0.
156 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
157 ` // Brute-force on common login Comment Brute-force on common login ports
ports` documenting intent.
158 ` if ([Link].dst_port == 22 \ \ [Link].dst_port == 3389 \
159 ` [Link].dst_port == 21 \ \ [Link].dst_port == 23)`
160 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Line Source Easy Technical Explanation


Explanation
161 ` c.attack_type = "Brute-Force Executable c.attack_type = "Brute-Force Login
Login Attempt";` statement. Attempt";
162 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
163 ` [Link] = "Repeated short Executable [Link] = "Repeated short flows to
flows to a known-login service.";` statement. a known-login service.";
164 ` [Link] = "Enable Executable [Link] = "Enable fail2ban /
fail2ban / account lockout; require key- statement. account lockout; require key-based
based auth.";` auth.";
165 ` return finish(c);` Exit function and return finish(c);
give back a value.
166 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
167 ` c.attack_type = "Behavioral Executable c.attack_type = "Behavioral Deviation";
Deviation";` statement.

Page 356 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
168 ` [Link] = Severity::MEDIUM;` Executable [Link] = Severity::MEDIUM;
statement.
169 ` [Link] = "Host volume / Executable [Link] = "Host volume / pattern
pattern significantly deviates from its own statement. significantly deviates from its own
baseline.";` baseline.";
170 ` [Link] = "Investigate Executable [Link] = "Investigate the
the host for new processes / suspicious statement. host for new processes / suspicious
activity.";` activity.";
171 ` return finish(c);` Exit function and return finish(c);
give back a value.
172 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
173 `` Blank line for Separator between code blocks.
readability.
174 ` // Rule 8: Fast peer expansion Comment Rule 8: Fast peer expansion (lateral
(lateral movement)` documenting movement)
intent.
175 ` if (has_flag(results, Conditional if (has_flag(results,
"FAST_PEER_EXPANSION"))` branch — run "FAST_PEER_EXPANSION"))
code only when
condition true.
176 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
177 ` c.attack_type = "Suspected Executable c.attack_type = "Suspected Lateral
Lateral Movement";` statement. Movement";
178 ` [Link] = Severity::CRITICAL;` Executable [Link] = Severity::CRITICAL;
statement.
179 ` [Link] = "A single host is Source code line. [Link] = "A single host is rapidly
rapidly contacting many new internal contacting many new internal peers - "
peers - "`
180 ` "consistent with worm Executable "consistent with worm spreading or
spreading or attacker pivoting.";` statement. attacker pivoting.";
181 ` [Link] = "Quarantine Executable [Link] = "Quarantine
immediately; force credential rotation.";` statement. immediately; force credential rotation.";
182 ` return finish(c);` Exit function and return finish(c);
give back a value.
183 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
184 `` Blank line for Separator between code blocks.
readability.
185 ` // Rule 9: Unexpected entropy on Comment Rule 9: Unexpected entropy on plaintext
plaintext port = tunneling` documenting port = tunneling
intent.
186 ` if (has_flag(results, Conditional if (has_flag(results,
"UNEXPECTED_HIGH_ENTROPY"))` branch — run "UNEXPECTED_HIGH_ENTROPY"))

Page 357 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
code only when
condition true.
187 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
188 ` c.attack_type = "Suspected Executable c.attack_type = "Suspected Tunneling /
Tunneling / Exfiltration";` statement. Exfiltration";
189 ` [Link] = Severity::HIGH;` Executable [Link] = Severity::HIGH;
statement.
190 ` [Link] = "Encrypted-looking Executable [Link] = "Encrypted-looking
payload over a normally-plaintext port.";` statement. payload over a normally-plaintext port.";
191 ` [Link] = "Capture Executable [Link] = "Capture flow
flow PCAP; inspect for tunneled C2 or statement. PCAP; inspect for tunneled C2 or data
data exfil.";` exfil.";
192 ` return finish(c);` Exit function and return finish(c);
give back a value.
193 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
194 `` Blank line for Separator between code blocks.
readability.
195 ` // Default: unknown` Comment Default: unknown
documenting
intent.
196 ` c.attack_type = "Unclassified Executable c.attack_type = "Unclassified Anomaly";
Anomaly";` statement.
197 ` [Link] = "Multiple detectors Executable [Link] = "Multiple detectors fired
fired but no specific attack signature statement. but no specific attack signature
matched.";` matched.";
198 ` [Link] = "Investigate the Executable [Link] = "Investigate the
flow manually; correlate with other statement. flow manually; correlate with other
alerts.";` alerts.";
199 ` return finish(c);` Exit function and return finish(c);
give back a value.
200 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
201 `` Blank line for Separator between code blocks.
readability.
202 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/src/[Link]
Total lines: 27

Page 358 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `// [Link] - shared helper Comment documenting [Link] - shared helper
implementations (ip_to_string, intent. implementations (ip_to_string,
severity_to_string)` severity_to_string)
2 `#include "types.h"` Import another header #include "types.h"
file into this compilation
unit.
3 `#include <cstdio>` Import another header #include <cstdio>
file into this compilation
unit.
4 `` Blank line for readability. Separator between code blocks.
5 `namespace nads {` Start a named code namespace nads {
region so names do not
clash globally.
6 `` Blank line for readability. Separator between code blocks.
7 `std::string ip_to_string(uint32_t ip_be) Source code line. std::string ip_to_string(uint32_t ip_be)
{` {
8 ` // ip_be is in network byte order Comment documenting ip_be is in network byte order (big
(big endian) as read from packet.` intent. endian) as read from packet.
9 ` // We render bytes most-significant Comment documenting We render bytes most-significant first.
first.` intent.
10 ` unsigned char* b = Executable statement. unsigned char* b =
reinterpret_cast<unsigned reinterpret_cast<unsigned
char*>(&ip_be);` char*>(&ip_be);
11 ` char buf[24];` Executable statement. char buf[24];
12 ` std::snprintf(buf, sizeof(buf), Executable statement. std::snprintf(buf, sizeof(buf),
"%u.%u.%u.%u", b[0], b[1], b[2], "%u.%u.%u.%u", b[0], b[1], b[2],
b[3]);` b[3]);
13 ` return std::string(buf);` Exit function and give return std::string(buf);
back a value.
14 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
15 `` Blank line for readability. Separator between code blocks.
16 `std::string severity_to_string(Severity Source code line. std::string severity_to_string(Severity
s) {` s) {
17 ` switch (s) {` Source code line. switch (s) {
18 ` case Severity::INFO: return Executable statement. case Severity::INFO: return
"INFO";` "INFO";
19 ` case Severity::LOW: return Executable statement. case Severity::LOW: return
"LOW";` "LOW";
20 ` case Severity::MEDIUM: return Executable statement. case Severity::MEDIUM: return
"MEDIUM";` "MEDIUM";
21 ` case Severity::HIGH: return Executable statement. case Severity::HIGH: return
"HIGH";` "HIGH";
22 ` case Severity::CRITICAL: return Executable statement. case Severity::CRITICAL: return
"CRITICAL";` "CRITICAL";
23 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
24 ` return "UNKNOWN";` Exit function and give return "UNKNOWN";
back a value.

Page 359 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


25 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.
26 `` Blank line for readability. Separator between code blocks.
27 `} // namespace nads` End of nads namespace. } // namespace nads

File: nads/src/volume_detector.cpp
Total lines: 130

Line Source Easy Technical Explanation


Explanation
1 `#include "volume_detector.h"` Import another #include "volume_detector.h"
header file into
this compilation
unit.
2 `#include <algorithm>` Import another #include <algorithm>
header file into
this compilation
unit.
3 `#include <sstream>` Import another #include <sstream>
header file into
this compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `namespace nads {` Start a named namespace nads {
code region so
names do not
clash globally.
6 `` Blank line for Separator between code blocks.
readability.
7 `VolumeDetector::VolumeDetector(const Named VolumeDetector::VolumeDetector(const
Config& cfg)` constant — Config& cfg)
value should
not change.
8 ` : hist_pps_(cfg.ewma_alpha, Source code : hist_pps_(cfg.ewma_alpha,
static_cast<size_t>(cfg.percentile_window)),` line. static_cast<size_t>(cfg.percentile_window)),
9 ` hist_syn_(cfg.ewma_alpha, Source code hist_syn_(cfg.ewma_alpha,
static_cast<size_t>(cfg.percentile_window)),` line. static_cast<size_t>(cfg.percentile_window)),
10 ` cfg_(cfg) {` Source code cfg_(cfg) {
line.
11 ` for (auto& b : buckets_) b = Bucket{};` Loop over for (auto& b : buckets_) b = Bucket{};
items or until
condition
changes.
12 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Page 360 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
13 `` Blank line for Separator between code blocks.
readability.
14 `int Named int
VolumeDetector::bucket_index_for(int64_t constant — VolumeDetector::bucket_index_for(int64_t
ts_us) const {` value should ts_us) const {
not change.
15 ` int64_t sec = ts_us / 1000000LL;` Executable int64_t sec = ts_us / 1000000LL;
statement.
16 ` return static_cast<int>(sec % Exit function return static_cast<int>(sec %
NUM_BUCKETS);` and give back NUM_BUCKETS);
a value.
17 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
18 `` Blank line for Separator between code blocks.
readability.
19 `void Source code void
VolumeDetector::rotate_if_needed(int64_t line. VolumeDetector::rotate_if_needed(int64_t
ts_us) {` ts_us) {
20 ` int64_t cur_id = ts_us / 1000000LL;` Executable int64_t cur_id = ts_us / 1000000LL;
statement.
21 ` if (cur_id == newest_id_) return;` Conditional if (cur_id == newest_id_) return;
branch — run
code only when
condition true.
22 ` int idx = bucket_index_for(ts_us);` Executable int idx = bucket_index_for(ts_us);
statement.
23 ` Bucket& b = buckets_[idx];` Executable Bucket& b = buckets_[idx];
statement.
24 ` if (b.bucket_id != cur_id) {` Conditional if (b.bucket_id != cur_id) {
branch — run
code only when
condition true.
25 ` [Link] = 0;` Executable [Link] = 0;
statement.
26 ` [Link] = 0;` Executable [Link] = 0;
statement.
27 ` [Link] = 0;` Executable [Link] = 0;
statement.
28 ` b.new_flows = 0;` Executable b.new_flows = 0;
statement.
29 ` b.bucket_id = cur_id;` Executable b.bucket_id = cur_id;
statement.
30 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
31 ` newest_id_ = cur_id;` Executable newest_id_ = cur_id;
statement.

Page 361 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
32 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
33 `` Blank line for Separator between code blocks.
readability.
34 `void VolumeDetector::on_packet(const Named void VolumeDetector::on_packet(const
PacketInfo& pkt) {` constant — PacketInfo& pkt) {
value should
not change.
35 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
36 ` rotate_if_needed(pkt.timestamp_us);` Executable rotate_if_needed(pkt.timestamp_us);
statement.
37 ` int idx = Executable int idx =
bucket_index_for(pkt.timestamp_us);` statement. bucket_index_for(pkt.timestamp_us);
38 ` Bucket& b = buckets_[idx];` Executable Bucket& b = buckets_[idx];
statement.
39 ` [Link]++;` Executable [Link]++;
statement.
40 ` [Link] += [Link];` Executable [Link] += [Link];
statement.
41 ` if ([Link] == PROTO_TCP && Conditional if ([Link] == PROTO_TCP &&
(pkt.tcp_flags & TCP_SYN)) {` branch — run (pkt.tcp_flags & TCP_SYN)) {
code only when
condition true.
42 ` [Link]++;` Executable [Link]++;
statement.
43 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
44 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
45 `` Blank line for Separator between code blocks.
readability.
46 `void VolumeDetector::on_new_flow() {` Source code void VolumeDetector::on_new_flow() {
line.
47 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
48 ` int idx = bucket_index_for(now_us());` Executable int idx = bucket_index_for(now_us());
statement.
49 ` buckets_[idx].new_flows++;` Executable buckets_[idx].new_flows++;
statement.

Page 362 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
50 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
51 `` Blank line for Separator between code blocks.
readability.
52 `VolumeDetector::Rates Named VolumeDetector::Rates
VolumeDetector::current_rates() const {` constant — VolumeDetector::current_rates() const {
value should
not change.
53 ` std::lock_guard<std::mutex> lock(mtx_);` Lock a mutex RAII mutex lock.
so only one
thread uses
shared data at
a time.
54 ` int64_t cur_id = newest_id_;` Executable int64_t cur_id = newest_id_;
statement.
55 ` if (cur_id < 0) return {};` Conditional if (cur_id < 0) return {};
branch — run
code only when
condition true.
56 ` int64_t oldest = cur_id - NUM_BUCKETS Executable int64_t oldest = cur_id - NUM_BUCKETS +
+ 1;` statement. 1;
57 ` uint64_t total_p = 0, total_b = 0, total_s = Executable uint64_t total_p = 0, total_b = 0, total_s = 0,
0, total_nf = 0;` statement. total_nf = 0;
58 ` int valid_secs = 0;` Executable int valid_secs = 0;
statement.
59 ` for (const auto& b : buckets_) {` Loop over for (const auto& b : buckets_) {
items or until
condition
changes.
60 ` if (b.bucket_id >= oldest && Conditional if (b.bucket_id >= oldest && b.bucket_id <=
b.bucket_id <= cur_id) {` branch — run cur_id) {
code only when
condition true.
61 ` total_p += [Link];` Executable total_p += [Link];
statement.
62 ` total_b += [Link];` Executable total_b += [Link];
statement.
63 ` total_s += [Link];` Executable total_s += [Link];
statement.
64 ` total_nf += b.new_flows;` Executable total_nf += b.new_flows;
statement.
65 ` valid_secs++;` Executable valid_secs++;
statement.
66 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
67 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 363 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening
a block.
68 ` if (valid_secs == 0) valid_secs = 1;` Conditional if (valid_secs == 0) valid_secs = 1;
branch — run
code only when
condition true.
69 ` Rates r;` Executable Rates r;
statement.
70 ` [Link] = static_cast<double>(total_p) / Executable [Link] = static_cast<double>(total_p) /
valid_secs;` statement. valid_secs;
71 ` [Link] = static_cast<double>(total_b) * 8.0 Executable [Link] = static_cast<double>(total_b) * 8.0 /
/ valid_secs;` statement. valid_secs;
72 ` r.syn_pps = static_cast<double>(total_s) Executable r.syn_pps = static_cast<double>(total_s) /
/ valid_secs;` statement. valid_secs;
73 ` r.new_flow_per_sec = Executable r.new_flow_per_sec =
static_cast<double>(total_nf) / valid_secs;` statement. static_cast<double>(total_nf) / valid_secs;
74 ` return r;` Exit function return r;
and give back
a value.
75 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
76 `` Blank line for Separator between code blocks.
readability.
77 `DetectorResult VolumeDetector::detect() {` Build or return score 0-1, flags, detail string.
a detector
score result.
78 ` DetectorResult res;` Build or return score 0-1, flags, detail string.
a detector
score result.
79 ` res.detector_name = "volume";` Executable res.detector_name = "volume";
statement.
80 ` Rates r = current_rates();` Executable Rates r = current_rates();
statement.

Line Source Easy Technical Explanation


Explanation
81 `` Blank line for Separator between code blocks.
readability.
82 ` double zp = 0.0, zs = 0.0;` Executable double zp = 0.0, zs = 0.0;
statement.
83 ` if (cfg_.adaptive_thresholds) {` Conditional if (cfg_.adaptive_thresholds) {
branch — run
code only when
condition true.
84 ` zp = hist_pps_.score([Link], 5);` Executable zp = hist_pps_.score([Link], 5);
statement.
85 ` zs = hist_syn_.score(r.syn_pps, 5);` Executable zs = hist_syn_.score(r.syn_pps, 5);
statement.

Page 364 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
86 ` } else {` Source code } else {
line.
87 ` if (hist_pps_legacy_.ready(5))` Conditional if (hist_pps_legacy_.ready(5))
branch — run
code only when
condition true.
88 ` zp = Compare value Z-score or normalized score.
normalize_z(hist_pps_legacy_.zscore([Link]), to learned
3.0);` baseline
statistically.
89 ` if (hist_syn_legacy_.ready(5))` Conditional if (hist_syn_legacy_.ready(5))
branch — run
code only when
condition true.
90 ` zs = Compare value Z-score or normalized score.
normalize_z(hist_syn_legacy_.zscore(r.syn_pps), to learned
3.0);` baseline
statistically.
91 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
92 `` Blank line for Separator between code blocks.
readability.
93 ` double hard = 0.0;` Executable double hard = 0.0;
statement.
94 ` const double syn_thr = Named const double syn_thr =
cfg_.syn_flood_threshold_pps;` constant — cfg_.syn_flood_threshold_pps;
value should
not change.
95 ` const double pkt_thr = Named const double pkt_thr =
cfg_.packet_flood_threshold_pps;` constant — cfg_.packet_flood_threshold_pps;
value should
not change.
96 ` if (r.syn_pps > syn_thr * 2) hard = Conditional if (r.syn_pps > syn_thr * 2) hard =
std::max(hard, 0.97);` branch — run std::max(hard, 0.97);
code only when
condition true.
97 ` else if (r.syn_pps > syn_thr) hard = Executable else if (r.syn_pps > syn_thr) hard =
std::max(hard, 0.85);` statement. std::max(hard, 0.85);
98 ` else if (r.syn_pps > syn_thr / 5) hard = Executable else if (r.syn_pps > syn_thr / 5) hard =
std::max(hard, 0.70);` statement. std::max(hard, 0.70);
99 `` Blank line for Separator between code blocks.
readability.
100 ` if ([Link] > pkt_thr * 2) hard = Conditional if ([Link] > pkt_thr * 2) hard =
std::max(hard, 0.90);` branch — run std::max(hard, 0.90);
code only when
condition true.
101 ` else if ([Link] > pkt_thr) hard = Executable else if ([Link] > pkt_thr) hard =
std::max(hard, 0.75);` statement. std::max(hard, 0.75);
102 ` else if ([Link] > pkt_thr / 4) hard = Executable else if ([Link] > pkt_thr / 4) hard =
std::max(hard, 0.60);` statement. std::max(hard, 0.60);

Page 365 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
103 `` Blank line for Separator between code blocks.
readability.
104 ` if (r.new_flow_per_sec > 100.0) hard = Conditional if (r.new_flow_per_sec > 100.0) hard =
std::max(hard, 0.85);` branch — run std::max(hard, 0.85);
code only when
condition true.
105 ` else if (r.new_flow_per_sec > 20.0) hard = Executable else if (r.new_flow_per_sec > 20.0) hard
std::max(hard, 0.70);` statement. = std::max(hard, 0.70);
106 `` Blank line for Separator between code blocks.
readability.
107 ` [Link] = std::max({zp, zs, hard});` Executable [Link] = std::max({zp, zs, hard});
statement.
108 ` res.is_anomaly = [Link] > 0.5;` Executable res.is_anomaly = [Link] > 0.5;
statement.
109 `` Blank line for Separator between code blocks.
readability.
110 ` if (r.syn_pps > 10.0) Conditional if (r.syn_pps > 10.0)
[Link].push_back("HIGH_SYN_RATE");` branch — run [Link].push_back("HIGH_SYN_RATE");
code only when
condition true.
111 ` if ([Link] > 100.0) Conditional if ([Link] > 100.0)
[Link].push_back("HIGH_PPS");` branch — run [Link].push_back("HIGH_PPS");
code only when
condition true.
112 ` if (r.new_flow_per_sec > 20.0) Conditional if (r.new_flow_per_sec > 20.0)
[Link].push_back("FLOW_BURST");` branch — run [Link].push_back("FLOW_BURST");
code only when
condition true.
113 `` Blank line for Separator between code blocks.
readability.
114 ` std::ostringstream ss;` Executable std::ostringstream ss;
statement.
115 ` ss << "pps=" << static_cast<int>([Link])` Source code ss << "pps=" << static_cast<int>([Link])
line.
116 ` << " syn_pps=" << Source code << " syn_pps=" <<
static_cast<int>(r.syn_pps)` line. static_cast<int>(r.syn_pps)
117 ` << " new_flows/s=" << Executable << " new_flows/s=" <<
static_cast<int>(r.new_flow_per_sec);` statement. static_cast<int>(r.new_flow_per_sec);
118 ` [Link] = [Link]();` Executable [Link] = [Link]();
statement.
119 `` Blank line for Separator between code blocks.
readability.
120 ` if (cfg_.adaptive_thresholds) {` Conditional if (cfg_.adaptive_thresholds) {
branch — run
code only when
condition true.
121 ` hist_pps_.observe([Link]);` Executable hist_pps_.observe([Link]);
statement.
122 ` hist_syn_.observe(r.syn_pps);` Executable hist_syn_.observe(r.syn_pps);
statement.

Page 366 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
123 ` } else {` Source code } else {
line.
124 ` hist_pps_legacy_.update([Link]);` Executable hist_pps_legacy_.update([Link]);
statement.
125 ` hist_syn_legacy_.update(r.syn_pps);` Executable hist_syn_legacy_.update(r.syn_pps);
statement.
126 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
127 ` return res;` Exit function return res;
and give back
a value.
128 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
129 `` Blank line for Separator between code blocks.
readability.
130 `} // namespace nads` End of nads } // namespace nads
namespace.

File: nads/tests/run_tests.cpp
Total lines: 2

Line Source Easy Explanation Technical Explanation


1 `#include "test_runner.h"` Import another header file into this #include "test_runner.h"
compilation unit.
2 `int main() { return Source code line. int main() { return
nads_test::run_all(); }` nads_test::run_all(); }

File: nads/tests/test_adaptive_stats.cpp
Total lines: 32

Lin Source Easy Technical Explanation


e Explanation
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.

Page 367 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
2 `#include "running_stats.h"` Import #include "running_stats.h"
another
header file
into this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code blocks.
readability.
6 `REGISTER_TEST(ewma_stats_tracks_mean) Source code REGISTER_TEST(ewma_stats_tracks_mean) {
{` line.
7 ` EwmaStats s(0.2);` Executable EwmaStats s(0.2);
statement.
8 ` for (int i = 0; i < 50; ++i) [Link](100.0);` Loop over for (int i = 0; i < 50; ++i) [Link](100.0);
items or until
condition
changes.
9 ` REQUIRE([Link](10));` Executable REQUIRE([Link](10));
statement.
10 ` REQUIRE_NEAR([Link](), 100.0, 5.0);` Executable REQUIRE_NEAR([Link](), 100.0, 5.0);
statement.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
12 `` Blank line for Separator between code blocks.
readability.
13 `REGISTER_TEST(ewma_stats_spike_zscore) Compare Z-score or normalized score.
{` value to
learned
baseline
statistically.
14 ` EwmaStats s(0.1);` Executable EwmaStats s(0.1);
statement.
15 ` for (int i = 0; i < 40; ++i) [Link](10.0);` Loop over for (int i = 0; i < 40; ++i) [Link](10.0);
items or until
condition
changes.
16 ` double z = [Link](1000.0);` Compare Z-score or normalized score.
value to
learned
baseline
statistically.
17 ` REQUIRE(z > 2.0);` Executable REQUIRE(z > 2.0);
statement.
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 368 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
19 `` Blank line for Separator between code blocks.
readability.
20 `REGISTER_TEST(ring_buffer_percentile_p95) Source code REGISTER_TEST(ring_buffer_percentile_p95) {
{` line.
21 ` RingBufferPercentile r(100);` Executable RingBufferPercentile r(100);
statement.
22 ` for (int i = 1; i <= 100; ++i) Loop over for (int i = 1; i <= 100; ++i)
[Link](static_cast<double>(i));` items or until [Link](static_cast<double>(i));
condition
changes.
23 ` double p = [Link](0.95);` Executable double p = [Link](0.95);
statement.
24 ` REQUIRE(p >= 94.0);` Executable REQUIRE(p >= 94.0);
statement.
25 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
26 `` Blank line for Separator between code blocks.
readability.
27 `REGISTER_TEST(adaptive_baseline_detects_ Source code REGISTER_TEST(adaptive_baseline_detects_
spike) {` line. spike) {
28 ` AdaptiveBaseline b(0.1, 64);` Executable AdaptiveBaseline b(0.1, 64);
statement.
29 ` for (int i = 0; i < 40; ++i) [Link](10.0);` Loop over for (int i = 0; i < 40; ++i) [Link](10.0);
items or until
condition
changes.
30 ` double sc = [Link](500.0, 10);` Executable double sc = [Link](500.0, 10);
statement.
31 ` REQUIRE(sc > 0.5);` Executable REQUIRE(sc > 0.5);
statement.
32 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

File: nads/tests/test_classifier.cpp
Total lines: 125

Lin Source Easy Technical Explanation


e Explanation
1 `#include "test_runner.h"` Import another #include "test_runner.h"
header file into
this
compilation
unit.

Page 369 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
2 `#include "threat_classifier.h"` Import another #include "threat_classifier.h"
header file into
this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code blocks.
readability.
6 `static DetectorResult make(const std::string& Build or return score 0-1, flags, detail string.
name, double s,` a detector
score result.
7 ` std::vector<std::string> flags = Source code std::vector<std::string> flags = {}) {
{}) {` line.
8 ` DetectorResult r;` Build or return score 0-1, flags, detail string.
a detector
score result.
9 ` r.detector_name = name;` Executable r.detector_name = name;
statement.
10 ` [Link] = s;` Executable [Link] = s;
statement.
11 ` [Link] = std::move(flags);` Executable [Link] = std::move(flags);
statement.
12 ` return r;` Exit function return r;
and give back
a value.
13 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
14 `` Blank line for Separator between code blocks.
readability.
15 `REGISTER_TEST(classifier_syn_flood) {` Source code REGISTER_TEST(classifier_syn_flood) {
line.
16 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
17 ` FlowRecord f;` Executable FlowRecord f;
statement.
18 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
19 ` std::vector<DetectorResult> results = {` Build or return score 0-1, flags, detail string.
a detector
score result.
20 ` make("protocol", 0.9, {"SYN_NO_ACK"}),` Source code make("protocol", 0.9, {"SYN_NO_ACK"}),
line.
21 ` make("volume", 0.85),` Source code make("volume", 0.85),
line.

Page 370 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
22 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
23 ` auto t = [Link](f, results, 0.92);` Executable auto t = [Link](f, results, 0.92);
statement.
24 ` REQUIRE(t.attack_type == "SYN Flood Executable REQUIRE(t.attack_type == "SYN Flood
DDoS");` statement. DDoS");
25 ` REQUIRE([Link] == Executable REQUIRE([Link] == Severity::CRITICAL);
Severity::CRITICAL);` statement.
26 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
27 `` Blank line for Separator between code blocks.
readability.
28 `REGISTER_TEST(classifier_null_scan) {` Source code REGISTER_TEST(classifier_null_scan) {
line.
29 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
30 ` FlowRecord f;` Executable FlowRecord f;
statement.
31 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
32 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
33 ` { make("protocol", 0.9, {"NULL_SCAN"}) Source code { make("protocol", 0.9, {"NULL_SCAN"}) },
},` line.
34 ` 0.85);` Executable 0.85);
statement.
35 ` REQUIRE(t.attack_type == "TCP NULL Executable REQUIRE(t.attack_type == "TCP NULL Scan");
Scan");` statement.
36 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
37 `` Blank line for Separator between code blocks.
readability.
38 `REGISTER_TEST(classifier_xmas_scan) {` Source code REGISTER_TEST(classifier_xmas_scan) {
line.
39 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
40 ` FlowRecord f;` Executable FlowRecord f;
statement.
41 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
42 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
43 ` { make("protocol", 0.9, {"XMAS_SCAN"}) Source code { make("protocol", 0.9, {"XMAS_SCAN"}) },
},` line.

Page 371 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
44 ` 0.85);` Executable 0.85);
statement.
45 ` REQUIRE(t.attack_type == "TCP XMAS Executable REQUIRE(t.attack_type == "TCP XMAS
Scan");` statement. Scan");
46 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
47 `` Blank line for Separator between code blocks.
readability.
48 `REGISTER_TEST(classifier_port_scan) {` Source code REGISTER_TEST(classifier_port_scan) {
line.
49 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
50 ` FlowRecord f;` Executable FlowRecord f;
statement.
51 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
52 ` { make("graph", 0.8, {"DEGREE_SPIKE"}) Source code { make("graph", 0.8, {"DEGREE_SPIKE"}) },
},` line.
53 ` 0.78);` Executable 0.78);
statement.
54 ` REQUIRE(t.attack_type == "TCP Port Executable REQUIRE(t.attack_type == "TCP Port Scan");
Scan");` statement.
55 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
56 `` Blank line for Separator between code blocks.
readability.
57 `REGISTER_TEST(classifier_beacon) {` Source code REGISTER_TEST(classifier_beacon) {
line.
58 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
59 ` FlowRecord f;` Executable FlowRecord f;
statement.
60 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
61 ` { make("temporal", 0.9, Source code { make("temporal", 0.9,
{"BEACON_PATTERN"}) },` line. {"BEACON_PATTERN"}) },
62 ` 0.88);` Executable 0.88);
statement.
63 ` REQUIRE(t.attack_type == "C&C Beacon Executable REQUIRE(t.attack_type == "C&C Beacon
Pattern");` statement. Pattern");
64 ` REQUIRE([Link] == Executable REQUIRE([Link] == Severity::CRITICAL);
Severity::CRITICAL);` statement.
65 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 372 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
66 `` Blank line for Separator between code blocks.
readability.
67 `REGISTER_TEST(classifier_brute_force_ssh) Source code REGISTER_TEST(classifier_brute_force_ssh)
{` line. {
68 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
69 ` FlowRecord f;` Executable FlowRecord f;
statement.
70 ` [Link].dst_port = 22;` Executable [Link].dst_port = 22;
statement.
71 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
72 ` { make("baseline", 0.8, Source code { make("baseline", 0.8,
{"HOST_BPS_DEVIATION"}) },` line. {"HOST_BPS_DEVIATION"}) },
73 ` 0.78);` Executable 0.78);
statement.
74 ` REQUIRE(t.attack_type == "Brute-Force Executable REQUIRE(t.attack_type == "Brute-Force Login
Login Attempt");` statement. Attempt");
75 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
76 `` Blank line for Separator between code blocks.
readability.
77 `REGISTER_TEST(classifier_lateral_movement Source code REGISTER_TEST(classifier_lateral_movement
) {` line. ){
78 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
79 ` FlowRecord f;` Executable FlowRecord f;
statement.
80 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.

Lin Source Easy Technical Explanation


e Explanation
81 ` { make("graph", 0.9, Source code { make("graph", 0.9,
{"FAST_PEER_EXPANSION"}) },` line. {"FAST_PEER_EXPANSION"}) },
82 ` 0.91);` Executable 0.91);
statement.
83 ` REQUIRE(t.attack_type == "Suspected Executable REQUIRE(t.attack_type == "Suspected Lateral
Lateral Movement");` statement. Movement");
84 ` REQUIRE([Link] == Executable REQUIRE([Link] == Severity::CRITICAL);
Severity::CRITICAL);` statement.
85 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
86 `` Blank line for Separator between code blocks.
readability.

Page 373 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
87 `REGISTER_TEST(classifier_dns_amp) {` Source code REGISTER_TEST(classifier_dns_amp) {
line.
88 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
89 ` FlowRecord f;` Executable FlowRecord f;
statement.
90 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
91 ` { make("protocol", 0.7, Source code { make("protocol", 0.7,
{"DNS_LARGE_RESPONSE"}) },` line. {"DNS_LARGE_RESPONSE"}) },
92 ` 0.72);` Executable 0.72);
statement.
93 ` REQUIRE(t.attack_type == "DNS Anomaly / Executable REQUIRE(t.attack_type == "DNS Anomaly /
Amplification");` statement. Amplification");
94 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
95 `` Blank line for Separator between code blocks.
readability.
96 `REGISTER_TEST(classifier_tunneling) {` Source code REGISTER_TEST(classifier_tunneling) {
line.
97 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
98 ` FlowRecord f;` Executable FlowRecord f;
statement.
99 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.
100 ` { make("entropy", 0.7, Source code { make("entropy", 0.7,
{"UNEXPECTED_HIGH_ENTROPY"}) },` line. {"UNEXPECTED_HIGH_ENTROPY"}) },
101 ` 0.7);` Executable 0.7);
statement.
102 ` REQUIRE(t.attack_type == "Suspected Executable REQUIRE(t.attack_type == "Suspected
Tunneling / Exfiltration");` statement. Tunneling / Exfiltration");
103 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
104 `` Blank line for Separator between code blocks.
readability.
105 `REGISTER_TEST(classifier_unknown_fallback Source code REGISTER_TEST(classifier_unknown_fallback
) {` line. ){
106 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
107 ` FlowRecord f;` Executable FlowRecord f;
statement.
108 ` auto t = [Link](f,` Source code auto t = [Link](f,
line.

Page 374 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
109 ` { make("statistical", 0.5) },` Source code { make("statistical", 0.5) },
line.
110 ` 0.55);` Executable 0.55);
statement.
111 ` REQUIRE(t.attack_type == "Unclassified Executable REQUIRE(t.attack_type == "Unclassified
Anomaly");` statement. Anomaly");
112 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
113 `` Blank line for Separator between code blocks.
readability.
114 `REGISTER_TEST(classifier_severity_grading) Source code REGISTER_TEST(classifier_severity_grading)
{` line. {
115 ` ThreatClassifier c;` Executable ThreatClassifier c;
statement.
116 ` FlowRecord f;` Executable FlowRecord f;
statement.
117 ` auto low = [Link](f, { make("statistical", Executable auto low = [Link](f, { make("statistical", 0.4)
0.4) }, 0.4);` statement. }, 0.4);
118 ` REQUIRE([Link] == Severity::LOW);` Executable REQUIRE([Link] == Severity::LOW);
statement.
119 ` auto med = [Link](f, { make("statistical", Executable auto med = [Link](f, { make("statistical", 0.6)
0.6) }, 0.6);` statement. }, 0.6);
120 ` REQUIRE([Link] == Executable REQUIRE([Link] ==
Severity::MEDIUM);` statement. Severity::MEDIUM);
121 ` auto high = [Link](f, { make("statistical", Executable auto high = [Link](f, { make("statistical", 0.8)
0.8) }, 0.8);` statement. }, 0.8);
122 ` REQUIRE([Link] == Severity::HIGH);` Executable REQUIRE([Link] == Severity::HIGH);
statement.
123 ` auto crit = [Link](f, { make("statistical", Executable auto crit = [Link](f, { make("statistical", 0.95)
0.95) }, 0.95);` statement. }, 0.95);
124 ` REQUIRE([Link] == Executable REQUIRE([Link] == Severity::CRITICAL);
Severity::CRITICAL);` statement.
125 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

File: nads/tests/test_correlation.cpp
Total lines: 18

Page 375 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "correlation_engine.h"` Import #include "correlation_engine.h"
another
header file
into this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code blocks.
readability.
6 `REGISTER_TEST(correlation_boost_multi_det Source code REGISTER_TEST(correlation_boost_multi_det
ector) {` line. ector) {
7 ` CorrelationEngine eng(30);` Executable CorrelationEngine eng(30);
statement.
8 ` int64_t now = 1000000LL * 1000;` Executable int64_t now = 1000000LL * 1000;
statement.
9 ` DetectorResult a, b;` Build or return score 0-1, flags, detail string.
a detector
score result.
10 ` a.detector_name = "protocol";` Executable a.detector_name = "protocol";
statement.
11 ` [Link] = 0.8;` Executable [Link] = 0.8;
statement.
12 ` b.detector_name = "temporal";` Executable b.detector_name = "temporal";
statement.
13 ` [Link] = 0.7;` Executable [Link] = 0.7;
statement.
14 ` [Link](0x0A000001, a, now);` Executable [Link](0x0A000001, a, now);
statement.
15 ` [Link](0x0A000001, b, now);` Executable [Link](0x0A000001, b, now);
statement.
16 ` double boost = Executable double boost =
eng.correlation_boost(0x0A000001, now);` statement. eng.correlation_boost(0x0A000001, now);
17 ` REQUIRE(boost >= 0.10);` Executable REQUIRE(boost >= 0.10);
statement.
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 376 of 629


NADS Complete Technical Reference

File: nads/tests/test_entropy.cpp
Total lines: 50

Lin Source Easy Technical Explanation


e Explanatio
n
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "entropy_profiler.h"` Import #include "entropy_profiler.h"
another
header file
into this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code blocks.
readability.
6 `REGISTER_TEST(entropy_all_zero_is_zero) {` Source code REGISTER_TEST(entropy_all_zero_is_zero) {
line.
7 ` std::array<uint64_t, 256> hist{};` Executable std::array<uint64_t, 256> hist{};
statement.
8 ` hist[0] = 1000;` Executable hist[0] = 1000;
statement.
9 ` double H = EntropyProfiler::shannon(hist, Executable double H = EntropyProfiler::shannon(hist, 1000);
1000);` statement.
10 ` REQUIRE_NEAR(H, 0.0, 1e-9);` Executable REQUIRE_NEAR(H, 0.0, 1e-9);
statement.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
12 `` Blank line for Separator between code blocks.
readability.
13 `REGISTER_TEST(entropy_uniform_random_is_ Source code REGISTER_TEST(entropy_uniform_random_is_
8) {` line. 8) {
14 ` std::array<uint64_t, 256> hist{};` Executable std::array<uint64_t, 256> hist{};
statement.
15 ` for (int i = 0; i < 256; ++i) hist[i] = 100;` Loop over for (int i = 0; i < 256; ++i) hist[i] = 100;
items or until
condition
changes.
16 ` double H = EntropyProfiler::shannon(hist, 256 Executable double H = EntropyProfiler::shannon(hist, 256 *
* 100);` statement. 100);
17 ` REQUIRE_NEAR(H, 8.0, 0.01);` Executable REQUIRE_NEAR(H, 8.0, 0.01);
statement.

Page 377 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
19 `` Blank line for Separator between code blocks.
readability.
20 `REGISTER_TEST(entropy_two_symbols_is_on Source code REGISTER_TEST(entropy_two_symbols_is_one
e) {` line. ){
21 ` std::array<uint64_t, 256> hist{};` Executable std::array<uint64_t, 256> hist{};
statement.
22 ` hist[0] = 500;` Executable hist[0] = 500;
statement.
23 ` hist[1] = 500;` Executable hist[1] = 500;
statement.
24 ` double H = EntropyProfiler::shannon(hist, Executable double H = EntropyProfiler::shannon(hist, 1000);
1000);` statement.
25 ` REQUIRE_NEAR(H, 1.0, 1e-6);` Executable REQUIRE_NEAR(H, 1.0, 1e-6);
statement.
26 `}` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
27 `` Blank line for Separator between code blocks.
readability.
28 `REGISTER_TEST(entropy_score_high_on_plain Source code REGISTER_TEST(entropy_score_high_on_plain
text_port) {` line. text_port) {
29 ` EntropyProfiler p;` Executable EntropyProfiler p;
statement.
30 ` FlowRecord f;` Executable FlowRecord f;
statement.
31 ` [Link].dst_port = 80; // HTTP - should be Source code [Link].dst_port = 80; // HTTP - should be
plaintext` line. plaintext
32 ` [Link] = 7.5; // but we see encrypted- Source code [Link] = 7.5; // but we see encrypted-
looking data` line. looking data
33 ` // Need at least 50 sampled bytes to score` Comment Need at least 50 sampled bytes to score
documenting
intent.
34 ` for (int i = 0; i < 256; ++i) f.byte_histogram[i] = Loop over for (int i = 0; i < 256; ++i) f.byte_histogram[i] = 1;
1;` items or until
condition
changes.
35 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
36 ` REQUIRE([Link] >= 0.5);` Executable REQUIRE([Link] >= 0.5);
statement.
37 ` bool has_flag = false;` Executable bool has_flag = false;
statement.

Page 378 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
38 ` for (const auto& flg : [Link]) if (flg == Loop over for (const auto& flg : [Link]) if (flg ==
"UNEXPECTED_HIGH_ENTROPY") has_flag = items or until "UNEXPECTED_HIGH_ENTROPY") has_flag =
true;` condition
changes.
39 ` REQUIRE(has_flag);` Executable REQUIRE(has_flag);
statement.
40 `}` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
41 `` Blank line for Separator between code blocks.
readability.
42 `REGISTER_TEST(entropy_no_score_on_tiny_s Source code REGISTER_TEST(entropy_no_score_on_tiny_s
ample) {` line. ample) {
43 ` EntropyProfiler p;` Executable EntropyProfiler p;
statement.
44 ` FlowRecord f;` Executable FlowRecord f;
statement.
45 ` [Link].dst_port = 80;` Executable [Link].dst_port = 80;
statement.
46 ` [Link] = 7.9;` Executable [Link] = 7.9;
statement.
47 ` f.byte_histogram[0] = 5; // only 5 bytes Source code f.byte_histogram[0] = 5; // only 5 bytes sampled
sampled` line.
48 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
49 ` REQUIRE_EQ([Link], 0.0);` Executable REQUIRE_EQ([Link], 0.0);
statement.
50 `}` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.

File: nads/tests/test_flow_table.cpp
Total lines: 75

Lin Source Easy Technical Explanation


e Explanati
on
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.

Page 379 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
2 `#include "flow_table.h"` Import #include "flow_table.h"
another
header file
into this
compilation
unit.
3 `#include <arpa/inet.h>` Import #include <arpa/inet.h>
another
header file
into this
compilation
unit.
4 `` Blank line Separator between code blocks.
for
readability.
5 `using namespace nads;` Executable using namespace nads;
statement.
6 `` Blank line Separator between code blocks.
for
readability.
7 `static PacketInfo mk(uint32_t s, uint32_t d, Source static PacketInfo mk(uint32_t s, uint32_t d,
uint16_t sp, uint16_t dp, int64_t ts,` code line. uint16_t sp, uint16_t dp, int64_t ts,
8 ` uint8_t proto = PROTO_TCP, Source uint8_t proto = PROTO_TCP, uint8_t flags =
uint8_t flags = TCP_ACK, uint32_t len = 100) {` code line. TCP_ACK, uint32_t len = 100) {
9 ` PacketInfo p;` Executable PacketInfo p;
statement.
10 ` p.src_ip = s; p.dst_ip = d;` Executable p.src_ip = s; p.dst_ip = d;
statement.
11 ` p.src_port = sp; p.dst_port = dp;` Executable p.src_port = sp; p.dst_port = dp;
statement.
12 ` [Link] = proto;` Executable [Link] = proto;
statement.
13 ` p.tcp_flags = flags;` Executable p.tcp_flags = flags;
statement.
14 ` p.timestamp_us = ts;` Executable p.timestamp_us = ts;
statement.
15 ` [Link] = len;` Executable [Link] = len;
statement.
16 ` [Link] = true;` Executable [Link] = true;
statement.
17 ` return p;` Exit return p;
function
and give
back a
value.
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.

Page 380 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
19 `` Blank line Separator between code blocks.
for
readability.
20 `REGISTER_TEST(flow_table_bidirectional_norm Source REGISTER_TEST(flow_table_bidirectional_norm
alization) {` code line. alization) {
21 ` FlowTable t(60);` Executable FlowTable t(60);
statement.
22 ` uint32_t a = inet_addr("[Link]"), b = Executable uint32_t a = inet_addr("[Link]"), b =
inet_addr("[Link]");` statement. inet_addr("[Link]");
23 ` bool isnew = false;` Executable bool isnew = false;
statement.
24 ` [Link](mk(a, b, 1000, 80, 1'000'000, Executable [Link](mk(a, b, 1000, 80, 1'000'000,
PROTO_TCP, TCP_SYN), &isnew);` statement. PROTO_TCP, TCP_SYN), &isnew);
25 ` REQUIRE(isnew);` Executable REQUIRE(isnew);
statement.
26 ` [Link](mk(b, a, 80, 1000, 1'500'000, TCP_ACK), Executable statement.
PROTO_TCP, TCP_SYN \ &isnew);`
27 ` REQUIRE(!isnew); // same flow, opposite Source REQUIRE(!isnew); // same flow, opposite
direction` code line. direction
28 ` REQUIRE_EQ([Link](), 1u);` Executable REQUIRE_EQ([Link](), 1u);
statement.
29 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
30 `` Blank line Separator between code blocks.
for
readability.
31 `REGISTER_TEST(flow_table_separate_flows_dif Source REGISTER_TEST(flow_table_separate_flows_dif
ferent_protocol) {` code line. ferent_protocol) {
32 ` FlowTable t(60);` Executable FlowTable t(60);
statement.
33 ` uint32_t a = inet_addr("[Link]"), b = Executable uint32_t a = inet_addr("[Link]"), b =
inet_addr("[Link]");` statement. inet_addr("[Link]");
34 ` bool isnew = false;` Executable bool isnew = false;
statement.
35 ` [Link](mk(a, b, 1000, 80, 1'000'000, Executable [Link](mk(a, b, 1000, 80, 1'000'000,
PROTO_TCP), &isnew);` statement. PROTO_TCP), &isnew);
36 ` REQUIRE(isnew);` Executable REQUIRE(isnew);
statement.
37 ` [Link](mk(a, b, 1000, 80, 1'000'000, Executable [Link](mk(a, b, 1000, 80, 1'000'000,
PROTO_UDP), &isnew);` statement. PROTO_UDP), &isnew);
38 ` REQUIRE(isnew);` Executable REQUIRE(isnew);
statement.
39 ` REQUIRE_EQ([Link](), 2u);` Executable REQUIRE_EQ([Link](), 2u);
statement.
40 `}` Brace or C/C++ syntax structure.
parenthesis

Page 381 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
closing/ope
ning a
block.
41 `` Blank line Separator between code blocks.
for
readability.
42 `REGISTER_TEST(flow_table_expires_idle_flows Source REGISTER_TEST(flow_table_expires_idle_flows
) {` code line. ){
43 ` FlowTable t(60);` Executable FlowTable t(60);
statement.
44 ` uint32_t a = inet_addr("[Link]"), b = Executable uint32_t a = inet_addr("[Link]"), b =
inet_addr("[Link]");` statement. inet_addr("[Link]");
45 ` [Link](mk(a, b, 5, 6, 0));` Executable [Link](mk(a, b, 5, 6, 0));
statement.
46 ` auto exp = t.sweep_expired(70 * 1000000LL);` Executable auto exp = t.sweep_expired(70 * 1000000LL);
statement.
47 ` REQUIRE_EQ([Link](), 1u);` Executable REQUIRE_EQ([Link](), 1u);
statement.
48 ` REQUIRE(exp[0].is_complete);` Executable REQUIRE(exp[0].is_complete);
statement.
49 ` REQUIRE_EQ([Link](), 0u);` Executable REQUIRE_EQ([Link](), 0u);
statement.
50 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
51 `` Blank line Separator between code blocks.
for
readability.
52 `REGISTER_TEST(flow_table_records_packet_b Source REGISTER_TEST(flow_table_records_packet_by
yte_counts) {` code line. te_counts) {
53 ` FlowTable t(60);` Executable FlowTable t(60);
statement.
54 ` uint32_t a = inet_addr("[Link]"), b = Executable uint32_t a = inet_addr("[Link]"), b =
inet_addr("[Link]");` statement. inet_addr("[Link]");
55 ` for (int i = 0; i < 5; ++i) {` Loop over for (int i = 0; i < 5; ++i) {
items or
until
condition
changes.
56 ` [Link](mk(a, b, 1, 80, i*100000, Executable [Link](mk(a, b, 1, 80, i*100000, PROTO_TCP,
PROTO_TCP, TCP_ACK, 200));` statement. TCP_ACK, 200));
57 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
58 ` auto exp = t.sweep_expired(120 * Executable auto exp = t.sweep_expired(120 * 1000000LL);
1000000LL);` statement.

Page 382 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
59 ` REQUIRE_EQ([Link](), 1u);` Executable REQUIRE_EQ([Link](), 1u);
statement.
60 ` REQUIRE_EQ(exp[0].packet_count, 5u);` Executable REQUIRE_EQ(exp[0].packet_count, 5u);
statement.
61 ` REQUIRE_EQ(exp[0].byte_count, 1000u);` Executable REQUIRE_EQ(exp[0].byte_count, 1000u);
statement.
62 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
63 `` Blank line Separator between code blocks.
for
readability.
64 `REGISTER_TEST(flow_table_compute_features Source REGISTER_TEST(flow_table_compute_features
_rates_correct) {` code line. _rates_correct) {
65 ` FlowRecord r;` Executable FlowRecord r;
statement.
66 ` r.first_seen_us = 0;` Executable r.first_seen_us = 0;
statement.
67 ` r.last_seen_us = 1'000'000; // 1 second` Source r.last_seen_us = 1'000'000; // 1 second
code line.
68 ` r.packet_count = 10;` Executable r.packet_count = 10;
statement.
69 ` r.byte_count = 1500;` Executable r.byte_count = 1500;
statement.
70 ` r.size_buf = {100, 100, 100, 100, 100};` Executable r.size_buf = {100, 100, 100, 100, 100};
statement.
71 ` FlowTable::compute_features(r);` Executable FlowTable::compute_features(r);
statement.
72 ` REQUIRE_NEAR([Link], 10.0, 1e-6);` Executable REQUIRE_NEAR([Link], 10.0, 1e-6);
statement.
73 ` REQUIRE_NEAR([Link], 12000.0, 1e-6); // Source REQUIRE_NEAR([Link], 12000.0, 1e-6); // 1500 *
1500 * 8` code line. 8
74 ` REQUIRE_NEAR(r.mean_pkt_size, 100.0, 1e- Executable REQUIRE_NEAR(r.mean_pkt_size, 100.0, 1e-6);
6);` statement.
75 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.

File: nads/tests/test_fusion.cpp
Total lines: 91

Page 383 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
1 `#include "test_runner.h"` Import another #include "test_runner.h"
header file into
this compilation
unit.
2 `#include "fusion_engine.h"` Import another #include "fusion_engine.h"
header file into
this compilation
unit.
3 `` Blank line for Separator between code
readability. blocks.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code
readability. blocks.
6 `static DetectorResult make(const std::string& name, double s) Build or return score 0-1, flags, detail string.
{` a detector
score result.
7 ` DetectorResult r;` Build or return score 0-1, flags, detail string.
a detector
score result.
8 ` r.detector_name = name;` Executable r.detector_name = name;
statement.
9 ` [Link] = s;` Executable [Link] = s;
statement.
10 ` return r;` Exit function return r;
and give back
a value.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
12 `` Blank line for Separator between code
readability. blocks.
13 `REGISTER_TEST(fusion_zero_scores_no_alert) {` Combine Fusion / correlation logic.
multiple
detector
scores.
14 ` Config c;` Executable Config c;
statement.
15 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
16 ` std::vector<DetectorResult> results = {` Build or return score 0-1, flags, detail string.
a detector
score result.
17 ` make("statistical", 0.0),` Source code make("statistical", 0.0),
line.
18 ` make("volume", 0.0),` Source code make("volume", 0.0),
line.
19 ` make("protocol", 0.0),` Source code make("protocol", 0.0),
line.

Page 384 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
20 ` make("baseline", 0.0),` Source code make("baseline", 0.0),
line.
21 ` make("graph", 0.0),` Source code make("graph", 0.0),
line.
22 ` make("temporal", 0.0),` Source code make("temporal", 0.0),
line.
23 ` make("entropy", 0.0),` Source code make("entropy", 0.0),
line.
24 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
25 ` auto r = [Link](results);` Executable auto r = [Link](results);
statement.
26 ` REQUIRE_NEAR(r.final_score, 0.0, 1e-9);` Executable REQUIRE_NEAR(r.final_score,
statement. 0.0, 1e-9);
27 ` REQUIRE(!r.is_anomaly);` Executable REQUIRE(!r.is_anomaly);
statement.
28 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
29 `` Blank line for Separator between code
readability. blocks.
30 `REGISTER_TEST(fusion_single_detector_scaled_by_weight) Combine Fusion / correlation logic.
{` multiple
detector
scores.
31 ` Config c;` Executable Config c;
statement.
32 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
33 ` // Volume only - weight is 0.25 of 1.0 total weights = Comment Volume only - weight is 0.25 of
sum/total_w` documenting 1.0 total weights = sum/total_w
intent.
34 ` // sum=0.25*1.0, total_w=0.25 → final=1.0` Comment sum=0.25*1.0, total_w=0.25 →
documenting final=1.0
intent.
35 ` auto r = [Link]({ make("volume", 1.0) });` Executable auto r = [Link]({
statement. make("volume", 1.0) });
36 ` REQUIRE_NEAR(r.final_score, 1.0, 1e-9);` Executable REQUIRE_NEAR(r.final_score,
statement. 1.0, 1e-9);
37 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
38 `` Blank line for Separator between code
readability. blocks.
39 `REGISTER_TEST(fusion_high_scores_trigger_alert) {` Combine Fusion / correlation logic.
multiple

Page 385 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
detector
scores.
40 ` Config c;` Executable Config c;
statement.
41 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
42 ` std::vector<DetectorResult> results = {` Build or return score 0-1, flags, detail string.
a detector
score result.
43 ` make("statistical", 0.9),` Source code make("statistical", 0.9),
line.
44 ` make("volume", 0.95),` Source code make("volume", 0.95),
line.
45 ` make("protocol", 0.85),` Source code make("protocol", 0.85),
line.
46 ` make("baseline", 0.8),` Source code make("baseline", 0.8),
line.
47 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
48 ` auto r = [Link](results);` Executable auto r = [Link](results);
statement.
49 ` REQUIRE(r.final_score > c.alert_threshold);` Executable REQUIRE(r.final_score >
statement. c.alert_threshold);
50 ` REQUIRE(r.is_anomaly);` Executable REQUIRE(r.is_anomaly);
statement.
51 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
52 `` Blank line for Separator between code
readability. blocks.
53 `REGISTER_TEST(fusion_corroboration_boost) {` Combine Fusion / correlation logic.
multiple
detector
scores.
54 ` Config c;` Executable Config c;
statement.
55 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
56 ` // Several detectors firing at moderate level should get a Comment Several detectors firing at
boost` documenting moderate level should get a
intent. boost
57 ` std::vector<DetectorResult> results = {` Build or return score 0-1, flags, detail string.
a detector
score result.
58 ` make("statistical", 0.6),` Source code make("statistical", 0.6),
line.

Page 386 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
59 ` make("volume", 0.6),` Source code make("volume", 0.6),
line.
60 ` make("protocol", 0.6),` Source code make("protocol", 0.6),
line.
61 ` make("baseline", 0.6),` Source code make("baseline", 0.6),
line.
62 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
63 ` auto r = [Link](results);` Executable auto r = [Link](results);
statement.
64 ` // Without boost, weighted avg would be 0.6. With ≥4 firing, Comment Without boost, weighted avg
boost adds 0.15.` documenting would be 0.6. With ≥4 firing,
intent. boost adds 0.15.
65 ` REQUIRE(r.final_score > 0.65);` Executable REQUIRE(r.final_score >
statement. 0.65);
66 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
67 `` Blank line for Separator between code
readability. blocks.
68 `REGISTER_TEST(fusion_unknown_detector_zero_weight) {` Combine Fusion / correlation logic.
multiple
detector
scores.
69 ` Config c;` Executable Config c;
statement.
70 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
71 ` auto r = [Link]({ make("nonexistent_detector", 1.0) });` Executable auto r = [Link]({
statement. make("nonexistent_detector",
1.0) });
72 ` // Unknown detector has zero weight; total_w=0; Comment Unknown detector has zero
final_score stays 0` documenting weight; total_w=0; final_score
intent. stays 0
73 ` REQUIRE_NEAR(r.final_score, 0.0, 1e-9);` Executable REQUIRE_NEAR(r.final_score,
statement. 0.0, 1e-9);
74 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
75 `` Blank line for Separator between code
readability. blocks.
76 `REGISTER_TEST(fusion_clamps_to_one) {` Combine Fusion / correlation logic.
multiple
detector
scores.
77 ` Config c;` Executable Config c;
statement.

Page 387 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
78 ` FusionEngine f(c);` Executable FusionEngine f(c);
statement.
79 ` std::vector<DetectorResult> results = {` Build or return score 0-1, flags, detail string.
a detector
score result.
80 ` make("statistical", 1.0),` Source code make("statistical", 1.0),
line.

Line Source Easy Explanation Technical Explanation


81 ` make("volume", 1.0),` Source code line. make("volume", 1.0),
82 ` make("protocol", 1.0),` Source code line. make("protocol", 1.0),
83 ` make("baseline", 1.0),` Source code line. make("baseline", 1.0),
84 ` make("graph", 1.0),` Source code line. make("graph", 1.0),
85 ` make("temporal", 1.0),` Source code line. make("temporal", 1.0),
86 ` make("entropy", 1.0),` Source code line. make("entropy", 1.0),
87 ` };` Brace or parenthesis closing/opening C/C++ syntax structure.
a block.
88 ` auto r = [Link](results);` Executable statement. auto r = [Link](results);
89 ` REQUIRE(r.final_score <= Executable statement. REQUIRE(r.final_score <=
1.0);` 1.0);
90 ` REQUIRE(r.final_score >= Executable statement. REQUIRE(r.final_score >=
0.99);` 0.99);
91 `}` Brace or parenthesis closing/opening C/C++ syntax structure.
a block.

File: nads/tests/test_graph_detector.cpp
Total lines: 51

Lin Source Easy Technical Explanation


e Explanation
1 `#include "test_runner.h"` Import another #include "test_runner.h"
header file
into this
compilation
unit.
2 `#include "graph_detector.h"` Import another #include "graph_detector.h"
header file
into this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.

Page 388 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
5 `` Blank line for Separator between code blocks.
readability.
6 `REGISTER_TEST(graph_first_contact_no_alert Source code REGISTER_TEST(graph_first_contact_no_alert
) {` line. ){
7 ` GraphDetector g;` Executable GraphDetector g;
statement.
8 ` auto r = g.on_new_flow(0x0a000001, Executable auto r = g.on_new_flow(0x0a000001,
0x0a000002, 1'000'000);` statement. 0x0a000002, 1'000'000);
9 ` // First-ever contact: no degree spike yet` Comment First-ever contact: no degree spike yet
documenting
intent.
10 ` REQUIRE([Link] < 0.5);` Executable REQUIRE([Link] < 0.5);
statement.
11 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
12 `` Blank line for Separator between code blocks.
readability.
13 `REGISTER_TEST(graph_repeated_peer_no_al Source code REGISTER_TEST(graph_repeated_peer_no_al
ert) {` line. ert) {
14 ` GraphDetector g;` Executable GraphDetector g;
statement.
15 ` int64_t t = 1'000'000;` Executable int64_t t = 1'000'000;
statement.
16 ` // Same src talking to the same dst Comment Same src talking to the same dst repeatedly is
repeatedly is NOT new edges.` documenting NOT new edges.
intent.
17 ` for (int i = 0; i < 50; ++i) {` Loop over for (int i = 0; i < 50; ++i) {
items or until
condition
changes.
18 ` g.on_new_flow(0x0a000001, 0x0a000002, Executable g.on_new_flow(0x0a000001, 0x0a000002, t);
t);` statement.
19 ` t += 1'000'000;` Executable t += 1'000'000;
statement.
20 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
21 ` auto r = g.on_new_flow(0x0a000001, Executable auto r = g.on_new_flow(0x0a000001,
0x0a000002, t);` statement. 0x0a000002, t);
22 ` REQUIRE([Link] < 0.5);` Executable REQUIRE([Link] < 0.5);
statement.
23 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
24 `` Blank line for Separator between code blocks.
readability.

Page 389 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
25 `REGISTER_TEST(graph_degree_spike_flagge Source code REGISTER_TEST(graph_degree_spike_flagge
d) {` line. d) {
26 ` GraphDetector g;` Executable GraphDetector g;
statement.
27 ` int64_t t = 1'000'000;` Executable int64_t t = 1'000'000;
statement.
28 `` Blank line for Separator between code blocks.
readability.
29 ` // Establish a slow baseline: src contacts a Comment Establish a slow baseline: src contacts a few
few peers over time.` documenting peers over time.
intent.
30 ` for (int i = 0; i < 8; ++i) {` Loop over for (int i = 0; i < 8; ++i) {
items or until
condition
changes.
31 ` g.on_new_flow(0x0a000001, 0x0a000010 Executable g.on_new_flow(0x0a000001, 0x0a000010 + i,
+ i, t);` statement. t);
32 ` t += 60'000'000; // 1 minute apart` Source code t += 60'000'000; // 1 minute apart
line.
33 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
34 `` Blank line for Separator between code blocks.
readability.
35 ` // Now blast many new peers in quick Comment Now blast many new peers in quick succession
succession (port-scan-like)` documenting (port-scan-like)
intent.
36 ` DetectorResult last;` Build or return score 0-1, flags, detail string.
a detector
score result.
37 ` for (int i = 0; i < 60; ++i) {` Loop over for (int i = 0; i < 60; ++i) {
items or until
condition
changes.
38 ` last = g.on_new_flow(0x0a000001, Executable last = g.on_new_flow(0x0a000001, 0x0a000100
0x0a000100 + i, t);` statement. + i, t);
39 ` t += 100'000; // 100ms apart` Source code t += 100'000; // 100ms apart
line.
40 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
41 ` // At least one alert should fire as new-edge Comment At least one alert should fire as new-edge rate
rate spikes` documenting spikes
intent.
42 ` REQUIRE([Link] > 0.0);` Executable REQUIRE([Link] > 0.0);
statement.
43 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 390 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
44 `` Blank line for Separator between code blocks.
readability.
45 `REGISTER_TEST(graph_node_count_grows) Source code REGISTER_TEST(graph_node_count_grows) {
{` line.
46 ` GraphDetector g;` Executable GraphDetector g;
statement.
47 ` g.on_new_flow(0x01, 0x02, 1);` Executable g.on_new_flow(0x01, 0x02, 1);
statement.
48 ` g.on_new_flow(0x03, 0x04, 2);` Executable g.on_new_flow(0x03, 0x04, 2);
statement.
49 ` g.on_new_flow(0x05, 0x06, 3);` Executable g.on_new_flow(0x05, 0x06, 3);
statement.
50 ` REQUIRE([Link]() >= 3);` Executable REQUIRE([Link]() >= 3);
statement.
51 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

File: nads/tests/test_parser.cpp
Total lines: 120

Lin Source Easy Technical Explanation


e Explanatio
n
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "parser.h"` Import #include "parser.h"
another
header file
into this
compilation
unit.
3 `#include <cstring>` Import #include <cstring>
another
header file
into this
compilation
unit.
4 `#include <arpa/inet.h>` Import #include <arpa/inet.h>
another
header file
into this
compilation
unit.

Page 391 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
5 `` Blank line for Separator between code blocks.
readability.
6 `using namespace nads;` Executable using namespace nads;
statement.
7 `` Blank line for Separator between code blocks.
readability.
8 `// Build a synthetic Ethernet/IPv4/TCP packet` Comment Build a synthetic Ethernet/IPv4/TCP packet
documenting
intent.
9 `static std::vector<uint8_t> Source code static std::vector<uint8_t>
make_eth_ip_tcp(uint32_t src_ip_be, uint32_t line. make_eth_ip_tcp(uint32_t src_ip_be, uint32_t
dst_ip_be,` dst_ip_be,
10 ` uint16_t src_port, Source code uint16_t src_port, uint16_t dst_port,
uint16_t dst_port,` line.
11 ` uint8_t flags, size_t Source code uint8_t flags, size_t payload_size = 0) {
payload_size = 0) {` line.
12 ` std::vector<uint8_t> p;` Executable std::vector<uint8_t> p;
statement.
13 ` // Ethernet` Comment Ethernet
documenting
intent.
14 ` EthernetHeader eth{};` Executable EthernetHeader eth{};
statement.
15 ` std::memset(eth.dest_mac, 0xAA, 6);` Executable std::memset(eth.dest_mac, 0xAA, 6);
statement.
16 ` std::memset(eth.src_mac, 0xBB, 6);` Executable std::memset(eth.src_mac, 0xBB, 6);
statement.
17 ` eth.ether_type = htons(0x0800);` Executable eth.ether_type = htons(0x0800);
statement.
18 ` [Link]([Link](), Source code [Link]([Link](),
reinterpret_cast<uint8_t*>(&eth),` line. reinterpret_cast<uint8_t*>(&eth),
19 ` reinterpret_cast<uint8_t*>(&eth) + Executable reinterpret_cast<uint8_t*>(&eth) + sizeof(eth));
sizeof(eth));` statement.
20 ` // IP` Comment IP
documenting
intent.
21 ` IPHeader ip{};` Executable IPHeader ip{};
statement.
22 ` ip.version_ihl = 0x45;` Executable ip.version_ihl = 0x45;
statement.
23 ` [Link] = 0;` Executable [Link] = 0;
statement.
24 ` ip.total_length = htons(20 + 20 + Executable ip.total_length = htons(20 + 20 +
payload_size);` statement. payload_size);
25 ` [Link] = 64;` Executable [Link] = 64;
statement.
26 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.

Page 392 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
27 ` ip.src_ip = src_ip_be;` Executable ip.src_ip = src_ip_be;
statement.
28 ` ip.dst_ip = dst_ip_be;` Executable ip.dst_ip = dst_ip_be;
statement.
29 ` [Link]([Link](), Source code [Link]([Link](),
reinterpret_cast<uint8_t*>(&ip),` line. reinterpret_cast<uint8_t*>(&ip),
30 ` reinterpret_cast<uint8_t*>(&ip) + Executable reinterpret_cast<uint8_t*>(&ip) + sizeof(ip));
sizeof(ip));` statement.
31 ` // TCP` Comment TCP
documenting
intent.
32 ` TCPHeader tcp{};` Executable TCPHeader tcp{};
statement.
33 ` tcp.src_port = htons(src_port);` Executable tcp.src_port = htons(src_port);
statement.
34 ` tcp.dst_port = htons(dst_port);` Executable tcp.dst_port = htons(dst_port);
statement.
35 ` tcp.seq_num = 0;` Executable tcp.seq_num = 0;
statement.
36 ` tcp.ack_num = 0;` Executable tcp.ack_num = 0;
statement.
37 ` tcp.data_offset = 0x50; // 5 * 4 = 20 bytes` Source code tcp.data_offset = 0x50; // 5 * 4 = 20 bytes
line.
38 ` [Link] = flags;` Executable [Link] = flags;
statement.
39 ` [Link] = htons(64240);` Executable [Link] = htons(64240);
statement.
40 ` [Link]([Link](), Source code [Link]([Link](),
reinterpret_cast<uint8_t*>(&tcp),` line. reinterpret_cast<uint8_t*>(&tcp),
41 ` reinterpret_cast<uint8_t*>(&tcp) + Executable reinterpret_cast<uint8_t*>(&tcp) + sizeof(tcp));
sizeof(tcp));` statement.
42 ` // Payload` Comment Payload
documenting
intent.
43 ` for (size_t i = 0; i < payload_size; ++i) Loop over for (size_t i = 0; i < payload_size; ++i)
p.push_back(static_cast<uint8_t>(i));` items or until p.push_back(static_cast<uint8_t>(i));
condition
changes.
44 ` return p;` Exit function return p;
and give
back a value.
45 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
46 `` Blank line for Separator between code blocks.
readability.
47 `REGISTER_TEST(parser_basic_tcp_syn) {` Source code REGISTER_TEST(parser_basic_tcp_syn) {
line.

Page 393 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
48 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
49 ` uint32_t src = inet_addr("[Link]");` Executable uint32_t src = inet_addr("[Link]");
statement.
50 ` uint32_t dst = inet_addr("[Link]");` Executable uint32_t dst = inet_addr("[Link]");
statement.
51 ` pkt.raw_bytes = make_eth_ip_tcp(src, dst, Executable pkt.raw_bytes = make_eth_ip_tcp(src, dst,
54321, 443, TCP_SYN, 0);` statement. 54321, 443, TCP_SYN, 0);
52 ` [Link] = pkt.raw_bytes.size();` Executable [Link] = pkt.raw_bytes.size();
statement.
53 ` pkt.cap_length = pkt.raw_bytes.size();` Executable pkt.cap_length = pkt.raw_bytes.size();
statement.
54 `` Blank line for Separator between code blocks.
readability.
55 ` PacketParser parser(1);` Executable PacketParser parser(1);
statement.
56 ` REQUIRE([Link](pkt));` Executable REQUIRE([Link](pkt));
statement.
57 ` REQUIRE_EQ(pkt.src_port, 54321);` Executable REQUIRE_EQ(pkt.src_port, 54321);
statement.
58 ` REQUIRE_EQ(pkt.dst_port, 443);` Executable REQUIRE_EQ(pkt.dst_port, 443);
statement.
59 ` REQUIRE_EQ([Link], PROTO_TCP);` Executable REQUIRE_EQ([Link], PROTO_TCP);
statement.
60 ` REQUIRE((pkt.tcp_flags & TCP_SYN) != 0);` Executable REQUIRE((pkt.tcp_flags & TCP_SYN) != 0);
statement.
61 ` REQUIRE_EQ(ip_to_string(pkt.src_ip), Executable REQUIRE_EQ(ip_to_string(pkt.src_ip),
std::string("[Link]"));` statement. std::string("[Link]"));
62 ` REQUIRE_EQ(ip_to_string(pkt.dst_ip), Executable REQUIRE_EQ(ip_to_string(pkt.dst_ip),
std::string("[Link]"));` statement. std::string("[Link]"));
63 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
64 `` Blank line for Separator between code blocks.
readability.
65 `REGISTER_TEST(parser_truncated_packet_rejec Source code REGISTER_TEST(parser_truncated_packet_r
ted) {` line. ejected) {
66 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
67 ` pkt.raw_bytes = std::vector<uint8_t>(8, 0); // Source code pkt.raw_bytes = std::vector<uint8_t>(8, 0); //
too small` line. too small
68 ` [Link] = 8;` Executable [Link] = 8;
statement.
69 ` PacketParser parser(1);` Executable PacketParser parser(1);
statement.
70 ` REQUIRE(![Link](pkt));` Executable REQUIRE(![Link](pkt));
statement.

Page 394 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
71 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
72 `` Blank line for Separator between code blocks.
readability.
73 `REGISTER_TEST(parser_payload_offset_survive Byte index Replaces old payload_ptr.
s_move) {` where
payload
starts inside
raw_bytes
(safe after
move).
74 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
75 ` uint32_t src = inet_addr("[Link]");` Executable uint32_t src = inet_addr("[Link]");
statement.
76 ` uint32_t dst = inet_addr("[Link]");` Executable uint32_t dst = inet_addr("[Link]");
statement.
77 ` pkt.raw_bytes = make_eth_ip_tcp(src, dst, TCP_ACK, Executable statement.
1234, 80, TCP_PSH \ 16);`
78 ` [Link] = pkt.raw_bytes.size();` Executable [Link] = pkt.raw_bytes.size();
statement.
79 ` pkt.cap_length = pkt.raw_bytes.size();` Executable pkt.cap_length = pkt.raw_bytes.size();
statement.
80 `` Blank line for Separator between code blocks.
readability.

Lin Source Easy Technical Explanation


e Explanati
on
81 ` PacketParser parser(1);` Executable PacketParser parser(1);
statement.
82 ` REQUIRE([Link](pkt));` Executable REQUIRE([Link](pkt));
statement.
83 ` REQUIRE(pkt.payload_size > 0);` Executable REQUIRE(pkt.payload_size > 0);
statement.
84 `` Blank line Separator between code blocks.
for
readability.
85 ` std::vector<PacketInfo> queue;` Executable std::vector<PacketInfo> queue;
statement.
86 ` queue.push_back(std::move(pkt));` Executable queue.push_back(std::move(pkt));
statement.
87 ` const PacketInfo& moved = [Link]();` Named const PacketInfo& moved = [Link]();
constant —
value
should not
change.

Page 395 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
88 ` REQUIRE(moved.payload_size > 0);` Executable REQUIRE(moved.payload_size > 0);
statement.
89 ` REQUIRE(moved.payload_offset + Byte index Replaces old payload_ptr.
moved.payload_size <= where
moved.raw_bytes.size());` payload
starts inside
raw_bytes
(safe after
move).
90 ` const uint8_t* ptr = moved.raw_bytes.data() + Byte index Replaces old payload_ptr.
moved.payload_offset;` where
payload
starts inside
raw_bytes
(safe after
move).
91 ` REQUIRE_EQ(ptr[0], static_cast<uint8_t>(0));` Executable REQUIRE_EQ(ptr[0], static_cast<uint8_t>(0));
statement.
92 ` REQUIRE_EQ(ptr[15], Executable REQUIRE_EQ(ptr[15], static_cast<uint8_t>(15));
static_cast<uint8_t>(15));` statement.
93 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
94 `` Blank line Separator between code blocks.
for
readability.
95 `REGISTER_TEST(parser_truncated_ip_total_len Source REGISTER_TEST(parser_truncated_ip_total_len
gth_clamped) {` code line. gth_clamped) {
96 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
97 ` pkt.raw_bytes = Source pkt.raw_bytes =
make_eth_ip_tcp(inet_addr("[Link]"), code line. make_eth_ip_tcp(inet_addr("[Link]"),
inet_addr("[Link]"),` inet_addr("[Link]"),
98 ` 1000, 443, TCP_SYN, 0);` Executable 1000, 443, TCP_SYN, 0);
statement.
99 ` // Claim 1500-byte IP packet but only capture Comment Claim 1500-byte IP packet but only capture
Ethernet+IP+TCP (54 bytes)` documentin Ethernet+IP+TCP (54 bytes)
g intent.
100 ` IPHeader* ip = Executable IPHeader* ip =
reinterpret_cast<IPHeader*>(pkt.raw_bytes.data() statement. reinterpret_cast<IPHeader*>(pkt.raw_bytes.data(
+ 14);` ) + 14);
101 ` ip->total_length = htons(1500);` Executable ip->total_length = htons(1500);
statement.
102 ` [Link] = pkt.raw_bytes.size();` Executable [Link] = pkt.raw_bytes.size();
statement.
103 ` pkt.cap_length = pkt.raw_bytes.size();` Executable pkt.cap_length = pkt.raw_bytes.size();
statement.
104 `` Blank line Separator between code blocks.
for
readability.

Page 396 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
105 ` PacketParser parser(1);` Executable PacketParser parser(1);
statement.
106 ` REQUIRE([Link](pkt));` Executable REQUIRE([Link](pkt));
statement.
107 ` REQUIRE([Link]);` Executable REQUIRE([Link]);
statement.
108 ` REQUIRE(pkt.payload_size == 0);` Executable REQUIRE(pkt.payload_size == 0);
statement.
109 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
110 `` Blank line Separator between code blocks.
for
readability.
111 `REGISTER_TEST(parser_non_ip_etype_rejecte Source REGISTER_TEST(parser_non_ip_etype_rejecte
d) {` code line. d) {
112 ` PacketInfo pkt;` Executable PacketInfo pkt;
statement.
113 ` pkt.raw_bytes = make_eth_ip_tcp(0, 0, 0, 0, 0, Executable pkt.raw_bytes = make_eth_ip_tcp(0, 0, 0, 0, 0, 0);
0);` statement.
114 ` // Overwrite ethertype with ARP` Comment Overwrite ethertype with ARP
documentin
g intent.
115 ` EthernetHeader* eth = Executable EthernetHeader* eth =
reinterpret_cast<EthernetHeader*>(pkt.raw_bytes statement. reinterpret_cast<EthernetHeader*>(pkt.raw_byte
.data());` [Link]());
116 ` eth->ether_type = htons(0x0806); // ARP` Source eth->ether_type = htons(0x0806); // ARP
code line.
117 ` [Link] = pkt.raw_bytes.size();` Executable [Link] = pkt.raw_bytes.size();
statement.
118 ` PacketParser parser(1);` Executable PacketParser parser(1);
statement.
119 ` REQUIRE(![Link](pkt));` Executable REQUIRE(![Link](pkt));
statement.
120 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.

File: nads/tests/test_protocol_analyzer.cpp
Total lines: 78

Page 397 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "protocol_analyzer.h"` Import #include "protocol_analyzer.h"
another
header file
into this
compilation
unit.
3 `` Blank line for Separator between code blocks.
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line for Separator between code blocks.
readability.
6 `REGISTER_TEST(protocol_syn_no_ack_flagge Source code REGISTER_TEST(protocol_syn_no_ack_flagge
d) {` line. d) {
7 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
8 ` FlowRecord f;` Executable FlowRecord f;
statement.
9 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
10 ` f.syn_count = 200;` Executable f.syn_count = 200;
statement.
11 ` f.ack_count = 0;` Executable f.ack_count = 0;
statement.
12 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
13 ` REQUIRE([Link] >= 0.85);` Executable REQUIRE([Link] >= 0.85);
statement.
14 ` bool has_syn_no_ack = false;` Executable bool has_syn_no_ack = false;
statement.
15 ` for (const auto& flg : [Link]) if (flg == Loop over for (const auto& flg : [Link]) if (flg ==
"SYN_NO_ACK") has_syn_no_ack = true;` items or until "SYN_NO_ACK") has_syn_no_ack = true;
condition
changes.
16 ` REQUIRE(has_syn_no_ack);` Executable REQUIRE(has_syn_no_ack);
statement.
17 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
18 `` Blank line for Separator between code blocks.
readability.
19 `REGISTER_TEST(protocol_null_scan_flagged) Source code REGISTER_TEST(protocol_null_scan_flagged)
{` line. {

Page 398 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
20 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
21 ` FlowRecord f;` Executable FlowRecord f;
statement.
22 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
23 ` f.has_null_flags = true;` Executable f.has_null_flags = true;
statement.
24 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
25 ` REQUIRE([Link] >= 0.9);` Executable REQUIRE([Link] >= 0.9);
statement.
26 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
27 `` Blank line for Separator between code blocks.
readability.
28 `REGISTER_TEST(protocol_xmas_scan_flagge Source code REGISTER_TEST(protocol_xmas_scan_flagged
d) {` line. ){
29 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
30 ` FlowRecord f;` Executable FlowRecord f;
statement.
31 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
32 ` f.has_xmas_flags = true;` Executable f.has_xmas_flags = true;
statement.
33 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
34 ` REQUIRE([Link] >= 0.9);` Executable REQUIRE([Link] >= 0.9);
statement.
35 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
36 `` Blank line for Separator between code blocks.
readability.
37 `REGISTER_TEST(protocol_normal_tcp_no_aler Source code REGISTER_TEST(protocol_normal_tcp_no_aler
t) {` line. t) {
38 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
39 ` FlowRecord f;` Executable FlowRecord f;
statement.
40 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
41 ` f.syn_count = 1;` Executable f.syn_count = 1;
statement.

Page 399 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
42 ` f.ack_count = 5;` Executable f.ack_count = 5;
statement.
43 ` f.fin_count = 1;` Executable f.fin_count = 1;
statement.
44 ` f.has_full_handshake = true;` Executable f.has_full_handshake = true;
statement.
45 ` f.packet_count = 20;` Executable f.packet_count = 20;
statement.
46 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
47 ` REQUIRE([Link] < 0.5);` Executable REQUIRE([Link] < 0.5);
statement.
48 ` REQUIRE(!r.is_anomaly);` Executable REQUIRE(!r.is_anomaly);
statement.
49 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
50 `` Blank line for Separator between code blocks.
readability.
51 `REGISTER_TEST(protocol_dns_amplification_fl Source code REGISTER_TEST(protocol_dns_amplification_fl
agged) {` line. agged) {
52 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
53 ` FlowRecord f;` Executable FlowRecord f;
statement.
54 ` [Link] = PROTO_UDP;` Executable [Link] = PROTO_UDP;
statement.
55 ` [Link].src_port = 53;` Executable [Link].src_port = 53;
statement.
56 ` f.mean_pkt_size = 1200.0;` Executable f.mean_pkt_size = 1200.0;
statement.
57 ` [Link] = 50.0;` Executable [Link] = 50.0;
statement.
58 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
59 ` REQUIRE([Link] >= 0.7);` Executable REQUIRE([Link] >= 0.7);
statement.
60 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
61 `` Blank line for Separator between code blocks.
readability.
62 `REGISTER_TEST(protocol_icmp_flood_flagged Source code REGISTER_TEST(protocol_icmp_flood_flagged
) {` line. ){
63 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.

Page 400 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
64 ` FlowRecord f;` Executable FlowRecord f;
statement.
65 ` [Link] = PROTO_ICMP;` Executable [Link] = PROTO_ICMP;
statement.
66 ` [Link] = 800.0;` Executable [Link] = 800.0;
statement.
67 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
68 ` REQUIRE([Link] >= 0.8);` Executable REQUIRE([Link] >= 0.8);
statement.
69 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
70 `` Blank line for Separator between code blocks.
readability.
71 `REGISTER_TEST(protocol_rst_flood_flagged) Source code REGISTER_TEST(protocol_rst_flood_flagged) {
{` line.
72 ` ProtocolAnalyzer p;` Executable ProtocolAnalyzer p;
statement.
73 ` FlowRecord f;` Executable FlowRecord f;
statement.
74 ` [Link] = PROTO_TCP;` Executable [Link] = PROTO_TCP;
statement.
75 ` f.rst_count = 200;` Executable f.rst_count = 200;
statement.
76 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
77 ` REQUIRE([Link] >= 0.7);` Executable REQUIRE([Link] >= 0.7);
statement.
78 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

File: nads/tests/test_runner.h
Total lines: 80

Line Source Easy Explanation Technical Explanation


1 `// test_runner.h - tiny header-only Comment test_runner.h - tiny header-only
assertion + registration framework.` documenting intent. assertion + registration framework.
2 `// No external dependencies. Each test Comment No external dependencies. Each test
file calls REGISTER_TEST(...) at file documenting intent. file calls REGISTER_TEST(...) at file
scope.` scope.

Page 401 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


3 `#pragma once` Compiler directive #pragma once
(packing, once, etc.).
4 `` Blank line for Separator between code blocks.
readability.
5 `#include <iostream>` Import another #include <iostream>
header file into this
compilation unit.
6 `#include <string>` Import another #include <string>
header file into this
compilation unit.
7 `#include <vector>` Import another #include <vector>
header file into this
compilation unit.
8 `#include <functional>` Import another #include <functional>
header file into this
compilation unit.
9 `#include <sstream>` Import another #include <sstream>
header file into this
compilation unit.
10 `#include <cmath>` Import another #include <cmath>
header file into this
compilation unit.
11 `` Blank line for Separator between code blocks.
readability.
12 `namespace nads_test {` Start a named code namespace nads_test {
region so names do
not clash globally.
13 `` Blank line for Separator between code blocks.
readability.
14 `struct TestCase {` Source code line. struct TestCase {
15 ` std::string name;` Executable std::string name;
statement.
16 ` std::function<void()> fn;` Executable std::function<void()> fn;
statement.
17 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
18 `` Blank line for Separator between code blocks.
readability.
19 `inline std::vector<TestCase>& registry() Source code line. inline std::vector<TestCase>&
{` registry() {
20 ` static std::vector<TestCase> r;` Executable static std::vector<TestCase> r;
statement.
21 ` return r;` Exit function and give return r;
back a value.
22 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
23 `` Blank line for Separator between code blocks.
readability.
24 `struct Registrar {` Source code line. struct Registrar {

Page 402 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


25 ` Registrar(const std::string& name, Named constant — Registrar(const std::string& name,
std::function<void()> fn) {` value should not std::function<void()> fn) {
change.
26 ` registry().push_back({name, Executable registry().push_back({name,
std::move(fn)});` statement. std::move(fn)});
27 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
28 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
29 `` Blank line for Separator between code blocks.
readability.
30 `struct AssertFailure {` Source code line. struct AssertFailure {
31 ` std::string msg;` Executable std::string msg;
statement.
32 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
33 `` Blank line for Separator between code blocks.
readability.
34 `inline void check(bool ok, const char* Named constant — inline void check(bool ok, const char*
expr, const char* file, int line, const value should not expr, const char* file, int line, const s
std::string& extra = "") {` change.
35 ` if (!ok) {` Conditional branch if (!ok) {
— run code only
when condition true.
36 ` std::ostringstream s;` Executable std::ostringstream s;
statement.
37 ` s << file << ":" << line << " " << Executable s << file << ":" << line << " " << expr;
expr;` statement.
38 ` if (![Link]()) s << " [" << Conditional branch if (![Link]()) s << " [" << extra
extra << "]";` — run code only << "]";
when condition true.
39 ` throw AssertFailure{ [Link]() };` Executable throw AssertFailure{ [Link]() };
statement.
40 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
41 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
42 `` Blank line for Separator between code blocks.
readability.
43 `inline int run_all() {` Source code line. inline int run_all() {
44 ` int passed = 0, failed = 0;` Executable int passed = 0, failed = 0;
statement.
45 ` for (const auto& t : registry()) {` Loop over items or for (const auto& t : registry()) {
until condition
changes.

Page 403 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


46 ` std::cout << "[RUN ] " << [Link] Executable std::cout << "[RUN ] " << [Link] <<
<< "\n";` statement. "\n";
47 ` try {` Source code line. try {
48 ` [Link]();` Executable [Link]();
statement.
49 ` std::cout << "[ OK ] " << [Link] Executable std::cout << "[ OK ] " << [Link] << "\n";
<< "\n";` statement.
50 ` ++passed;` Executable ++passed;
statement.
51 ` } catch (const AssertFailure& e) {` Named constant — } catch (const AssertFailure& e) {
value should not
change.
52 ` std::cout << "[FAIL] " << [Link] Executable std::cout << "[FAIL] " << [Link] << "\n
<< "\n " << [Link] << "\n";` statement. " << [Link] << "\n";
53 ` ++failed;` Executable ++failed;
statement.
54 ` } catch (const std::exception& e) {` Named constant — } catch (const std::exception& e) {
value should not
change.
55 ` std::cout << "[FAIL] " << [Link] Executable std::cout << "[FAIL] " << [Link] << "\n
<< "\n exception: " << [Link]() << statement. exception: " << [Link]() << "\n";
"\n";`
56 ` ++failed;` Executable ++failed;
statement.
57 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
58 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
59 ` std::cout << "\n=== " << passed << " Executable std::cout << "\n=== " << passed << "
passed, " << failed << " failed ===\n";` statement. passed, " << failed << " failed ===\n";
60 ` return failed;` Exit function and give return failed;
back a value.
61 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
62 `` Blank line for Separator between code blocks.
readability.
63 `} // namespace nads_test` Source code line. } // namespace nads_test
64 `` Blank line for Separator between code blocks.
readability.
65 `#define REQUIRE(cond) Comment define REQUIRE(cond)
::nads_test::check((cond), #cond, documenting intent. ::nads_test::check((cond), #cond,
__FILE__, __LINE__)` __FILE__, __LINE__)
66 `#define REQUIRE_EQ(a, b) do { \` Comment define REQUIRE_EQ(a, b) do { \
documenting intent.
67 ` auto _va = (a); auto _vb = (b); \` Source code line. auto _va = (a); auto _vb = (b); \
68 ` std::ostringstream _s; _s << #a " == " Source code line. std::ostringstream _s; _s << #a " == "
#b " (" << _va << " vs " << _vb << ")"; \` #b " (" << _va << " vs " << _vb << ")"; \

Page 404 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


69 ` ::nads_test::check(_va == _vb, Source code line. ::nads_test::check(_va == _vb,
_s.str().c_str(), __FILE__, __LINE__); \` _s.str().c_str(), __FILE__, __LINE__); \
70 `} while (0)` Source code line. } while (0)
71 `#define REQUIRE_NEAR(a, b, eps) do Comment define REQUIRE_NEAR(a, b, eps) do {
{ \` documenting intent. \
72 ` double _va = (a); double _vb = (b); \` Source code line. double _va = (a); double _vb = (b); \
73 ` std::ostringstream _s; _s << #a " ≈ " " << _va << " - " << < " << (eps) << ")"; \`
#b " (\ _vb << "\
74 ` ::nads_test::check(std::fabs(_va - Source code line. ::nads_test::check(std::fabs(_va - _vb)
_vb) < (eps), _s.str().c_str(), __FILE__, < (eps), _s.str().c_str(), __FILE__,
__LINE__); \` __LINE__); \
75 `} while (0)` Source code line. } while (0)
76 `` Blank line for Separator between code blocks.
readability.
77 `#define REGISTER_TEST(name) \` Comment define REGISTER_TEST(name) \
documenting intent.
78 ` static void test_##name(); \` Source code line. static void test_##name(); \
79 ` static ::nads_test::Registrar Source code line. static ::nads_test::Registrar
reg_##name(#name, test_##name); \` reg_##name(#name, test_##name); \
80 ` static void test_##name()` Source code line. static void test_##name()

File: nads/tests/test_running_stats.cpp
Total lines: 35

Lin Source Easy Technical Explanation


e Explanati
on
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "running_stats.h"` Import #include "running_stats.h"
another
header file
into this
compilation
unit.
3 `#include <cmath>` Import #include <cmath>
another
header file
into this
compilation
unit.

Page 405 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
4 `` Blank line Separator between code blocks.
for
readability.
5 `using namespace nads;` Executable using namespace nads;
statement.
6 `` Blank line Separator between code blocks.
for
readability.
7 `REGISTER_TEST(running_stats_mean_variance_ba Source REGISTER_TEST(running_stats_mean_vari
sic) {` code line. ance_basic) {
8 ` RunningStats s;` Executable RunningStats s;
statement.
9 ` for (double v : {2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0}) Loop over for (double v : {2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0,
[Link](v);` items or 9.0}) [Link](v);
until
condition
changes.
10 ` REQUIRE_EQ([Link](), 8u);` Executable REQUIRE_EQ([Link](), 8u);
statement.
11 ` REQUIRE_NEAR([Link](), 5.0, 1e-9);` Executable REQUIRE_NEAR([Link](), 5.0, 1e-9);
statement.
12 ` REQUIRE_NEAR([Link](), 32.0/7.0, 1e-9); // Source REQUIRE_NEAR([Link](), 32.0/7.0, 1e-
sample variance` code line. 9); // sample variance
13 ` REQUIRE_NEAR([Link](), std::sqrt(32.0/7.0), Executable REQUIRE_NEAR([Link](),
1e-9);` statement. std::sqrt(32.0/7.0), 1e-9);
14 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
15 `` Blank line Separator between code blocks.
for
readability.
16 `REGISTER_TEST(running_stats_zscore_zero_when Compare Z-score or normalized score.
_no_variation) {` value to
learned
baseline
statistically.
17 ` RunningStats s;` Executable RunningStats s;
statement.
18 ` for (int i = 0; i < 10; ++i) [Link](5.0);` Loop over for (int i = 0; i < 10; ++i) [Link](5.0);
items or
until
condition
changes.
19 ` REQUIRE_NEAR([Link](5.0), 0.0, 1e-9);` Compare Z-score or normalized score.
value to
learned
baseline
statistically.
20 `}` Brace or C/C++ syntax structure.
parenthesis

Page 406 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
closing/ope
ning a
block.
21 `` Blank line Separator between code blocks.
for
readability.
22 `REGISTER_TEST(running_stats_zscore_outlier) {` Compare Z-score or normalized score.
value to
learned
baseline
statistically.
23 ` RunningStats s;` Executable RunningStats s;
statement.
24 ` for (double v : {10, 11, 9, 10, 12, 11, 9, 10, 11, 10}) Loop over for (double v : {10, 11, 9, 10, 12, 11, 9, 10,
[Link](v);` items or 11, 10}) [Link](v);
until
condition
changes.
25 ` double z = [Link](50);` Compare Z-score or normalized score.
value to
learned
baseline
statistically.
26 ` REQUIRE(z > 5.0);` Executable REQUIRE(z > 5.0);
statement.
27 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
28 `` Blank line Separator between code blocks.
for
readability.
29 `REGISTER_TEST(normalize_z_caps_at_1) {` Compare Z-score or normalized score.
value to
learned
baseline
statistically.
30 ` REQUIRE_NEAR(normalize_z(0.0, 3.0), 0.0, 1e- Compare Z-score or normalized score.
9);` value to
learned
baseline
statistically.
31 ` REQUIRE_NEAR(normalize_z(3.0, 3.0), 1.0, 1e- Compare Z-score or normalized score.
9);` value to
learned
baseline
statistically.
32 ` REQUIRE_NEAR(normalize_z(100.0, 3.0), 1.0, Compare Z-score or normalized score.
1e-9);` value to
learned
baseline
statistically.

Page 407 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
33 ` REQUIRE_NEAR(normalize_z(-3.0, 3.0), 1.0, 1e- Compare Z-score or normalized score.
9);` value to
learned
baseline
statistically.
34 ` REQUIRE_NEAR(normalize_z(1.5, 3.0), 0.5, 1e- Compare Z-score or normalized score.
9);` value to
learned
baseline
statistically.
35 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.

File: nads/tests/test_stat_detector.cpp
Total lines: 43

Lin Source Easy Technical Explanation


e Explanati
on
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "stat_detector.h"` Import #include "stat_detector.h"
another
header file
into this
compilation
unit.
3 `` Blank line Separator between code blocks.
for
readability.
4 `using namespace nads;` Executable using namespace nads;
statement.
5 `` Blank line Separator between code blocks.
for
readability.
6 `REGISTER_TEST(stat_detector_normal_traffic_ Source REGISTER_TEST(stat_detector_normal_traffic_
no_alert) {` code line. no_alert) {
7 ` StatisticalDetector d;` Executable StatisticalDetector d;
statement.

Page 408 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
8 ` // Feed 100 normal flows. None should be Comment Feed 100 normal flows. None should be high-
high-scored.` documentin scored.
g intent.
9 ` int high_score_count = 0;` Executable int high_score_count = 0;
statement.
10 ` for (int i = 0; i < 100; ++i) {` Loop over for (int i = 0; i < 100; ++i) {
items or
until
condition
changes.
11 ` FlowRecord r;` Executable FlowRecord r;
statement.
12 ` r.first_seen_us = 0;` Executable r.first_seen_us = 0;
statement.
13 ` r.last_seen_us = 1'000'000;` Executable r.last_seen_us = 1'000'000;
statement.
14 ` [Link] = 100000 + (i % 10) * 1000;` Executable [Link] = 100000 + (i % 10) * 1000;
statement.
15 ` [Link] = 50 + (i % 5);` Executable [Link] = 50 + (i % 5);
statement.
16 ` r.mean_pkt_size = 500 + (i % 7);` Executable r.mean_pkt_size = 500 + (i % 7);
statement.
17 ` auto res = [Link](r);` Executable auto res = [Link](r);
statement.
18 ` if ([Link] > 0.6) ++high_score_count;` Conditional if ([Link] > 0.6) ++high_score_count;
branch —
run code
only when
condition
true.
19 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
20 ` REQUIRE(high_score_count <= 5); // tolerate Source REQUIRE(high_score_count <= 5); // tolerate a
a couple of false positives` code line. couple of false positives
21 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
22 `` Blank line Separator between code blocks.
for
readability.
23 `REGISTER_TEST(stat_detector_flags_outlier_af Source REGISTER_TEST(stat_detector_flags_outlier_af
ter_baseline) {` code line. ter_baseline) {
24 ` StatisticalDetector d;` Executable StatisticalDetector d;
statement.
25 ` for (int i = 0; i < 100; ++i) {` Loop over for (int i = 0; i < 100; ++i) {
items or

Page 409 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
until
condition
changes.
26 ` FlowRecord r;` Executable FlowRecord r;
statement.
27 ` r.first_seen_us = 0;` Executable r.first_seen_us = 0;
statement.
28 ` r.last_seen_us = 1'000'000;` Executable r.last_seen_us = 1'000'000;
statement.
29 ` [Link] = 10000.0 + (i % 5) * 100;` Executable [Link] = 10000.0 + (i % 5) * 100;
statement.
30 ` [Link] = 10.0 + (i % 3);` Executable [Link] = 10.0 + (i % 3);
statement.
31 ` r.mean_pkt_size = 200.0;` Executable r.mean_pkt_size = 200.0;
statement.
32 ` [Link](r);` Executable [Link](r);
statement.
33 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
34 ` FlowRecord big;` Executable FlowRecord big;
statement.
35 ` big.first_seen_us = 0;` Executable big.first_seen_us = 0;
statement.
36 ` big.last_seen_us = 1'000'000;` Executable big.last_seen_us = 1'000'000;
statement.
37 ` [Link] = 50'000'000.0; // 5000x baseline` Source [Link] = 50'000'000.0; // 5000x baseline
code line.
38 ` [Link] = 50000.0;` Executable [Link] = 50000.0;
statement.
39 ` big.mean_pkt_size = 1500.0;` Executable big.mean_pkt_size = 1500.0;
statement.
40 ` auto res = [Link](big);` Executable auto res = [Link](big);
statement.
41 ` REQUIRE([Link] > 0.8);` Executable REQUIRE([Link] > 0.8);
statement.
42 ` REQUIRE(res.is_anomaly);` Executable REQUIRE(res.is_anomaly);
statement.
43 `}` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.

Page 410 of 629


NADS Complete Technical Reference

File: nads/tests/test_temporal_detector.cpp
Total lines: 56

Lin Source Easy Technical Explanation


e Explanatio
n
1 `#include "test_runner.h"` Import #include "test_runner.h"
another
header file
into this
compilation
unit.
2 `#include "temporal_detector.h"` Import #include "temporal_detector.h"
another
header file
into this
compilation
unit.
3 `#include <cmath>` Import #include <cmath>
another
header file
into this
compilation
unit.
4 `` Blank line for Separator between code blocks.
readability.
5 `using namespace nads;` Executable using namespace nads;
statement.
6 `` Blank line for Separator between code blocks.
readability.
7 `static void fill_iat(FlowRecord& f, const Named static void fill_iat(FlowRecord& f, const
std::vector<int64_t>& iats) {` constant — std::vector<int64_t>& iats) {
value should
not change.
8 ` for (auto v : iats) f.iat_buffer.push_back(v);` Loop over for (auto v : iats) f.iat_buffer.push_back(v);
items or until
condition
changes.
9 ` double mean = 0.0;` Executable double mean = 0.0;
statement.
10 ` for (auto v : iats) mean += v;` Loop over for (auto v : iats) mean += v;
items or until
condition
changes.
11 ` mean /= [Link]();` Executable mean /= [Link]();
statement.
12 ` double var = 0.0;` Executable double var = 0.0;
statement.
13 ` for (auto v : iats) var += (v - mean) * (v - Loop over for (auto v : iats) var += (v - mean) * (v - mean);
mean);` items or until
condition
changes.
14 ` var /= [Link]();` Executable var /= [Link]();
statement.

Page 411 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
15 ` f.mean_iat = mean;` Executable f.mean_iat = mean;
statement.
16 ` f.stddev_iat = std::sqrt(var);` Executable f.stddev_iat = std::sqrt(var);
statement.
17 ` f.packet_count = [Link]() + 1;` Executable f.packet_count = [Link]() + 1;
statement.
18 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
19 `` Blank line for Separator between code blocks.
readability.
20 `REGISTER_TEST(temporal_perfect_beacon_fla Source code REGISTER_TEST(temporal_perfect_beacon_fla
gged) {` line. gged) {
21 ` TemporalDetector d;` Executable TemporalDetector d;
statement.
22 ` FlowRecord f;` Executable FlowRecord f;
statement.
23 ` // Perfectly regular: every 5 seconds` Comment Perfectly regular: every 5 seconds
documenting
intent.
24 ` std::vector<int64_t> iats(20, 5'000'000);` Executable std::vector<int64_t> iats(20, 5'000'000);
statement.
25 ` fill_iat(f, iats);` Executable fill_iat(f, iats);
statement.
26 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
27 ` REQUIRE([Link] >= 0.9);` Executable REQUIRE([Link] >= 0.9);
statement.
28 ` bool has_beacon = false;` Executable bool has_beacon = false;
statement.
29 ` for (const auto& flg : [Link]) if (flg == Loop over for (const auto& flg : [Link]) if (flg ==
"BEACON_PATTERN") has_beacon = true;` items or until "BEACON_PATTERN") has_beacon = true;
condition
changes.
30 ` REQUIRE(has_beacon);` Executable REQUIRE(has_beacon);
statement.
31 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
32 `` Blank line for Separator between code blocks.
readability.
33 `REGISTER_TEST(temporal_irregular_human_n Source code REGISTER_TEST(temporal_irregular_human_n
o_alert) {` line. o_alert) {
34 ` TemporalDetector d;` Executable TemporalDetector d;
statement.
35 ` FlowRecord f;` Executable FlowRecord f;
statement.

Page 412 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
36 ` // Highly variable IATs (human browsing)` Comment Highly variable IATs (human browsing)
documenting
intent.
37 ` std::vector<int64_t> iats = {` Source code std::vector<int64_t> iats = {
line.
38 ` 500'000, 12'000'000, 800'000, 30'000'000, Source code 500'000, 12'000'000, 800'000, 30'000'000,
2'000'000,` line. 2'000'000,
39 ` 45'000'000, 1'500'000, 8'000'000, Source code 45'000'000, 1'500'000, 8'000'000, 22'000'000,
22'000'000, 600'000,` line. 600'000,
40 ` 18'000'000, 3'200'000` Source code 18'000'000, 3'200'000
line.
41 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
42 ` fill_iat(f, iats);` Executable fill_iat(f, iats);
statement.
43 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
44 ` REQUIRE([Link] < 0.5);` Executable REQUIRE([Link] < 0.5);
statement.
45 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
46 `` Blank line for Separator between code blocks.
readability.
47 `REGISTER_TEST(temporal_too_few_samples_ Source code REGISTER_TEST(temporal_too_few_samples_
no_score) {` line. no_score) {
48 ` TemporalDetector d;` Executable TemporalDetector d;
statement.
49 ` FlowRecord f;` Executable FlowRecord f;
statement.
50 ` f.iat_buffer.push_back(1000);` Executable f.iat_buffer.push_back(1000);
statement.
51 ` f.iat_buffer.push_back(1100);` Executable f.iat_buffer.push_back(1100);
statement.
52 ` f.mean_iat = 1050;` Executable f.mean_iat = 1050;
statement.
53 ` f.stddev_iat = 50;` Executable f.stddev_iat = 50;
statement.
54 ` auto r = [Link](f);` Executable auto r = [Link](f);
statement.
55 ` REQUIRE_EQ([Link], 0.0);` Executable REQUIRE_EQ([Link], 0.0);
statement.
56 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 413 of 629


NADS Complete Technical Reference

File: nads/benchmarks/bench_capture.cpp
Total lines: 46

Line Source Easy Explanation Technical Explanation


1 `// Synthetic parse benchmark — build: Comment Synthetic parse benchmark — build:
add to CMake optionally` documenting intent. add to CMake optionally
2 `#include "parser.h"` Import another header #include "parser.h"
file into this
compilation unit.
3 `#include "types.h"` Import another header #include "types.h"
file into this
compilation unit.
4 `#include <chrono>` Import another header #include <chrono>
file into this
compilation unit.
5 `#include <iostream>` Import another header #include <iostream>
file into this
compilation unit.
6 `#include <vector>` Import another header #include <vector>
file into this
compilation unit.
7 `#include <cstring>` Import another header #include <cstring>
file into this
compilation unit.
8 `#include <arpa/inet.h>` Import another header #include <arpa/inet.h>
file into this
compilation unit.
9 `` Blank line for Separator between code blocks.
readability.
10 `using namespace nads;` Executable statement. using namespace nads;
11 `` Blank line for Separator between code blocks.
readability.
12 `int main() {` Source code line. int main() {
13 ` std::vector<uint8_t> frame(128, 0);` Executable statement. std::vector<uint8_t> frame(128, 0);
14 ` EthernetHeader eth{};` Executable statement. EthernetHeader eth{};
15 ` eth.ether_type = htons(0x0800);` Executable statement. eth.ether_type = htons(0x0800);
16 ` std::memcpy([Link](), &eth, Executable statement. std::memcpy([Link](), &eth, 14);
14);`
17 ` IPHeader ip{};` Executable statement. IPHeader ip{};
18 ` ip.version_ihl = 0x45;` Executable statement. ip.version_ihl = 0x45;
19 ` ip.total_length = htons(40);` Executable statement. ip.total_length = htons(40);
20 ` [Link] = PROTO_TCP;` Executable statement. [Link] = PROTO_TCP;
21 ` ip.src_ip = inet_addr("[Link]");` Executable statement. ip.src_ip = inet_addr("[Link]");
22 ` ip.dst_ip = inet_addr("[Link]");` Executable statement. ip.dst_ip = inet_addr("[Link]");

Page 414 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


23 ` std::memcpy([Link]() + 14, &ip, Executable statement. std::memcpy([Link]() + 14, &ip,
20);` 20);
24 ` TCPHeader tcp{};` Executable statement. TCPHeader tcp{};
25 ` tcp.src_port = htons(443);` Executable statement. tcp.src_port = htons(443);
26 ` tcp.dst_port = htons(52000);` Executable statement. tcp.dst_port = htons(52000);
27 ` tcp.data_offset = 0x50;` Executable statement. tcp.data_offset = 0x50;
28 ` [Link] = TCP_SYN;` Executable statement. [Link] = TCP_SYN;
29 ` std::memcpy([Link]() + 34, Executable statement. std::memcpy([Link]() + 34, &tcp,
&tcp, 20);` 20);
30 `` Blank line for Separator between code blocks.
readability.
31 ` PacketParser parser(1);` Executable statement. PacketParser parser(1);
32 ` const int N = 200000;` Named constant — const int N = 200000;
value should not
change.
33 ` auto t0 = Executable statement. auto t0 =
std::chrono::steady_clock::now();` std::chrono::steady_clock::now();
34 ` for (int i = 0; i < N; ++i) {` Loop over items or for (int i = 0; i < N; ++i) {
until condition
changes.
35 ` PacketInfo pkt;` Executable statement. PacketInfo pkt;
36 ` pkt.raw_bytes = frame;` Executable statement. pkt.raw_bytes = frame;
37 ` pkt.cap_length = [Link]();` Executable statement. pkt.cap_length = [Link]();
38 ` pkt.timestamp_us = i;` Executable statement. pkt.timestamp_us = i;
39 ` [Link](pkt);` Executable statement. [Link](pkt);
40 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
41 ` auto t1 = Executable statement. auto t1 =
std::chrono::steady_clock::now();` std::chrono::steady_clock::now();
42 ` double sec = Executable statement. double sec =
std::chrono::duration<double>(t1 - std::chrono::duration<double>(t1 -
t0).count();` t0).count();
43 ` std::cout << "parsed " << N << " pkts Source code line. std::cout << "parsed " << N << " pkts
in " << sec << "s ("` in " << sec << "s ("
44 ` << static_cast<int>(N / sec) Executable statement. << static_cast<int>(N / sec) << "
<< " pps)\n";` pps)\n";
45 ` return 0;` Exit function and give return 0;
back a value.
46 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

File: nads/tools/train_fusion.py

Page 415 of 629


NADS Complete Technical Reference

Total lines: 61

Line Source Easy Explanation Technical Explanation


1 `#!/usr/bin/env python3` Comment !/usr/bin/env python3
documenting intent.
2 `"""Train logistic fusion weights from Source code line. """Train logistic fusion weights from
[Link] (offline)."""` [Link] (offline)."""
3 `import json` Source code line. import json
4 `import argparse` Source code line. import argparse
5 `` Blank line for Separator between code blocks.
readability.
6 `DETECTORS = [` Source code line. DETECTORS = [
7 ` "statistical", "volume", "protocol", Source code line. "statistical", "volume", "protocol",
"baseline",` "baseline",
8 ` "graph", "temporal", "entropy",` Source code line. "graph", "temporal", "entropy",
9 `]` Source code line. ]
10 `` Blank line for Separator between code blocks.
readability.
11 `def featurize(alert):` Source code line. def featurize(alert):
12 ` scores = {[Link]("detector_name", d): Source code line. scores = {[Link]("detector_name", d):
[Link]("score", 0)` [Link]("score", 0)
13 ` for d in Loop over items or for d in [Link]("detector_results", [])}
[Link]("detector_results", [])}` until condition
changes.
14 ` if isinstance(next(iter([Link]()), Conditional branch if isinstance(next(iter([Link]()),
""), str):` — run code only ""), str):
when condition true.
15 ` m = {}` Source code line. m = {}
16 ` for k, v in [Link]("detectors", Loop over items or for k, v in [Link]("detectors",
{}).items():` until condition {}).items():
changes.
17 ` m[k] = v` Source code line. m[k] = v
18 ` if m:` Conditional branch if m:
— run code only
when condition true.
19 ` scores = m` Source code line. scores = m
20 ` return [float([Link](name, 0.0)) for Exit function and return [float([Link](name, 0.0)) for
name in DETECTORS]` give back a value. name in DETECTORS]
21 `` Blank line for Separator between code blocks.
readability.
22 `def main():` Source code line. def main():
23 ` ap = [Link]()` Source code line. ap = [Link]()
24 ` ap.add_argument("--alerts", Source code line. ap.add_argument("--alerts",
default="[Link]")` default="[Link]")
25 ` ap.add_argument("--out", Combine multiple Fusion / correlation logic.
default="fusion_weights.txt")` detector scores.
26 ` args = ap.parse_args()` Source code line. args = ap.parse_args()

Page 416 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


27 `` Blank line for Separator between code blocks.
readability.
28 ` with open([Link], encoding="utf- Source code line. with open([Link], encoding="utf-8")
8") as f:` as f:
29 ` data = [Link](f)` Source code line. data = [Link](f)
30 `` Blank line for Separator between code blocks.
readability.
31 ` X, y = [], []` Source code line. X, y = [], []
32 ` for a in data:` Loop over items or for a in data:
until condition
changes.
33 ` if "detectors" in a and not Conditional branch if "detectors" in a and not
[Link]("detector_results"):` — run code only [Link]("detector_results"):
when condition true.
34 ` feats = [float(a["detectors"].get(n, Source code line. feats = [float(a["detectors"].get(n, 0.0))
0.0)) for n in DETECTORS]` for n in DETECTORS]
35 ` else:` Source code line. else:
36 ` feats = featurize(a)` Source code line. feats = featurize(a)
37 ` [Link](feats)` Source code line. [Link](feats)
38 ` [Link](1 if [Link]("final_score", 0) Source code line. [Link](1 if [Link]("final_score", 0) >=
>= 0.7 else 0)` 0.7 else 0)
39 `` Blank line for Separator between code blocks.
readability.
40 ` if len(X) < 10:` Conditional branch if len(X) < 10:
— run code only
when condition true.
41 ` print("Need at least 10 alerts; got", Source code line. print("Need at least 10 alerts; got",
len(X))` len(X))
42 ` return 1` Exit function and return 1
give back a value.
43 `` Blank line for Separator between code blocks.
readability.
44 ` try:` Source code line. try:
45 ` import numpy as np` Source code line. import numpy as np
46 ` from sklearn.linear_model import Source code line. from sklearn.linear_model import
LogisticRegression` LogisticRegression
47 ` except ImportError:` Source code line. except ImportError:
48 ` print("Install: pip install numpy Source code line. print("Install: pip install numpy scikit-
scikit-learn")` learn")
49 ` return 1` Exit function and return 1
give back a value.
50 `` Blank line for Separator between code blocks.
readability.
51 ` clf = Source code line. clf =
LogisticRegression(max_iter=2000)` LogisticRegression(max_iter=2000)
52 ` [Link]([Link](X), [Link](y))` Source code line. [Link]([Link](X), [Link](y))
53 ` with open([Link], "w", Source code line. with open([Link], "w", encoding="utf-
encoding="utf-8") as out:` 8") as out:

Page 417 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


54 ` [Link](f"bias Source code line. [Link](f"bias {clf.intercept_[0]:.6f}\n")
{clf.intercept_[0]:.6f}\n")`
55 ` for name, coef in zip(DETECTORS, Loop over items or for name, coef in zip(DETECTORS,
clf.coef_[0]):` until condition clf.coef_[0]):
changes.
56 ` [Link](f"{name} {coef:.6f}\n")` Source code line. [Link](f"{name} {coef:.6f}\n")
57 ` print("Wrote", [Link])` Source code line. print("Wrote", [Link])
58 ` return 0` Exit function and return 0
give back a value.
59 `` Blank line for Separator between code blocks.
readability.
60 `if __name__ == "__main__":` Conditional branch if __name__ == "__main__":
— run code only
when condition true.
61 ` raise SystemExit(main())` Source code line. raise SystemExit(main())

File: nads/[Link]
Total lines: 56

Line Source Easy Explanation Technical Explanation


1 `# NADS Configuration File` Comment NADS Configuration File
documenting intent.
2 `# Lines starting with # are comments. Comment Lines starting with # are comments.
Format: key = value` documenting intent. Format: key = value
3 `# CLI flags override values set here.` Comment CLI flags override values set here.
documenting intent.
4 `` Blank line for Separator between code blocks.
readability.
5 `# --- Capture ---` Comment --- Capture ---
documenting intent.
6 `interface = lo` Source code line. interface = lo
7 `bpf_filter =` Source code line. bpf_filter =
8 `` Blank line for Separator between code blocks.
readability.
9 `# --- Output ---` Comment --- Output ---
documenting intent.
10 `output_log = [Link]` Source code line. output_log = [Link]
11 `json_output = [Link]` Source code line. json_output = [Link]
12 `` Blank line for Separator between code blocks.
readability.
13 `# --- Thresholds ---` Comment --- Thresholds ---
documenting intent.
14 `alert_threshold = 0.75` Source code line. alert_threshold = 0.75

Page 418 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


15 `critical_threshold = 0.9` Source code line. critical_threshold = 0.9
16 `flow_timeout_sec = 30` Source code line. flow_timeout_sec = 30
17 `syn_flood_threshold_pps = 500` Source code line. syn_flood_threshold_pps = 500
18 `packet_flood_threshold_pps = 2000` Source code line. packet_flood_threshold_pps = 2000
19 `` Blank line for Separator between code blocks.
readability.
20 `# --- Adaptive statistics ---` Comment --- Adaptive statistics ---
documenting intent.
21 `ewma_alpha = 0.05` Source code line. ewma_alpha = 0.05
22 `percentile_window = 256` Source code line. percentile_window = 256
23 `adaptive_thresholds = true` Source code line. adaptive_thresholds = true
24 `` Blank line for Separator between code blocks.
readability.
25 `# --- Fusion / correlation ---` Comment --- Fusion / correlation ---
documenting intent.
26 `# fusion_type = weighted` Comment fusion_type = weighted
documenting intent.
27 `fusion_type = logistic` Combine multiple Fusion / correlation logic.
detector scores.
28 `use_logistic_fusion = false` Source code line. use_logistic_fusion = false
29 `fusion_weights_path = Combine multiple Fusion / correlation logic.
fusion_weights.txt` detector scores.
30 `fusion_learning_rate = 0.01` Combine multiple Fusion / correlation logic.
detector scores.
31 `correlation_window_sec = 30` Source code line. correlation_window_sec = 30
32 `use_legacy_fusion_boost = true` Combine multiple Fusion / correlation logic.
detector scores.
33 `` Blank line for Separator between code blocks.
readability.
34 `# --- Profiling ---` Comment --- Profiling ---
documenting intent.
35 `use_per_service_baseline = true` Source code line. use_per_service_baseline = true
36 `` Blank line for Separator between code blocks.
readability.
37 `# --- Observability ---` Comment --- Observability ---
documenting intent.
38 `metrics_enabled = true` Source code line. metrics_enabled = true
39 `webhook_url =` Source code line. webhook_url =
40 `` Blank line for Separator between code blocks.
readability.
41 `# --- Advanced detectors ---` Comment --- Advanced detectors ---
documenting intent.
42 `enable_slow_scan = true` Source code line. enable_slow_scan = true
43 `enable_beacon_detector = true` Source code line. enable_beacon_detector = true
44 `enable_burst_detector = true` Source code line. enable_burst_detector = true
45 `enable_dns_tunnel = true` Source code line. enable_dns_tunnel = true

Page 419 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


46 `enable_syn_ratio = true` Source code line. enable_syn_ratio = true
47 `enable_long_lived_flow = true` Source code line. enable_long_lived_flow = true
48 `` Blank line for Separator between code blocks.
readability.
49 `# --- Detector Weights (should sum ~ Comment --- Detector Weights (should sum ~
1.0) ---` documenting intent. 1.0) ---
50 `w_statistical = 0.15` Source code line. w_statistical = 0.15
51 `w_volume = 0.20` Source code line. w_volume = 0.20
52 `w_protocol = 0.20` Source code line. w_protocol = 0.20
53 `w_baseline = 0.10` Source code line. w_baseline = 0.10
54 `w_graph = 0.10` Source code line. w_graph = 0.10
55 `w_temporal = 0.05` Source code line. w_temporal = 0.05
56 `w_entropy = 0.05` Source code line. w_entropy = 0.05

File: nads/fusion_weights.txt
Total lines: 8

Line Source Easy Explanation Technical Explanation


1 `bias -0.8` Source code line. bias -0.8
2 `statistical 1.0` Source code line. statistical 1.0
3 `volume 1.2` Source code line. volume 1.2
4 `protocol 1.0` Source code line. protocol 1.0
5 `baseline 0.8` Source code line. baseline 0.8
6 `graph 0.7` Source code line. graph 0.7
7 `temporal 0.6` Source code line. temporal 0.6
8 `entropy 0.4` Source code line. entropy 0.4

File: nads/[Link]
Total lines: 103

Lin Source Easy Technical Explanation


e Explanati
on
1 `cmake_minimum_required(VERSION 3.16)` Source cmake_minimum_required(VERSION 3.16)
code line.
2 `project(NADS LANGUAGES CXX VERSION 1.0)` Source project(NADS LANGUAGES CXX VERSION 1.0)
code line.

Page 420 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
3 `` Blank line Separator between code blocks.
for
readability.
4 `set(CMAKE_CXX_STANDARD 17)` Source set(CMAKE_CXX_STANDARD 17)
code line.
5 `set(CMAKE_CXX_STANDARD_REQUIRED Source set(CMAKE_CXX_STANDARD_REQUIRED ON)
ON)` code line.
6 `set(CMAKE_CXX_EXTENSIONS OFF)` Source set(CMAKE_CXX_EXTENSIONS OFF)
code line.
7 `` Blank line Separator between code blocks.
for
readability.
8 `if(NOT CMAKE_BUILD_TYPE)` Source if(NOT CMAKE_BUILD_TYPE)
code line.
9 ` set(CMAKE_BUILD_TYPE Release)` Source set(CMAKE_BUILD_TYPE Release)
code line.
10 `endif()` Source endif()
code line.
11 `` Blank line Separator between code blocks.
for
readability.
12 `# Compiler flags` Comment Compiler flags
documentin
g intent.
13 `if(CMAKE_CXX_COMPILER_ID STREQUAL Source if(CMAKE_CXX_COMPILER_ID STREQUAL
"GNU" OR CMAKE_CXX_COMPILER_ID code line. "GNU" OR CMAKE_CXX_COMPILER_ID
MATCHES "Clang")` MATCHES "Clang")
14 ` add_compile_options(-Wall -Wextra - Source add_compile_options(-Wall -Wextra -Wpedantic -
Wpedantic -Wno-unused-parameter)` code line. Wno-unused-parameter)
15 ` if(CMAKE_BUILD_TYPE STREQUAL Source if(CMAKE_BUILD_TYPE STREQUAL "Release")
"Release")` code line.
16 ` add_compile_options(-O2)` Source add_compile_options(-O2)
code line.
17 ` endif()` Source endif()
code line.
18 ` if(CMAKE_BUILD_TYPE STREQUAL Source if(CMAKE_BUILD_TYPE STREQUAL "Debug")
"Debug")` code line.
19 ` add_compile_options(-g -O0 - Source add_compile_options(-g -O0 -
fsanitize=address,undefined)` code line. fsanitize=address,undefined)
20 ` add_link_options(- Source add_link_options(-fsanitize=address,undefined)
fsanitize=address,undefined)` code line.
21 ` endif()` Source endif()
code line.
22 `endif()` Source endif()
code line.
23 `` Blank line Separator between code blocks.
for
readability.

Page 421 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
24 `# Find libpcap` Comment Find libpcap
documentin
g intent.
25 `find_path(PCAP_INCLUDE_DIR pcap.h` Source find_path(PCAP_INCLUDE_DIR pcap.h
code line.
26 ` PATHS /usr/include /usr/local/include Source PATHS /usr/include /usr/local/include
/opt/homebrew/include)` code line. /opt/homebrew/include)
27 `find_library(PCAP_LIBRARY NAMES pcap` Source find_library(PCAP_LIBRARY NAMES pcap
code line.
28 ` PATHS /usr/lib /usr/local/lib /opt/homebrew/lib Source PATHS /usr/lib /usr/local/lib /opt/homebrew/lib
/usr/lib/x86_64-linux-gnu)` code line. /usr/lib/x86_64-linux-gnu)
29 `` Blank line Separator between code blocks.
for
readability.
30 `if(NOT PCAP_INCLUDE_DIR OR NOT Source if(NOT PCAP_INCLUDE_DIR OR NOT
PCAP_LIBRARY)` code line. PCAP_LIBRARY)
31 ` message(FATAL_ERROR` Source message(FATAL_ERROR
code line.
32 ` "libpcap not found. Install it:\n"` Source "libpcap not found. Install it:\n"
code line.
33 ` " Ubuntu/Debian: sudo apt install libpcap- Source " Ubuntu/Debian: sudo apt install libpcap-dev\n"
dev\n"` code line.
34 ` " Fedora/RHEL: sudo dnf install libpcap- Source " Fedora/RHEL: sudo dnf install libpcap-
devel\n"` code line. devel\n"
35 ` " macOS: brew install libpcap\n")` Source " macOS: brew install libpcap\n")
code line.
36 `endif()` Source endif()
code line.
37 `` Blank line Separator between code blocks.
for
readability.
38 `message(STATUS "libpcap include: Source message(STATUS "libpcap include:
${PCAP_INCLUDE_DIR}")` code line. ${PCAP_INCLUDE_DIR}")
39 `message(STATUS "libpcap library: Source message(STATUS "libpcap library:
${PCAP_LIBRARY}")` code line. ${PCAP_LIBRARY}")
40 `` Blank line Separator between code blocks.
for
readability.
41 `include_directories(${CMAKE_CURRENT_SOUR Source include_directories(${CMAKE_CURRENT_SOUR
CE_DIR}/include ${PCAP_INCLUDE_DIR})` code line. CE_DIR}/include ${PCAP_INCLUDE_DIR})
42 `` Blank line Separator between code blocks.
for
readability.
43 `# Library of all NADS modules (used by both Comment Library of all NADS modules (used by both main
main + tests)` documentin + tests)
g intent.
44 `set(NADS_SRCS` Source set(NADS_SRCS
code line.

Page 422 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
45 ` src/[Link]` Source src/[Link]
code line.
46 ` src/running_stats.cpp` Source src/running_stats.cpp
code line.
47 ` src/config_loader.cpp` Source src/config_loader.cpp
code line.
48 ` src/[Link]` Source src/[Link]
code line.
49 ` src/[Link]` Source src/[Link]
code line.
50 ` src/l7_parser.cpp` Source src/l7_parser.cpp
code line.
51 ` src/flow_table.cpp` Source src/flow_table.cpp
code line.
52 ` src/stat_detector.cpp` Source src/stat_detector.cpp
code line.
53 ` src/volume_detector.cpp` Source src/volume_detector.cpp
code line.
54 ` src/protocol_analyzer.cpp` Source src/protocol_analyzer.cpp
code line.
55 ` src/baseline_engine.cpp` Source src/baseline_engine.cpp
code line.
56 ` src/graph_detector.cpp` Source src/graph_detector.cpp
code line.
57 ` src/temporal_detector.cpp` Source src/temporal_detector.cpp
code line.
58 ` src/entropy_profiler.cpp` Source src/entropy_profiler.cpp
code line.
59 ` src/threat_classifier.cpp` Source src/threat_classifier.cpp
code line.
60 ` src/fusion_engine.cpp` Combine Fusion / correlation logic.
multiple
detector
scores.
61 ` src/logistic_fusion.cpp` Source src/logistic_fusion.cpp
code line.
62 ` src/correlation_engine.cpp` Source src/correlation_engine.cpp
code line.
63 ` src/advanced_detectors.cpp` Source src/advanced_detectors.cpp
code line.
64 ` src/metrics_registry.cpp` Source src/metrics_registry.cpp
code line.
65 ` src/alert_system.cpp` Source src/alert_system.cpp
code line.
66 ` src/console_display.cpp` Source src/console_display.cpp
code line.
67 ` src/[Link]` Source src/[Link]
code line.

Page 423 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanati
on
68 ` src/http_server.cpp` Source src/http_server.cpp
code line.
69 `)` Brace or C/C++ syntax structure.
parenthesis
closing/ope
ning a
block.
70 `` Blank line Separator between code blocks.
for
readability.
71 `add_library(nads_lib STATIC ${NADS_SRCS})` Source add_library(nads_lib STATIC ${NADS_SRCS})
code line.
72 `target_link_libraries(nads_lib PUBLIC Source target_link_libraries(nads_lib PUBLIC
${PCAP_LIBRARY} pthread)` code line. ${PCAP_LIBRARY} pthread)
73 `` Blank line Separator between code blocks.
for
readability.
74 `# Main executable` Comment Main executable
documentin
g intent.
75 `add_executable(nads src/[Link])` Source add_executable(nads src/[Link])
code line.
76 `target_link_libraries(nads PRIVATE nads_lib)` Source target_link_libraries(nads PRIVATE nads_lib)
code line.
77 `` Blank line Separator between code blocks.
for
readability.
78 `# Tests` Comment Tests
documentin
g intent.
79 `enable_testing()` Source enable_testing()
code line.
80 `add_executable(run_tests` Source add_executable(run_tests
code line.

Line Source Easy Technical Explanation


Explanation
81 ` tests/run_tests.cpp` Source code line. tests/run_tests.cpp
82 ` tests/test_parser.cpp` Source code line. tests/test_parser.cpp
83 ` tests/test_flow_table.cpp` Source code line. tests/test_flow_table.cpp
84 ` tests/test_running_stats.cpp` Source code line. tests/test_running_stats.cpp
85 ` tests/test_adaptive_stats.cpp` Source code line. tests/test_adaptive_stats.cpp
86 ` tests/test_correlation.cpp` Source code line. tests/test_correlation.cpp
87 ` tests/test_stat_detector.cpp` Source code line. tests/test_stat_detector.cpp
88 ` tests/test_protocol_analyzer.cpp` Source code line. tests/test_protocol_analyzer.cpp
89 ` tests/test_graph_detector.cpp` Source code line. tests/test_graph_detector.cpp
90 ` tests/test_temporal_detector.cpp` Source code line. tests/test_temporal_detector.cpp

Page 424 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
91 ` tests/test_entropy.cpp` Source code line. tests/test_entropy.cpp
92 ` tests/test_fusion.cpp` Source code line. tests/test_fusion.cpp
93 ` tests/test_classifier.cpp` Source code line. tests/test_classifier.cpp
94 `)` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
95 `target_link_libraries(run_tests PRIVATE Source code line. target_link_libraries(run_tests PRIVATE
nads_lib)` nads_lib)
96 `add_test(NAME unit_tests COMMAND Source code line. add_test(NAME unit_tests COMMAND
run_tests)` run_tests)
97 `` Blank line for Separator between code blocks.
readability.
98 `# Installation` Comment Installation
documenting intent.
99 `install(TARGETS nads RUNTIME Source code line. install(TARGETS nads RUNTIME
DESTINATION bin)` DESTINATION bin)
100 `install(FILES [Link] DESTINATION Source code line. install(FILES [Link] DESTINATION
etc/nads OPTIONAL)` etc/nads OPTIONAL)
101 `` Blank line for Separator between code blocks.
readability.
102 `add_executable(bench_capture Source code line. add_executable(bench_capture
benchmarks/bench_capture.cpp)` benchmarks/bench_capture.cpp)
103 `target_link_libraries(bench_capture Source code line. target_link_libraries(bench_capture
PRIVATE nads_lib)` PRIVATE nads_lib)

File: webwireshark/src/lib/[Link]
Total lines: 296

Li Source Easy Technical Explanation


n Expla
e nation
1 `/**` Block /**
comme
nt.
2 ` * [Link]` Block * [Link]
comme
nt.
3 ` * Real API hooks pointing to the NADS C++ Block * Real API hooks pointing to the NADS C++ backend
backend on port 8080.` comme on port 8080.
nt.
4 ` * Falls back gracefully if the backend is Block * Falls back gracefully if the backend is unreachable.
unreachable.` comme
nt.

Page 425 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
5 ` */` Block */
comme
nt.
6 `` Blank Separator between code blocks.
line for
readabi
lity.
7 `// ─── Types Comm ─── Types
───────────────────────────────── ent ─────────────────────────────────
───────────────────────────────── docum ─────────────────────────────────
──` enting ──
intent.
8 `` Blank Separator between code blocks.
line for
readabi
lity.
9 `export type NadsAlertSeverity = 'critical' \ 'high' \ 'medium' \
1 `export type NetworkFlowStatus = 'active' \ 'closed' 'suspicious' \
0 \
1 `export type CaptureStatusState = 'idle' \ 'capturi 'paused' \
1 ng' \
1 `` Blank Separator between code blocks.
2 line for
readabi
lity.
1 `export interface ProtocolField {` Source export interface ProtocolField {
3 code
line.
1 ` name: string;` Execut name: string;
4 able
statem
ent.
1 ` value: string;` Execut value: string;
5 able
statem
ent.
1 ` offset?: number;` Execut offset?: number;
6 able
statem
ent.
1 ` length?: number;` Execut length?: number;
7 able
statem
ent.
1 `}` Brace C/C++ syntax structure.
8 or
parent
hesis
closing
/openin
ga
block.

Page 426 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
1 `` Blank Separator between code blocks.
9 line for
readabi
lity.
2 `export interface ProtocolLayer {` Source export interface ProtocolLayer {
0 code
line.
2 ` name: string;` Execut name: string;
1 able
statem
ent.
2 ` fields: ProtocolField[];` Execut fields: ProtocolField[];
2 able
statem
ent.
2 `}` Brace C/C++ syntax structure.
3 or
parent
hesis
closing
/openin
ga
block.
2 `` Blank Separator between code blocks.
4 line for
readabi
lity.
2 `export interface Packet {` Source export interface Packet {
5 code
line.
2 ` no: number;` Execut no: number;
6 able
statem
ent.
2 ` time: string;` Execut time: string;
7 able
statem
ent.
2 ` src: string;` Execut src: string;
8 able
statem
ent.
2 ` dst: string;` Execut dst: string;
9 able
statem
ent.
3 ` protocol: string;` Execut protocol: string;
0 able
statem
ent.
3 ` length: number;` Execut length: number;
1 able
statem
ent.

Page 427 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
3 ` info: string;` Execut info: string;
2 able
statem
ent.
3 ` rawHex?: string;` Execut rawHex?: string;
3 able
statem
ent.
3 ` layers?: ProtocolLayer[];` Execut layers?: ProtocolLayer[];
4 able
statem
ent.
3 `}` Brace C/C++ syntax structure.
5 or
parent
hesis
closing
/openin
ga
block.
3 `` Blank Separator between code blocks.
6 line for
readabi
lity.
3 `export interface NadsAlert {` Source export interface NadsAlert {
7 code
line.
3 ` id: string;` Execut id: string;
8 able
statem
ent.
3 ` severity: NadsAlertSeverity;` Execut severity: NadsAlertSeverity;
9 able
statem
ent.
4 ` category: string;` Execut category: string;
0 able
statem
ent.
4 ` timestamp: string;` Execut timestamp: string;
1 able
statem
ent.
4 ` detector: string;` Execut detector: string;
2 able
statem
ent.
4 ` mitreTechnique?: string;` Execut mitreTechnique?: string;
3 able
statem
ent.
4 ` mitreTactics?: string[];` Execut mitreTactics?: string[];
4 able

Page 428 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
statem
ent.
4 ` srcAddr: string;` Execut srcAddr: string;
5 able
statem
ent.
4 ` dstAddr: string;` Execut dstAddr: string;
6 able
statem
ent.
4 ` description: string;` Execut description: string;
7 able
statem
ent.
4 ` confidence: number;` Execut confidence: number;
8 able
statem
ent.
4 ` evidence?: string[];` Execut evidence?: string[];
9 able
statem
ent.
5 ` acknowledged: boolean;` Execut acknowledged: boolean;
0 able
statem
ent.
5 `}` Brace C/C++ syntax structure.
1 or
parent
hesis
closing
/openin
ga
block.
5 `` Blank Separator between code blocks.
2 line for
readabi
lity.
5 `export interface NetworkFlow {` Source export interface NetworkFlow {
3 code
line.
5 ` id: string;` Execut id: string;
4 able
statem
ent.
5 ` srcAddr: string;` Execut srcAddr: string;
5 able
statem
ent.
5 ` srcPort: number;` Execut srcPort: number;
6 able
statem
ent.

Page 429 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
5 ` dstAddr: string;` Execut dstAddr: string;
7 able
statem
ent.
5 ` dstPort: number;` Execut dstPort: number;
8 able
statem
ent.
5 ` protocol: string;` Execut protocol: string;
9 able
statem
ent.
6 ` packets: number;` Execut packets: number;
0 able
statem
ent.
6 ` bytes: number;` Execut bytes: number;
1 able
statem
ent.
6 ` duration: number;` Execut duration: number;
2 able
statem
ent.
6 ` threatScore: number;` Execut threatScore: number;
3 able
statem
ent.
6 ` status: NetworkFlowStatus;` Execut status: NetworkFlowStatus;
4 able
statem
ent.
6 ` country?: string;` Execut country?: string;
5 able
statem
ent.
6 ` countryCode?: string;` Execut countryCode?: string;
6 able
statem
ent.
6 ` lat?: number;` Execut lat?: number;
7 able
statem
ent.
6 ` lon?: number;` Execut lon?: number;
8 able
statem
ent.
6 `}` Brace C/C++ syntax structure.
9 or
parent
hesis
closing
/openin

Page 430 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
ga
block.
7 `` Blank Separator between code blocks.
0 line for
readabi
lity.
7 `export interface ThreatIp {` Source export interface ThreatIp {
1 code
line.
7 ` ip: string;` Execut ip: string;
2 able
statem
ent.
7 ` country: string;` Execut country: string;
3 able
statem
ent.
7 ` countryCode: string;` Execut countryCode: string;
4 able
statem
ent.
7 ` alertCount: number;` Execut alertCount: number;
5 able
statem
ent.
7 ` threatScore: number;` Execut threatScore: number;
6 able
statem
ent.
7 ` lat?: number;` Execut lat?: number;
7 able
statem
ent.
7 ` lon?: number;` Execut lon?: number;
8 able
statem
ent.
7 `}` Brace C/C++ syntax structure.
9 or
parent
hesis
closing
/openin
ga
block.
8 `` Blank Separator between code blocks.
0 line for
readabi
lity.

Page 431 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
81 `export interface ProtocolStat {` Source export interface ProtocolStat {
code
line.
82 ` name: string;` Executa name: string;
ble
stateme
nt.
83 ` packets: number;` Executa packets: number;
ble
stateme
nt.
84 ` bytes: number;` Executa bytes: number;
ble
stateme
nt.
85 ` children?: { name: string; packets: number; bytes: Executa children?: { name: string; packets: number; bytes:
number }[];` ble number }[];
stateme
nt.
86 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
87 `` Blank Separator between code blocks.
line for
readabil
ity.
88 `export interface IODataPoint {` Source export interface IODataPoint {
code
line.
89 ` time: string;` Executa time: string;
ble
stateme
nt.
90 ` in: number;` Executa in: number;
ble
stateme
nt.
91 ` out: number;` Executa out: number;
ble
stateme
nt.
92 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
93 `` Blank Separator between code blocks.
line for

Page 432 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
readabil
ity.
94 `export interface EndpointStat {` Source export interface EndpointStat {
code
line.
95 ` ip: string;` Executa ip: string;
ble
stateme
nt.
96 ` pkts: number;` Executa pkts: number;
ble
stateme
nt.
97 ` bytes: number;` Executa bytes: number;
ble
stateme
nt.
98 ` country: string;` Executa country: string;
ble
stateme
nt.
99 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
10 `` Blank Separator between code blocks.
0 line for
readabil
ity.
10 `export interface NadsSummary {` Source export interface NadsSummary {
1 code
line.
10 ` activeFlows: number;` Executa activeFlows: number;
2 ble
stateme
nt.
10 ` alertsToday: number;` Executa alertsToday: number;
3 ble
stateme
nt.
10 ` detectionRate: number;` Executa detectionRate: number;
4 ble
stateme
nt.
10 ` topThreatIp: string;` Executa topThreatIp: string;
5 ble
stateme
nt.
10 ` deltaActiveFlows?: number;` Executa deltaActiveFlows?: number;
6 ble

Page 433 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
stateme
nt.
10 ` deltaAlertsToday?: number;` Executa deltaAlertsToday?: number;
7 ble
stateme
nt.
10 ` currentPps?: number;` Executa currentPps?: number;
8 ble
stateme
nt.
10 `}` Brace C/C++ syntax structure.
9 or
parenth
esis
closing/
opening
a block.
11 `` Blank Separator between code blocks.
0 line for
readabil
ity.
11 `export interface ThreatTimelinePoint {` Source export interface ThreatTimelinePoint {
1 code
line.
11 ` time: string;` Executa time: string;
2 ble
stateme
nt.
11 ` critical: number;` Executa critical: number;
3 ble
stateme
nt.
11 ` high: number;` Executa high: number;
4 ble
stateme
nt.
11 ` medium: number;` Executa medium: number;
5 ble
stateme
nt.
11 ` low: number;` Executa low: number;
6 ble
stateme
nt.
11 `}` Brace C/C++ syntax structure.
7 or
parenth
esis
closing/
opening
a block.
11 `` Blank Separator between code blocks.
8 line for

Page 434 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
readabil
ity.
11 `export interface DetectorConfig {` Source export interface DetectorConfig {
9 code
line.
12 ` name: string;` Executa name: string;
0 ble
stateme
nt.
12 ` enabled: boolean;` Executa enabled: boolean;
1 ble
stateme
nt.
12 ` threshold?: number;` Executa threshold?: number;
2 ble
stateme
nt.
12 ` description: string;` Executa description: string;
3 ble
stateme
nt.
12 `}` Brace C/C++ syntax structure.
4 or
parenth
esis
closing/
opening
a block.
12 `` Blank Separator between code blocks.
5 line for
readabil
ity.
12 `export interface NadsConfig {` Source export interface NadsConfig {
6 code
line.
12 ` detectors: DetectorConfig[];` Executa detectors: DetectorConfig[];
7 ble
stateme
nt.
12 ` baselinePackets: number;` Executa baselinePackets: number;
8 ble
stateme
nt.
12 ` baselineDays: number;` Executa baselineDays: number;
9 ble
stateme
nt.
13 ` interface: string;` Executa interface: string;
0 ble
stateme
nt.
13 ` captureFilter: string;` Executa captureFilter: string;
1 ble

Page 435 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
stateme
nt.
13 `}` Brace C/C++ syntax structure.
2 or
parenth
esis
closing/
opening
a block.
13 `` Blank Separator between code blocks.
3 line for
readabil
ity.
13 `export interface CaptureStatus {` Source export interface CaptureStatus {
4 code
line.
13 ` state: CaptureStatusState;` Executa state: CaptureStatusState;
5 ble
stateme
nt.
13 ` interface: string;` Executa interface: string;
6 ble
stateme
nt.
13 ` packets: number;` Executa packets: number;
7 ble
stateme
nt.
13 ` pps: number;` Executa pps: number;
8 ble
stateme
nt.
13 ` bps: number;` Executa bps: number;
9 ble
stateme
nt.
14 `}` Brace C/C++ syntax structure.
0 or
parenth
esis
closing/
opening
a block.
14 `` Blank Separator between code blocks.
1 line for
readabil
ity.
14 `// ─── API base URL Comme ─── API base URL
2 ───────────────────────────────── nt ────────────────────────────────
────────────────────────────` docume ─────────────────────────────
nting
intent.
14 `const API_BASE = '/api';` Named const API_BASE = '/api';
3 constan

Page 436 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
t—
value
should
not
change.
14 `` Blank Separator between code blocks.
4 line for
readabil
ity.
14 `// ─── Generic React fetch hook Comme ─── Generic React fetch hook
5 ───────────────────────────────── nt ────────────────────────────────
────────────────` docume ─────────────────
nting
intent.
14 `import { useState, useEffect, useCallback } from Executa import { useState, useEffect, useCallback } from
6 'react';` ble 'react';
stateme
nt.
14 `` Blank Separator between code blocks.
7 line for
readabil
ity.
14 `function useBackendQuery<T>(endpoint: string, Source function useBackendQuery<T>(endpoint: string,
8 fallback: T, refreshMs = 4000) {` code fallback: T, refreshMs = 4000) {
line.
14 ` const [data, setData] = useState<T>(fallback);` Named const [data, setData] = useState<T>(fallback);
9 constan
t—
value
should
not
change.
15 ` const [isLoading, setIsLoading] = useState(false);` Named const [isLoading, setIsLoading] = useState(false);
0 constan
t—
value
should
not
change.
15 ` const [isError, setIsError] = useState(false);` Named const [isError, setIsError] = useState(false);
1 constan
t—
value
should
not
change.
15 `` Blank Separator between code blocks.
2 line for
readabil
ity.
15 ` const load = useCallback(async () => {` Named const load = useCallback(async () => {
3 constan
t—
value
should

Page 437 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
not
change.
15 ` setIsLoading(true);` Executa setIsLoading(true);
4 ble
stateme
nt.
15 ` try {` Source try {
5 code
line.
15 ` const res = await Named const res = await fetch(`${API_BASE}${endpoint}`);
6 fetch(`${API_BASE}${endpoint}`);` constan
t—
value
should
not
change.
15 ` if ([Link]) {` Conditio if ([Link]) {
7 nal
branch
— run
code
only
when
conditio
n true.
15 ` const json = await [Link]();` Named const json = await [Link]();
8 constan
t—
value
should
not
change.
15 ` setData(json);` Executa setData(json);
9 ble
stateme
nt.
16 ` setIsError(false);` Executa setIsError(false);
0 ble
stateme
nt.

Li Source Easy Technical Explanation


n Explan
e ation
16 ` } else {` Source } else {
1 code
line.
16 ` setIsError(true);` Executa setIsError(true);
2 ble
stateme
nt.
16 ` }` Brace or C/C++ syntax structure.
3 parenth
esis

Page 438 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
closing/
opening
a block.
16 ` } catch (_e) {` Source } catch (_e) {
4 code
line.
16 ` setIsError(true);` Executa setIsError(true);
5 ble
stateme
nt.
16 ` } finally {` Source } finally {
6 code
line.
16 ` setIsLoading(false);` Executa setIsLoading(false);
7 ble
stateme
nt.
16 ` }` Brace or C/C++ syntax structure.
8 parenth
esis
closing/
opening
a block.
16 ` }, [endpoint]);` Executa }, [endpoint]);
9 ble
stateme
nt.
17 `` Blank Separator between code blocks.
0 line for
readabili
ty.
17 ` useEffect(() => {` Source useEffect(() => {
1 code
line.
17 ` load();` Executa load();
2 ble
stateme
nt.
17 ` if (refreshMs > 0) {` Conditio if (refreshMs > 0) {
3 nal
branch
— run
code
only
when
conditio
n true.
17 ` const id = setInterval(load, refreshMs);` Named const id = setInterval(load, refreshMs);
4 constant
— value
should
not
change.

Page 439 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
17 ` return () => clearInterval(id);` Exit return () => clearInterval(id);
5 function
and give
back a
value.
17 ` }` Brace or C/C++ syntax structure.
6 parenth
esis
closing/
opening
a block.
17 ` }, [load, refreshMs]);` Executa }, [load, refreshMs]);
7 ble
stateme
nt.
17 `` Blank Separator between code blocks.
8 line for
readabili
ty.
17 ` return { data, isLoading, isError, error: null, Exit return { data, isLoading, isError, error: null, refetch:
9 refetch: load };` function load };
and give
back a
value.
18 `}` Brace or C/C++ syntax structure.
0 parenth
esis
closing/
opening
a block.
18 `` Blank Separator between code blocks.
1 line for
readabili
ty.
18 `// ─── Exported hooks Comme ─── Exported hooks
2 ──────────────────────────────── nt ────────────────────────────────
───────────────────────────` docume ───────────────────────────
nting
intent.
18 `` Blank Separator between code blocks.
3 line for
readabili
ty.
18 `export const useGetPackets = (` Named export const useGetPackets = (
4 constant
— value
should
not
change.
18 ` _params?: unknown,` Source _params?: unknown,
5 code
line.
18 ` _opts?: unknown` Source _opts?: unknown
6 code
line.

Page 440 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
18 `) => useBackendQuery<{ packets: Packet[] Executa ) => useBackendQuery<{ packets: Packet[]
7 }>('/packets', { packets: [] }, 2000);` ble }>('/packets', { packets: [] }, 2000);
stateme
nt.
18 `` Blank Separator between code blocks.
8 line for
readabili
ty.
18 `export const useGetNadsAlerts = (` Named export const useGetNadsAlerts = (
9 constant
— value
should
not
change.
19 ` _params?: unknown,` Source _params?: unknown,
0 code
line.
19 ` _opts?: unknown` Source _opts?: unknown
1 code
line.
19 `) => useBackendQuery<NadsAlert[]>('/alerts', [], Executa ) => useBackendQuery<NadsAlert[]>('/alerts', [],
2 3000);` ble 3000);
stateme
nt.
19 `` Blank Separator between code blocks.
3 line for
readabili
ty.
19 `export const useGetNadsSummary = (` Named export const useGetNadsSummary = (
4 constant
— value
should
not
change.
19 ` _params?: unknown,` Source _params?: unknown,
5 code
line.
19 ` _opts?: unknown` Source _opts?: unknown
6 code
line.
19 `) => Source ) =>
7 useBackendQuery<NadsSummary>('/summary', {` code useBackendQuery<NadsSummary>('/summary', {
line.
19 ` activeFlows: 0,` Source activeFlows: 0,
8 code
line.
19 ` alertsToday: 0,` Source alertsToday: 0,
9 code
line.
20 ` detectionRate: 0,` Source detectionRate: 0,
0 code
line.

Page 441 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
20 ` topThreatIp: '',` Source topThreatIp: '',
1 code
line.
20 `}, 2000);` Executa }, 2000);
2 ble
stateme
nt.
20 `` Blank Separator between code blocks.
3 line for
readabili
ty.
20 `export const useGetThreatTimeline = (` Named export const useGetThreatTimeline = (
4 constant
— value
should
not
change.
20 ` _params?: unknown,` Source _params?: unknown,
5 code
line.
20 ` _opts?: unknown` Source _opts?: unknown
6 code
line.
20 `) => Executa ) =>
7 useBackendQuery<ThreatTimelinePoint[]>('/threat- ble useBackendQuery<ThreatTimelinePoint[]>('/threat-
timeline', [], 5000);` stateme timeline', [], 5000);
nt.
20 `` Blank Separator between code blocks.
8 line for
readabili
ty.
20 `export const useGetThreatIps = (` Named export const useGetThreatIps = (
9 constant
— value
should
not
change.
21 ` _params?: unknown,` Source _params?: unknown,
0 code
line.
21 ` _opts?: unknown` Source _opts?: unknown
1 code
line.
21 `) => useBackendQuery<ThreatIp[]>('/threat-ips', [], Executa ) => useBackendQuery<ThreatIp[]>('/threat-ips', [],
2 5000);` ble 5000);
stateme
nt.
21 `` Blank Separator between code blocks.
3 line for
readabili
ty.
21 `export const useGetNadsFlows = (` Named export const useGetNadsFlows = (
4 constant

Page 442 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
— value
should
not
change.
21 ` _params?: unknown,` Source _params?: unknown,
5 code
line.
21 ` _opts?: unknown` Source _opts?: unknown
6 code
line.
21 `) => useBackendQuery<NetworkFlow[]>('/flows', [], Executa ) => useBackendQuery<NetworkFlow[]>('/flows', [],
7 3000);` ble 3000);
stateme
nt.
21 `` Blank Separator between code blocks.
8 line for
readabili
ty.
21 `export const useGetProtocolStats = (` Named export const useGetProtocolStats = (
9 constant
— value
should
not
change.
22 ` _params?: unknown,` Source _params?: unknown,
0 code
line.
22 ` _opts?: unknown` Source _opts?: unknown
1 code
line.
22 `) => useBackendQuery<ProtocolStat[]>('/protocol- Executa ) => useBackendQuery<ProtocolStat[]>('/protocol-
2 stats', [], 5000);` ble stats', [], 5000);
stateme
nt.
22 `` Blank Separator between code blocks.
3 line for
readabili
ty.
22 `export const useGetNadsConfig = (` Named export const useGetNadsConfig = (
4 constant
— value
should
not
change.
22 ` _params?: unknown,` Source _params?: unknown,
5 code
line.
22 ` _opts?: unknown` Source _opts?: unknown
6 code
line.
22 `) => useBackendQuery<NadsConfig>('/config', {` Source ) => useBackendQuery<NadsConfig>('/config', {
7 code
line.

Page 443 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
22 ` detectors: [],` Source detectors: [],
8 code
line.
22 ` baselinePackets: 0,` Source baselinePackets: 0,
9 code
line.
23 ` baselineDays: 7,` Source baselineDays: 7,
0 code
line.
23 ` interface: '',` Source interface: '',
1 code
line.
23 ` captureFilter: '',` Source captureFilter: '',
2 code
line.
23 `}, 0);` Executa }, 0);
3 ble
stateme
nt.
23 `` Blank Separator between code blocks.
4 line for
readabili
ty.
23 `export const useGetCaptureStatus = (` Named export const useGetCaptureStatus = (
5 constant
— value
should
not
change.
23 ` _params?: unknown,` Source _params?: unknown,
6 code
line.
23 ` _opts?: unknown` Source _opts?: unknown
7 code
line.
23 `) => Source ) =>
8 useBackendQuery<CaptureStatus>('/capture/status' code useBackendQuery<CaptureStatus>('/capture/status'
, {` line. ,{
23 ` state: 'idle',` Source state: 'idle',
9 code
line.
24 ` interface: '',` Source interface: '',
0 code
line.

Li Source Easy Technical Explanation


n Explan
e ation
24 ` packets: 0,` Source packets: 0,
1 code
line.

Page 444 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
24 ` pps: 0,` Source pps: 0,
2 code
line.
24 ` bps: 0,` Source bps: 0,
3 code
line.
24 `}, 1000);` Executa }, 1000);
4 ble
stateme
nt.
24 `` Blank Separator between code blocks.
5 line for
readabili
ty.
24 `export const useGetInterfaces = (` Named export const useGetInterfaces = (
6 constant
— value
should
not
change.
24 ` _params?: unknown,` Source _params?: unknown,
7 code
line.
24 ` _opts?: unknown` Source _opts?: unknown
8 code
line.
24 `) => useBackendQuery<string[]>('/interfaces', [], 0);` Executa ) => useBackendQuery<string[]>('/interfaces', [], 0);
9 ble
stateme
nt.
25 `` Blank Separator between code blocks.
0 line for
readabili
ty.
25 `export const useGetIoGraph = (` Named export const useGetIoGraph = (
1 constant
— value
should
not
change.
25 ` _params?: unknown,` Source _params?: unknown,
2 code
line.
25 ` _opts?: unknown` Source _opts?: unknown
3 code
line.
25 `) => useBackendQuery<IODataPoint[]>('/io-graph', Executa ) => useBackendQuery<IODataPoint[]>('/io-graph',
4 [], 2000);` ble [], 2000);
stateme
nt.
25 `` Blank Separator between code blocks.
5 line for

Page 445 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
readabili
ty.
25 `// ─── Capture control Comme ─── Capture control
6 ──────────────────────────────── nt ────────────────────────────────
─────────────────────────` docume ─────────────────────────
nting
intent.
25 `export async function startCapture(iface?: string, Source export async function startCapture(iface?: string,
7 filter?: string): Promise<void> {` code filter?: string): Promise<void> {
line.
25 ` await fetch(`${API_BASE}/capture/start`, {` Source await fetch(`${API_BASE}/capture/start`, {
8 code
line.
25 ` method: 'POST',` Source method: 'POST',
9 code
line.
26 ` headers: { 'Content-Type': 'application/json' },` Source headers: { 'Content-Type': 'application/json' },
0 code
line.
26 ` body: [Link]({ interface: iface, filter }),` Source body: [Link]({ interface: iface, filter }),
1 code
line.
26 ` });` Executa });
2 ble
stateme
nt.
26 `}` Brace or C/C++ syntax structure.
3 parenth
esis
closing/
opening
a block.
26 `` Blank Separator between code blocks.
4 line for
readabili
ty.
26 `export async function stopCapture(): Source export async function stopCapture(): Promise<void>
5 Promise<void> {` code {
line.
26 ` await fetch(`${API_BASE}/capture/stop`, { method: Executa await fetch(`${API_BASE}/capture/stop`, { method:
6 'POST' });` ble 'POST' });
stateme
nt.
26 `}` Brace or C/C++ syntax structure.
7 parenth
esis
closing/
opening
a block.
26 `` Blank Separator between code blocks.
8 line for
readabili
ty.

Page 446 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
26 `export async function pauseCapture(): Source export async function pauseCapture():
9 Promise<void> {` code Promise<void> {
line.
27 ` await fetch(`${API_BASE}/capture/pause`, { Executa await fetch(`${API_BASE}/capture/pause`, {
0 method: 'POST' });` ble method: 'POST' });
stateme
nt.
27 `}` Brace or C/C++ syntax structure.
1 parenth
esis
closing/
opening
a block.
27 `` Blank Separator between code blocks.
2 line for
readabili
ty.
27 `export async function resumeCapture(): Source export async function resumeCapture():
3 Promise<void> {` code Promise<void> {
line.
27 ` await fetch(`${API_BASE}/capture/resume`, { Executa await fetch(`${API_BASE}/capture/resume`, {
4 method: 'POST' });` ble method: 'POST' });
stateme
nt.
27 `}` Brace or C/C++ syntax structure.
5 parenth
esis
closing/
opening
a block.
27 `` Blank Separator between code blocks.
6 line for
readabili
ty.
27 `// ─── Config control Comme ─── Config control
7 ──────────────────────────────── nt ────────────────────────────────
───────────────────────────` docume ───────────────────────────
nting
intent.
27 `export async function saveNadsConfig(config: Source export async function saveNadsConfig(config:
8 Partial<NadsConfig>): Promise<void> {` code Partial<NadsConfig>): Promise<void> {
line.
27 ` await fetch(`${API_BASE}/config`, {` Source await fetch(`${API_BASE}/config`, {
9 code
line.
28 ` method: 'POST',` Source method: 'POST',
0 code
line.
28 ` headers: { 'Content-Type': 'application/json' },` Source headers: { 'Content-Type': 'application/json' },
1 code
line.

Page 447 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
28 ` body: [Link](config),` Source body: [Link](config),
2 code
line.
28 ` });` Executa });
3 ble
stateme
nt.
28 `}` Brace or C/C++ syntax structure.
4 parenth
esis
closing/
opening
a block.
28 `` Blank Separator between code blocks.
5 line for
readabili
ty.
28 `export async function recalculateBaseline(): Source export async function recalculateBaseline():
6 Promise<void> {` code Promise<void> {
line.
28 ` await fetch(`${API_BASE}/baseline/recalculate`, { Executa await fetch(`${API_BASE}/baseline/recalculate`, {
7 method: 'POST' });` ble method: 'POST' });
stateme
nt.
28 `}` Brace or C/C++ syntax structure.
8 parenth
esis
closing/
opening
a block.
28 `` Blank Separator between code blocks.
9 line for
readabili
ty.
29 `export async function resetBaseline(): Source export async function resetBaseline():
0 Promise<void> {` code Promise<void> {
line.
29 ` await fetch(`${API_BASE}/baseline/reset`, { Executa await fetch(`${API_BASE}/baseline/reset`, {
1 method: 'POST' });` ble method: 'POST' });
stateme
nt.
29 `}` Brace or C/C++ syntax structure.
2 parenth
esis
closing/
opening
a block.
29 `` Blank Separator between code blocks.
3 line for
readabili
ty.
29 `export async function acknowledgeAlert(id: string): Source export async function acknowledgeAlert(id: string):
4 Promise<void> {` code Promise<void> {
line.

Page 448 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Explan
e ation
29 ` await Executa await
5 fetch(`${API_BASE}/alerts/${id}/acknowledge`, { ble fetch(`${API_BASE}/alerts/${id}/acknowledge`, {
method: 'POST' });` stateme method: 'POST' });
nt.
29 `}` Brace or C/C++ syntax structure.
6 parenth
esis
closing/
opening
a block.

File: webwireshark/src/lib/[Link]
Total lines: 105

Li Source Easy Technical Explanation


n Expla
e natio
n
1 `import { Packet, NadsAlert, NetworkFlow, ThreatIp, Execu import { Packet, NadsAlert, NetworkFlow,
ProtocolStat, IODataPoint, EndpointStat, table ThreatIp, ProtocolStat, IODataPoint,
ConversationStat, DnsSumm...` statem EndpointStat, Conversa
ent.
2 `` Blank Separator between code blocks.
line for
reada
bility.
3 `export const generateMockPackets = (count: number): Name export const generateMockPackets = (count:
Packet[] => {` d number): Packet[] => {
consta
nt —
value
should
not
chang
e.
4 ` const protocols = ['TCP', 'UDP', 'DNS', 'HTTP', Name const protocols = ['TCP', 'UDP', 'DNS', 'HTTP',
'TLSv1.2', 'ICMP', 'ARP'];` d 'TLSv1.2', 'ICMP', 'ARP'];
consta
nt —
value
should
not
chang
e.
5 ` const srcIps = ['[Link]', '[Link]', Name const srcIps = ['[Link]', '[Link]',
'[Link]', '[Link]'];` d '[Link]', '[Link]'];
consta
nt —
value
should

Page 449 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
not
chang
e.
6 ` const dstIps = ['[Link]', '[Link]', '[Link]', Name const dstIps = ['[Link]', '[Link]', '[Link]',
'[Link]'];` d '[Link]'];
consta
nt —
value
should
not
chang
e.
7 ` const infos = [` Name const infos = [
d
consta
nt —
value
should
not
chang
e.
8 ` 'Echo (ping) request',` Sourc 'Echo (ping) request',
e code
line.
9 ` 'Standard query 0x1234 A [Link]',` Sourc 'Standard query 0x1234 A [Link]',
e code
line.
1 ` 'GET / HTTP/1.1',` Sourc 'GET / HTTP/1.1',
0 e code
line.
1 ` 'Client Hello',` Sourc 'Client Hello',
1 e code
line.
1 ` 'Application Data',` Sourc 'Application Data',
2 e code
line.
1 ` 'Who has [Link]? Tell [Link]',` Sourc 'Who has [Link]? Tell [Link]',
3 e code
line.
1 ` '443 → 50212 [ACK] Seq=1 Ack=1 Win=65535 Sourc '443 → 50212 [ACK] Seq=1 Ack=1 Win=65535
4 Len=0',` e code Len=0',
line.
1 ` ];` Execu ];
5 table
statem
ent.
1 `` Blank Separator between code blocks.
6 line for
reada
bility.
1 ` return [Link]({ length: count }).map((_, i) => {` Exit return [Link]({ length: count }).map((_, i) => {
7 functio
n and

Page 450 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
give
back a
value.
1 ` const proto = protocols[[Link]([Link]() * Name const proto = protocols[[Link]([Link]()
8 [Link])];` d * [Link])];
consta
nt —
value
should
not
chang
e.
1 ` const no = i + 1;` Name const no = i + 1;
9 d
consta
nt —
value
should
not
chang
e.
2 ` const time = new Date([Link]() - (count - i) * Name const time = new Date([Link]() - (count - i) *
0 1000).toISOString();` d 1000).toISOString();
consta
nt —
value
should
not
chang
e.
2 ` return {` Exit return {
1 functio
n and
give
back a
value.
2 ` no,` Sourc no,
2 e code
line.
2 ` time,` Sourc time,
3 e code
line.
2 ` src: srcIps[[Link]([Link]() * Sourc src: srcIps[[Link]([Link]() *
4 [Link])],` e code [Link])],
line.
2 ` dst: dstIps[[Link]([Link]() * Sourc dst: dstIps[[Link]([Link]() *
5 [Link])],` e code [Link])],
line.
2 ` protocol: proto,` Sourc protocol: proto,
6 e code
line.
2 ` length: [Link]([Link]() * 1500) + 64,` Sourc length: [Link]([Link]() * 1500) + 64,
7 e code
line.

Page 451 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
2 ` info: infos[[Link]([Link]() * [Link])],` Sourc info: infos[[Link]([Link]() *
8 e code [Link])],
line.
2 ` rawHex: Sourc rawHex:
9 '4500003c1c4640004006b1e6c0a8010a08080808c4b60 e code '4500003c1c4640004006b1e6c0a8010a0808080
1bb8764a2b600000000a00272106e2a0000020405b404 line. 8c4b601bb8764a2b600000000a00272106e2a00
02080a0058b8...` 00020405b4040
3 ` layers: [` Sourc layers: [
0 e code
line.
3 ` {` Brace C/C++ syntax structure.
1 or
parent
hesis
closin
g/ope
ning a
block.
3 ` name: 'Frame',` Sourc name: 'Frame',
2 e code
line.
3 ` fields: [` Sourc fields: [
3 e code
line.
3 ` { name: 'Arrival Time', value: time },` Sourc { name: 'Arrival Time', value: time },
4 e code
line.
3 ` { name: 'Frame Length', value: '74 bytes' },` Sourc { name: 'Frame Length', value: '74 bytes' },
5 e code
line.
3 ` ]` Sourc ]
6 e code
line.
3 ` },` Sourc },
7 e code
line.
3 ` {` Brace C/C++ syntax structure.
8 or
parent
hesis
closin
g/ope
ning a
block.
3 ` name: 'Ethernet II',` Sourc name: 'Ethernet II',
9 e code
line.
4 ` fields: [` Sourc fields: [
0 e code
line.

Page 452 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
4 ` { name: 'Destination', value: '00:11:22:33:44:55' Sourc { name: 'Destination', value: '00:11:22:33:44:55' },
1 },` e code
line.
4 ` { name: 'Source', value: 'aa:bb:cc:dd:ee:ff' },` Sourc { name: 'Source', value: 'aa:bb:cc:dd:ee:ff' },
2 e code
line.
4 ` { name: 'Type', value: 'IPv4 (0x0800)' },` Sourc { name: 'Type', value: 'IPv4 (0x0800)' },
3 e code
line.
4 ` ]` Sourc ]
4 e code
line.
4 ` },` Sourc },
5 e code
line.
4 ` {` Brace C/C++ syntax structure.
6 or
parent
hesis
closin
g/ope
ning a
block.
4 ` name: 'Internet Protocol Version 4',` Sourc name: 'Internet Protocol Version 4',
7 e code
line.
4 ` fields: [` Sourc fields: [
8 e code
line.
4 ` { name: 'Source', value: '[Link]' },` Sourc { name: 'Source', value: '[Link]' },
9 e code
line.
5 ` { name: 'Destination', value: '[Link]' },` Sourc { name: 'Destination', value: '[Link]' },
0 e code
line.
5 ` ]` Sourc ]
1 e code
line.
5 ` }` Brace C/C++ syntax structure.
2 or
parent
hesis
closin
g/ope
ning a
block.
5 ` ]` Sourc ]
3 e code
line.
5 ` };` Brace C/C++ syntax structure.
4 or
parent

Page 453 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
hesis
closin
g/ope
ning a
block.
5 ` });` Execu });
5 table
statem
ent.
5 `};` Brace C/C++ syntax structure.
6 or
parent
hesis
closin
g/ope
ning a
block.
5 `` Blank Separator between code blocks.
7 line for
reada
bility.
5 `export const generateMockAlerts = (count: number): Name export const generateMockAlerts = (count:
8 NadsAlert[] => {` d number): NadsAlert[] => {
consta
nt —
value
should
not
chang
e.
5 ` const severities: NadsAlertSeverity[] = ['critical', 'high', Name const severities: NadsAlertSeverity[] = ['critical',
9 'medium', 'low'];` d 'high', 'medium', 'low'];
consta
nt —
value
should
not
chang
e.
6 ` const categories = ['Port Scan', 'DDoS', 'Brute Force', Name const categories = ['Port Scan', 'DDoS', 'Brute
0 'Exfiltration', 'Lateral Movement', 'C2'];` d Force', 'Exfiltration', 'Lateral
consta
nt —
value
should
not
chang
e.
6 ` const techniques = ['T1046', 'T1499', 'T1110', 'T1048', Name const techniques = ['T1046', 'T1499', 'T1110',
1 'T1021', 'T1071'];` d 'T1048', 'T1021', 'T1071'];
consta
nt —
value
should
not

Page 454 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
chang
e.
6 ` ` Blank Separator between code blocks.
2 line for
reada
bility.
6 ` return [Link]({ length: count }).map((_, i) => {` Exit return [Link]({ length: count }).map((_, i) => {
3 functio
n and
give
back a
value.
6 ` const severity = severities[[Link]([Link]() * Name const severity =
4 [Link])];` d severities[[Link]([Link]() *
consta [Link])];
nt —
value
should
not
chang
e.
6 ` const category = categories[[Link]([Link]() Name const category =
5 * [Link])];` d categories[[Link]([Link]() *
consta [Link])];
nt —
value
should
not
chang
e.
6 ` const technique = Name const technique =
6 techniques[[Link]([Link]() * d techniques[[Link]([Link]() *
[Link])];` consta [Link])];
nt —
value
should
not
chang
e.
6 ` return {` Exit return {
7 functio
n and
give
back a
value.
6 ` id: `alert-${i}`,` Sourc id: `alert-${i}`,
8 e code
line.
6 ` severity,` Sourc severity,
9 e code
line.
7 ` category,` Sourc category,
0 e code
line.

Page 455 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e natio
n
7 ` timestamp: new Date([Link]() - [Link]() * Sourc timestamp: new Date([Link]() - [Link]()
1 86400000).toISOString(),` e code * 86400000).toISOString(),
line.
7 ` detector: `${category} Guard`,` Sourc detector: `${category} Guard`,
2 e code
line.
7 ` mitreTechnique: technique,` Sourc mitreTechnique: technique,
3 e code
line.
7 ` mitreTactics: ['Initial Access', 'Discovery'],` Sourc mitreTactics: ['Initial Access', 'Discovery'],
4 e code
line.
7 ` srcAddr: `10.0.0.${[Link]([Link]() * Sourc srcAddr: `10.0.0.${[Link]([Link]() *
5 255)}`,` e code 255)}`,
line.
7 ` dstAddr: `192.168.1.${[Link]([Link]() * Sourc dstAddr: `192.168.1.${[Link]([Link]() *
6 255)}`,` e code 255)}`,
line.
7 ` description: `Detected suspicious Sourc description: `Detected suspicious
7 ${[Link]()} activity from source.`,` e code ${[Link]()} activity from source.`,
line.
7 ` confidence: [Link]([Link]() * 40) + 60,` Sourc confidence: [Link]([Link]() * 40) + 60,
8 e code
line.
7 ` evidence: ['High connection rate', 'Multiple failed Sourc evidence: ['High connection rate', 'Multiple failed
9 logins', 'Unusual port accesses'],` e code logins', 'Unusual port accesses'],
line.
8 ` acknowledged: false,` Sourc acknowledged: false,
0 e code
line.

Line Source Easy Technical Explanation


Explanation
81 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
82 ` });` Executable });
statement.
83 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
84 `` Blank line for Separator between code blocks.
readability.
85 `export const generateMockFlows = Named constant export const generateMockFlows =
(count: number): NetworkFlow[] => {` — value should (count: number): NetworkFlow[] => {
not change.

Page 456 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
86 ` const statuses: NetworkFlowStatus[] = Named constant const statuses: NetworkFlowStatus[] =
['active', 'closed', 'suspicious', 'blocked'];` — value should ['active', 'closed', 'suspicious', 'blocke
not change.
87 ` ` Blank line for Separator between code blocks.
readability.
88 ` return [Link]({ length: count Exit function and return [Link]({ length: count
}).map((_, i) => ({` give back a }).map((_, i) => ({
value.
89 ` id: `flow-${i}`,` Source code line. id: `flow-${i}`,
90 ` srcAddr: Source code line. srcAddr:
`10.0.0.${[Link]([Link]() * `10.0.0.${[Link]([Link]() *
255)}`,` 255)}`,
91 ` srcPort: [Link]([Link]() * Source code line. srcPort: [Link]([Link]() *
60000) + 1024,` 60000) + 1024,
92 ` dstAddr: Source code line. dstAddr:
`192.168.1.${[Link]([Link]() * `192.168.1.${[Link]([Link]() *
255)}`,` 255)}`,
93 ` dstPort: [80, 443, 53, Source code line. dstPort: [80, 443, 53,
22][[Link]([Link]() * 4)],` 22][[Link]([Link]() * 4)],
94 ` protocol: ['TCP', Source code line. protocol: ['TCP',
'UDP'][[Link]([Link]() * 2)],` 'UDP'][[Link]([Link]() * 2)],
95 ` packets: [Link]([Link]() * Source code line. packets: [Link]([Link]() *
10000),` 10000),
96 ` bytes: [Link]([Link]() * Source code line. bytes: [Link]([Link]() *
10000000),` 10000000),
97 ` duration: [Link]([Link]() * Source code line. duration: [Link]([Link]() *
3600),` 3600),
98 ` threatScore: [Link]([Link]() Source code line. threatScore: [Link]([Link]() *
* 100),` 100),
99 ` status: Source code line. status:
statuses[[Link]([Link]() * statuses[[Link]([Link]() *
[Link])],` [Link])],
100 ` country: 'United States',` Source code line. country: 'United States',
101 ` countryCode: 'US',` Source code line. countryCode: 'US',
102 ` lat: 37.0902,` Source code line. lat: 37.0902,
103 ` lon: -95.7129,` Source code line. lon: -95.7129,
104 ` }));` Executable }));
statement.
105 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

File: webwireshark/src/lib/[Link]
Total lines: 6

Page 457 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


1 `import { clsx, type ClassValue } Source code line. import { clsx, type ClassValue }
from "clsx"` from "clsx"
2 `import { twMerge } from "tailwind- Source code line. import { twMerge } from "tailwind-
merge"` merge"
3 `` Blank line for readability. Separator between code blocks.
4 `export function cn(...inputs: Source code line. export function cn(...inputs:
ClassValue[]) {` ClassValue[]) {
5 ` return twMerge(clsx(inputs))` Exit function and give back a return twMerge(clsx(inputs))
value.
6 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a block.

File: webwireshark/src/lib/[Link]
Total lines: 156

Lin Source Easy Technical Explanation


e Explanation
1 `import { useAppStore } from Executable import { useAppStore } from
'../store/useAppStore';` statement. '../store/useAppStore';
2 `` Blank line for Separator between code blocks.
readability.
3 `export class WebSocketClient {` Source code export class WebSocketClient {
line.
4 ` private url: string;` Executable private url: string;
statement.
5 ` private ws: WebSocket \ null = null;` Executable statement.
6 ` private reconnectAttempts = 0;` Executable private reconnectAttempts = 0;
statement.
7 ` private maxReconnectAttempts = 10;` Executable private maxReconnectAttempts = 10;
statement.
8 ` private reconnectDelay = 2000;` Executable private reconnectDelay = 2000;
statement.
9 ` private heartbeatInterval: ReturnType<typeof null = null;` Executable statement.
setInterval> \
10 ` private reconnectTimeout: ReturnType<typeof null = null;` Executable statement.
setTimeout> \
11 `` Blank line for Separator between code blocks.
readability.
12 ` constructor(url: string) {` Source code constructor(url: string) {
line.
13 ` [Link] = url;` Executable [Link] = url;
statement.
14 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 458 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
closing/openin
g a block.
15 `` Blank line for Separator between code blocks.
readability.
16 ` connect() {` Source code connect() {
line.
17 ` if ([Link] && ([Link] === \ [Link] ===
[Link] \ [Link])) {`
18 ` return;` Exit function return;
and give back
a value.
19 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
20 ` try {` Source code try {
line.
21 ` [Link] = new WebSocket([Link]);` Executable [Link] = new WebSocket([Link]);
statement.
22 `` Blank line for Separator between code blocks.
readability.
23 ` [Link] = () => {` Source code [Link] = () => {
line.
24 ` Executable [Link]().setWsConnected(true);
[Link]().setWsConnected(true);` statement.
25 ` [Link] = 0;` Executable [Link] = 0;
statement.
26 ` [Link]();` Executable [Link]();
statement.
27 ` [Link]('[WS] Connected to NADS Executable [Link]('[WS] Connected to NADS
backend');` statement. backend');
28 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
29 `` Blank line for Separator between code blocks.
readability.
30 ` [Link] = (e) => {` Source code [Link] = (e) => {
line.
31 ` Executable [Link]().setWsConnected(false
[Link]().setWsConnected(false) statement. );
;`
32 ` [Link]();` Executable [Link]();
statement.
33 ` if ([Link] !== 1000) {` Conditional if ([Link] !== 1000) {
branch — run
code only
when condition
true.

Page 459 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
34 ` // Abnormal close — try to reconnect` Comment Abnormal close — try to reconnect
documenting
intent.
35 ` [Link]();` Executable [Link]();
statement.
36 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
37 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
38 `` Blank line for Separator between code blocks.
readability.
39 ` [Link] = () => {` Source code [Link] = () => {
line.
40 ` // Error is always followed by close; log Comment Error is always followed by close; log quietly
quietly` documenting
intent.
41 ` Executable [Link]().setWsConnected(false
[Link]().setWsConnected(false) statement. );
;`
42 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
43 `` Blank line for Separator between code blocks.
readability.
44 ` [Link] = (event) => {` Source code [Link] = (event) => {
line.
45 ` try {` Source code try {
line.
46 ` const data = [Link]([Link]);` Named const data = [Link]([Link]);
constant —
value should
not change.
47 ` [Link](data);` Executable [Link](data);
statement.
48 ` } catch (e) {` Source code } catch (e) {
line.
49 ` [Link]('[WS] Failed to parse Executable [Link]('[WS] Failed to parse message:',
message:', e);` statement. e);
50 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
51 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 460 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
52 ` } catch (e) {` Source code } catch (e) {
line.
53 ` [Link]('[WS] Failed to connect:', e);` Executable [Link]('[WS] Failed to connect:', e);
statement.
54 ` [Link]();` Executable [Link]();
statement.
55 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
56 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
57 `` Blank line for Separator between code blocks.
readability.
58 ` disconnect() {` Source code disconnect() {
line.
59 ` if ([Link]) {` Conditional if ([Link]) {
branch — run
code only
when condition
true.
60 ` clearTimeout([Link]);` Executable clearTimeout([Link]);
statement.
61 ` [Link] = null;` Executable [Link] = null;
statement.
62 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
63 ` if ([Link]) {` Conditional if ([Link]) {
branch — run
code only
when condition
true.
64 ` [Link](1000, 'Client disconnect');` Executable [Link](1000, 'Client disconnect');
statement.
65 ` [Link] = null;` Executable [Link] = null;
statement.
66 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
67 ` [Link]();` Executable [Link]();
statement.
68 ` [Link] = Source code [Link] =
[Link]; // prevent auto- line. [Link]; // prevent auto-
reconnect` reconnect
69 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 461 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
closing/openin
g a block.
70 `` Blank line for Separator between code blocks.
readability.
71 ` send(data: unknown) {` Source code send(data: unknown) {
line.
72 ` if ([Link] && [Link] === Conditional if ([Link] && [Link] ===
[Link]) {` branch — run [Link]) {
code only
when condition
true.
73 ` [Link]([Link](data));` Executable [Link]([Link](data));
statement.
74 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
75 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
76 `` Blank line for Separator between code blocks.
readability.
77 ` private handleMessage(data: any) {` Source code private handleMessage(data: any) {
line.
78 ` const state = [Link]();` Named const state = [Link]();
constant —
value should
not change.
79 `` Blank line for Separator between code blocks.
readability.
80 ` switch ([Link]) {` Source code switch ([Link]) {
line.

Lin Source Easy Technical Explanation


e Explanatio
n
81 ` case 'packet':` Source code case 'packet':
line.
82 ` [Link]([Link]);` Executable [Link]([Link]);
statement.
83 ` break;` Executable break;
statement.
84 `` Blank line for Separator between code blocks.
readability.
85 ` case 'packets':` Source code case 'packets':
line.
86 ` // Batch packet update` Comment Batch packet update
documenting
intent.

Page 462 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
87 ` if ([Link]([Link])) {` Conditional if ([Link]([Link])) {
branch — run
code only
when
condition
true.
88 ` [Link]([...[Link], Executable [Link]([...[Link],
...[Link]]);` statement. ...[Link]]);
89 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
90 ` break;` Executable break;
statement.
91 `` Blank line for Separator between code blocks.
readability.
92 ` case 'stats':` Source code case 'stats':
line.
93 ` [Link]({` Source code [Link]({
line.
94 ` pps: [Link]?.pps ?? 0,` Source code pps: [Link]?.pps ?? 0,
line.
95 ` bps: [Link]?.bps ?? 0,` Source code bps: [Link]?.bps ?? 0,
line.
96 ` totalPackets: [Link]?.totalPackets ?? 0,` Source code totalPackets: [Link]?.totalPackets
line. ?? 0,
97 ` });` Executable });
statement.
98 ` if ([Link]?.activeFlows != null) {` Conditional if ([Link]?.activeFlows != null) {
branch — run
code only
when
condition
true.
99 ` Executable [Link]([Link]
[Link]([Link]);` statement. ows);
100 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
101 ` break;` Executable break;
statement.
102 `` Blank line for Separator between code blocks.
readability.
103 ` case 'nads_alert':` Source code case 'nads_alert':
line.
104 ` Executable [Link]([Link]
[Link]([Link] + statement. Count + 1);
1);`

Page 463 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
105 ` break;` Executable break;
statement.
106 `` Blank line for Separator between code blocks.
readability.
107 ` case 'capture_status':` Source code case 'capture_status':
line.
108 ` if ([Link]?.state) {` Conditional if ([Link]?.state) {
branch — run
code only
when
condition
true.
109 ` [Link]([Link]);` Executable [Link]([Link]);
statement.
110 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
111 ` break;` Executable break;
statement.
112 `` Blank line for Separator between code blocks.
readability.
113 ` case 'pong':` Source code case 'pong':
line.
114 ` // heartbeat response — ignore` Comment heartbeat response — ignore
documenting
intent.
115 ` break;` Executable break;
statement.
116 `` Blank line for Separator between code blocks.
readability.
117 ` default:` Source code default:
line.
118 ` break;` Executable break;
statement.
119 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
120 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
121 `` Blank line for Separator between code blocks.
readability.
122 ` private handleReconnect() {` Source code private handleReconnect() {
line.
123 ` if ([Link] >= Conditional if ([Link] >=
[Link]) {` branch — run [Link]) {
code only

Page 464 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
when
condition
true.
124 ` [Link]('[WS] Max reconnect attempts Executable [Link]('[WS] Max reconnect
reached. Giving up.');` statement. attempts reached. Giving up.');
125 ` return;` Exit function return;
and give back
a value.
126 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
127 ` [Link]++;` Executable [Link]++;
statement.
128 ` const delay = [Link]([Link] * Named const delay =
[Link], 30000);` constant — [Link]([Link] *
value should [Link], 30000);
not change.
129 ` [Link](`[WS] Reconnecting in ${delay}ms Executable [Link](`[WS] Reconnecting in
(attempt statement. ${delay}ms (attempt
${[Link]}/${[Link] ${[Link]}/${[Link]
pts})`);` nectA
130 ` [Link] = setTimeout(() => {` Source code [Link] = setTimeout(() => {
line.
131 ` [Link]();` Executable [Link]();
statement.
132 ` }, delay);` Executable }, delay);
statement.
133 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
134 `` Blank line for Separator between code blocks.
readability.
135 ` private startHeartbeat() {` Source code private startHeartbeat() {
line.
136 ` [Link] = setInterval(() => {` Source code [Link] = setInterval(() => {
line.
137 ` [Link]({ type: 'ping' });` Executable [Link]({ type: 'ping' });
statement.
138 ` }, 15000);` Executable }, 15000);
statement.
139 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
140 `` Blank line for Separator between code blocks.
readability.
141 ` private stopHeartbeat() {` Source code private stopHeartbeat() {
line.

Page 465 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
142 ` if ([Link]) {` Conditional if ([Link]) {
branch — run
code only
when
condition
true.
143 ` clearInterval([Link]);` Executable clearInterval([Link]);
statement.
144 ` [Link] = null;` Executable [Link] = null;
statement.
145 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
146 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
147 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
148 `` Blank line for Separator between code blocks.
readability.
149 `// Singleton global client — connects to /ws on the Comment Singleton global client — connects to /ws
same host (proxied to NADS C++ on 8080)` documenting on the same host (proxied to NADS C++ on
intent. 8080)
150 `// export const wsClient = new WebSocketClient(` Comment export const wsClient = new
documenting WebSocketClient(
intent.
151 `// [Link] === 'https:'` Comment [Link] === 'https:'
documenting
intent.
152 `// ? `[Link] Comment ? `[Link]
documenting
intent.
153 `// : `[Link] Comment : `[Link]
documenting
intent.
154 `// );` Comment );
documenting
intent.
155 `// Replace the existing constructor call at the bottom Comment Replace the existing constructor call at the
of the file` documenting bottom of the file
intent.
156 `export const wsClient = new Named export const wsClient = new
WebSocketClient('[Link] constant — WebSocketClient('[Link]
value should
not change.

Page 466 of 629


NADS Complete Technical Reference

File: webwireshark/src/store/[Link]
Total lines: 158

Line Source Easy Explanation Technical Explanation


1 `import { create } from 'zustand';` Executable statement. import { create } from 'zustand';
2 `import { persist } from Executable statement. import { persist } from
'zustand/middleware';` 'zustand/middleware';
3 `import { Packet, CaptureStatusState } Executable statement. import { Packet, CaptureStatusState }
from '@workspace/api-client-react';` from '@workspace/api-client-react';
4 `` Blank line for Separator between code blocks.
readability.
5 `interface AppState {` Source code line. interface AppState {
6 ` captureState: CaptureStatusState;` Executable statement. captureState: CaptureStatusState;
7 ` selectedPacket: Packet \ null;` Executable statement.
8 ` displayFilter: string;` Executable statement. displayFilter: string;
9 ` packets: Packet[];` Executable statement. packets: Packet[];
10 ` stats: { pps: number; bps: number; Executable statement. stats: { pps: number; bps: number;
totalPackets: number };` totalPackets: number };
11 ` activeFlows: number;` Executable statement. activeFlows: number;
12 ` alertBadgeCount: number;` Executable statement. alertBadgeCount: number;
13 ` wsConnected: boolean;` Executable statement. wsConnected: boolean;
14 ` theme: string;` Executable statement. theme: string;
15 ` recentFilters: string[];` Executable statement. recentFilters: string[];
16 ` acknowledgedAlerts: string[];` Executable statement. acknowledgedAlerts: string[];
17 ` anomalyTimeFilter: string \ null;` Executable statement.
18 ` anomalyProtocolFilter: string \ null;` Executable statement.
19 ` // Settings state` Comment documenting Settings state
intent.
20 ` captureInterface: string;` Executable statement. captureInterface: string;
21 ` captureFilter: string;` Executable statement. captureFilter: string;
22 ` maxPackets: number;` Executable statement. maxPackets: number;
23 ` scrollToNew: boolean;` Executable statement. scrollToNew: boolean;
24 ` showRelativeTime: boolean;` Executable statement. showRelativeTime: boolean;
25 ` resolveNames: boolean;` Executable statement. resolveNames: boolean;
26 ` colorRulesEnabled: boolean;` Executable statement. colorRulesEnabled: boolean;
27 ` columns: { key: string; label: string; Executable statement. columns: { key: string; label: string;
visible: boolean }[];` visible: boolean }[];
28 `` Blank line for Separator between code blocks.
readability.
29 ` setCaptureState: (state: Executable statement. setCaptureState: (state:
CaptureStatusState) => void;` CaptureStatusState) => void;
30 ` setSelectedPacket: (packet: Packet \ null) => void;` Executable statement.
31 ` setDisplayFilter: (filter: string) => Executable statement. setDisplayFilter: (filter: string) => void;
void;`

Page 467 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


32 ` setPackets: (packets: Packet[]) => Executable statement. setPackets: (packets: Packet[]) =>
void;` void;
33 ` addPacket: (packet: Packet) => Executable statement. addPacket: (packet: Packet) => void;
void;`
34 ` clearPackets: () => void;` Executable statement. clearPackets: () => void;
35 ` setStats: (stats: { pps: number; bps: Executable statement. setStats: (stats: { pps: number; bps:
number; totalPackets: number }) => number; totalPackets: number }) =>
void;` void;
36 ` setActiveFlows: (flows: number) => Executable statement. setActiveFlows: (flows: number) =>
void;` void;
37 ` setAlertBadgeCount: (count: number) Executable statement. setAlertBadgeCount: (count: number)
=> void;` => void;
38 ` setWsConnected: (connected: Executable statement. setWsConnected: (connected:
boolean) => void;` boolean) => void;
39 ` setTheme: (theme: string) => void;` Executable statement. setTheme: (theme: string) => void;
40 ` addRecentFilter: (filter: string) => Executable statement. addRecentFilter: (filter: string) => void;
void;`
41 ` toggleAcknowledgeAlert: (id: string) Executable statement. toggleAcknowledgeAlert: (id: string) =>
=> void;` void;
42 ` setAnomalyFilter: (time: string \ null, protocol: string \ null) => void;`
43 ` clearAnomalyFilter: () => void;` Executable statement. clearAnomalyFilter: () => void;
44 ` // Settings setters` Comment documenting Settings setters
intent.
45 ` setCaptureInterface: (iface: string) => Executable statement. setCaptureInterface: (iface: string) =>
void;` void;
46 ` setCaptureFilter: (filter: string) => Executable statement. setCaptureFilter: (filter: string) => void;
void;`
47 ` setMaxPackets: (n: number) => Executable statement. setMaxPackets: (n: number) => void;
void;`
48 ` setScrollToNew: (v: boolean) => Executable statement. setScrollToNew: (v: boolean) => void;
void;`
49 ` setShowRelativeTime: (v: boolean) Executable statement. setShowRelativeTime: (v: boolean) =>
=> void;` void;
50 ` setResolveNames: (v: boolean) => Executable statement. setResolveNames: (v: boolean) =>
void;` void;
51 ` setColorRulesEnabled: (v: boolean) Executable statement. setColorRulesEnabled: (v: boolean)
=> void;` => void;
52 ` toggleColumnVisible: (key: string) => Executable statement. toggleColumnVisible: (key: string) =>
void;` void;
53 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
54 `` Blank line for Separator between code blocks.
readability.
55 `const DEFAULT_COLUMNS = [` Named constant — const DEFAULT_COLUMNS = [
value should not
change.
56 ` { key: 'no', label: 'No.', visible: true },` Source code line. { key: 'no', label: 'No.', visible: true },

Page 468 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


57 ` { key: 'time', label: 'Time', visible: true Source code line. { key: 'time', label: 'Time', visible: true
},` },
58 ` { key: 'src', label: 'Source', visible: Source code line. { key: 'src', label: 'Source', visible: true
true },` },
59 ` { key: 'dst', label: 'Destination', visible: Source code line. { key: 'dst', label: 'Destination', visible:
true },` true },
60 ` { key: 'protocol', label: 'Protocol', Source code line. { key: 'protocol', label: 'Protocol',
visible: true },` visible: true },
61 ` { key: 'length', label: 'Length', visible: Source code line. { key: 'length', label: 'Length', visible:
true },` true },
62 ` { key: 'info', label: 'Info', visible: true Source code line. { key: 'info', label: 'Info', visible: true },
},`
63 `];` Executable statement. ];
64 `` Blank line for Separator between code blocks.
readability.
65 `export const useAppStore = Named constant — export const useAppStore =
create<AppState>()(` value should not create<AppState>()(
change.
66 ` persist(` Source code line. persist(
67 ` (set) => ({` Source code line. (set) => ({
68 ` captureState: 'idle' as Source code line. captureState: 'idle' as
CaptureStatusState,` CaptureStatusState,
69 ` selectedPacket: null,` Source code line. selectedPacket: null,
70 ` displayFilter: '',` Source code line. displayFilter: '',
71 ` packets: [],` Source code line. packets: [],
72 ` stats: { pps: 0, bps: 0, Source code line. stats: { pps: 0, bps: 0, totalPackets: 0
totalPackets: 0 },` },
73 ` activeFlows: 0,` Source code line. activeFlows: 0,
74 ` alertBadgeCount: 0,` Source code line. alertBadgeCount: 0,
75 ` wsConnected: false,` Source code line. wsConnected: false,
76 ` theme: 'dark',` Source code line. theme: 'dark',
77 ` recentFilters: [],` Source code line. recentFilters: [],
78 ` acknowledgedAlerts: [],` Source code line. acknowledgedAlerts: [],
79 ` anomalyTimeFilter: null,` Source code line. anomalyTimeFilter: null,
80 ` anomalyProtocolFilter: null,` Source code line. anomalyProtocolFilter: null,

Line Source Easy Technical Explanation


Explanation
81 ` captureInterface: '',` Source code line. captureInterface: '',
82 ` captureFilter: '',` Source code line. captureFilter: '',
83 ` maxPackets: 100000,` Source code line. maxPackets: 100000,
84 ` scrollToNew: true,` Source code line. scrollToNew: true,
85 ` showRelativeTime: false,` Source code line. showRelativeTime: false,
86 ` resolveNames: false,` Source code line. resolveNames: false,
87 ` colorRulesEnabled: true,` Source code line. colorRulesEnabled: true,

Page 469 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
88 ` columns: DEFAULT_COLUMNS,` Source code line. columns: DEFAULT_COLUMNS,
89 `` Blank line for Separator between code blocks.
readability.
90 ` setCaptureState: (state) => set({ Source code line. setCaptureState: (state) => set({
captureState: state }),` captureState: state }),
91 ` setSelectedPacket: (packet) => set({ Source code line. setSelectedPacket: (packet) => set({
selectedPacket: packet }),` selectedPacket: packet }),
92 ` setDisplayFilter: (filter) => set({ Source code line. setDisplayFilter: (filter) => set({
displayFilter: filter }),` displayFilter: filter }),
93 ` setPackets: (packets) =>` Source code line. setPackets: (packets) =>
94 ` set((state) => {` Source code line. set((state) => {
95 ` const capped = [...packets];` Named constant const capped = [...packets];
— value should
not change.
96 ` if ([Link] > Conditional branch if ([Link] > [Link]) {
[Link]) {` — run code only
when condition
true.
97 ` [Link](0, [Link] - Executable [Link](0, [Link] -
[Link]);` statement. [Link]);
98 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
99 ` return { packets: capped };` Exit function and return { packets: capped };
give back a value.
100 ` }),` Source code line. }),
101 ` addPacket: (packet) =>` Source code line. addPacket: (packet) =>
102 ` set((state) => {` Source code line. set((state) => {
103 ` const newPackets = Named constant const newPackets = [...[Link],
[...[Link], packet];` — value should packet];
not change.
104 ` if ([Link] > Conditional branch if ([Link] >
[Link]) {` — run code only [Link]) {
when condition
true.
105 ` [Link](0, Executable [Link](0, [Link]
[Link] - [Link]);` statement. - [Link]);
106 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
107 ` return { packets: newPackets };` Exit function and return { packets: newPackets };
give back a value.
108 ` }),` Source code line. }),
109 ` clearPackets: () => set({ packets: [], Source code line. clearPackets: () => set({ packets: [],
selectedPacket: null }),` selectedPacket: null }),
110 ` setStats: (stats) => set({ stats }),` Source code line. setStats: (stats) => set({ stats }),

Page 470 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
111 ` setActiveFlows: (flows) => set({ Source code line. setActiveFlows: (flows) => set({
activeFlows: flows }),` activeFlows: flows }),
112 ` setAlertBadgeCount: (count) => set({ Source code line. setAlertBadgeCount: (count) => set({
alertBadgeCount: count }),` alertBadgeCount: count }),
113 ` setWsConnected: (connected) => Source code line. setWsConnected: (connected) => set({
set({ wsConnected: connected }),` wsConnected: connected }),
114 ` setTheme: (theme) => set({ theme Source code line. setTheme: (theme) => set({ theme }),
}),`
115 ` addRecentFilter: (filter) =>` Source code line. addRecentFilter: (filter) =>
116 ` set((state) => ({` Source code line. set((state) => ({
117 ` recentFilters: [filter, Source code line. recentFilters: [filter,
...[Link]((f) => f !== ...[Link]((f) => f !==
filter)].slice(0, 10),` filter)].slice(0, 10),
118 ` })),` Source code line. })),
119 ` toggleAcknowledgeAlert: (id) =>` Source code line. toggleAcknowledgeAlert: (id) =>
120 ` set((state) => ({` Source code line. set((state) => ({
121 ` acknowledgedAlerts: Source code line. acknowledgedAlerts:
[Link](id)` [Link](id)
122 ` ? Source code line. ? [Link]((a) =>
[Link]((a) => a a !== id)
!== id)`
123 ` : [...[Link], Source code line. : [...[Link], id],
id],`
124 ` })),` Source code line. })),
125 ` setAnomalyFilter: (time, protocol) =>` Source code line. setAnomalyFilter: (time, protocol) =>
126 ` set({ anomalyTimeFilter: time, Source code line. set({ anomalyTimeFilter: time,
anomalyProtocolFilter: protocol }),` anomalyProtocolFilter: protocol }),
127 ` clearAnomalyFilter: () =>` Source code line. clearAnomalyFilter: () =>
128 ` set({ anomalyTimeFilter: null, Source code line. set({ anomalyTimeFilter: null,
anomalyProtocolFilter: null }),` anomalyProtocolFilter: null }),
129 ` setCaptureInterface: (iface) => set({ Source code line. setCaptureInterface: (iface) => set({
captureInterface: iface }),` captureInterface: iface }),
130 ` setCaptureFilter: (filter) => set({ Source code line. setCaptureFilter: (filter) => set({
captureFilter: filter }),` captureFilter: filter }),
131 ` setMaxPackets: (n) => set({ Source code line. setMaxPackets: (n) => set({
maxPackets: n }),` maxPackets: n }),
132 ` setScrollToNew: (v) => set({ Source code line. setScrollToNew: (v) => set({
scrollToNew: v }),` scrollToNew: v }),
133 ` setShowRelativeTime: (v) => set({ Source code line. setShowRelativeTime: (v) => set({
showRelativeTime: v }),` showRelativeTime: v }),
134 ` setResolveNames: (v) => set({ Source code line. setResolveNames: (v) => set({
resolveNames: v }),` resolveNames: v }),
135 ` setColorRulesEnabled: (v) => set({ Source code line. setColorRulesEnabled: (v) => set({
colorRulesEnabled: v }),` colorRulesEnabled: v }),
136 ` toggleColumnVisible: (key) =>` Source code line. toggleColumnVisible: (key) =>
137 ` set((state) => ({` Source code line. set((state) => ({

Page 471 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
138 ` columns: [Link](c => Source code line. columns: [Link](c => [Link]
[Link] === key ? { ...c, visible: ![Link] } : === key ? { ...c, visible: ![Link] } : c),
c),`
139 ` })),` Source code line. })),
140 ` }),` Source code line. }),
141 ` {` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
142 ` name: 'webwireshark-storage',` Source code line. name: 'webwireshark-storage',
143 ` partialize: (state) => ({` Source code line. partialize: (state) => ({
144 ` theme: [Link],` Source code line. theme: [Link],
145 ` recentFilters: [Link],` Source code line. recentFilters: [Link],
146 ` acknowledgedAlerts: Source code line. acknowledgedAlerts:
[Link],` [Link],
147 ` captureInterface: Source code line. captureInterface: [Link],
[Link],`
148 ` captureFilter: [Link],` Source code line. captureFilter: [Link],
149 ` maxPackets: [Link],` Source code line. maxPackets: [Link],
150 ` scrollToNew: [Link],` Source code line. scrollToNew: [Link],
151 ` showRelativeTime: Source code line. showRelativeTime:
[Link],` [Link],
152 ` resolveNames: Source code line. resolveNames: [Link],
[Link],`
153 ` colorRulesEnabled: Source code line. colorRulesEnabled:
[Link],` [Link],
154 ` columns: [Link],` Source code line. columns: [Link],
155 ` }),` Source code line. }),
156 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
157 ` )` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
158 `);` Executable );
statement.

File: webwireshark/src/pages/[Link]
Total lines: 346

Page 472 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
1 `import { useState, useMemo, useRef, useEffect Executable import { useState, useMemo, useRef, useEffect
} from 'react';` statement. } from 'react';
2 `import { useGetNadsAlerts } from Executable import { useGetNadsAlerts } from
'@workspace/api-client-react';` statement. '@workspace/api-client-react';
3 `` Blank line for Separator between code blocks.
readability.
4 `import { FixedSizeList as List } from 'react- Executable import { FixedSizeList as List } from 'react-
window';` statement. window';
5 `import { ShieldCheck, ShieldAlert, X, Executable import { ShieldCheck, ShieldAlert, X,
CheckCircle, RotateCcw } from 'lucide-react';` statement. CheckCircle, RotateCcw } from 'lucide-react';
6 `import { Button } from Executable import { Button } from '@/components/ui/button';
'@/components/ui/button';` statement.
7 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
8 `import { useLocation } from 'wouter';` Executable import { useLocation } from 'wouter';
statement.
9 `` Blank line for Separator between code blocks.
readability.
10 `const CATEGORIES = ['Port Scan', 'DDoS', Named const CATEGORIES = ['Port Scan', 'DDoS',
'Brute Force', 'Exfiltration', 'C2', 'Lateral constant — 'Brute Force', 'Exfiltration', 'C2', 'L
Movement'];` value should
not change.
11 `const SEVERITIES = ['critical', 'high', 'medium', Named const SEVERITIES = ['critical', 'high', 'medium',
'low'] as const;` constant — 'low'] as const;
value should
not change.
12 `` Blank line for Separator between code blocks.
readability.
13 `function getSeverityColor(severity: string) {` Source code function getSeverityColor(severity: string) {
line.
14 ` switch ([Link]()) {` Source code switch ([Link]()) {
line.
15 ` case 'critical': return 'var(--critical)';` Executable case 'critical': return 'var(--critical)';
statement.
16 ` case 'high': return 'var(--high)';` Executable case 'high': return 'var(--high)';
statement.
17 ` case 'medium': return 'var(--medium)';` Executable case 'medium': return 'var(--medium)';
statement.
18 ` case 'low': return 'var(--low)';` Executable case 'low': return 'var(--low)';
statement.
19 ` default: return 'var(--normal)';` Executable default: return 'var(--normal)';
statement.
20 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
21 `}` Brace or C/C++ syntax structure.
parenthesis

Page 473 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
closing/openi
ng a block.
22 `` Blank line for Separator between code blocks.
readability.
23 `export default function Alerts() {` Source code export default function Alerts() {
line.
24 ` const [selectedAlertId, setSelectedAlertId] = null>(null);` Named constant — value should not change.
useState<string \
25 ` const [activeCategory, setActiveCategory] = null>(null);` Named constant — value should not change.
useState<string \
26 ` const [activeSeverity, setActiveSeverity] = null>(null);` Named constant — value should not change.
useState<string \
27 ` const [containerHeight, setContainerHeight] = Named const [containerHeight, setContainerHeight] =
useState(400);` constant — useState(400);
value should
not change.
28 ` const listContainerRef = Named const listContainerRef =
useRef<HTMLDivElement>(null);` constant — useRef<HTMLDivElement>(null);
value should
not change.
29 ` const { acknowledgedAlerts, Named const { acknowledgedAlerts,
toggleAcknowledgeAlert, anomalyTimeFilter, constant — toggleAcknowledgeAlert, anomalyTimeFilter,
anomalyProtocolFilter, clearAnomalyFilter } ...` value should anomalyPr
not change.
30 ` const [_location, setLocation] = useLocation();` Named const [_location, setLocation] = useLocation();
constant —
value should
not change.
31 `` Blank line for Separator between code blocks.
readability.
32 ` const { data: apiAlerts } = Named const { data: apiAlerts } =
useGetNadsAlerts(undefined, { query: { constant — useGetNadsAlerts(undefined, { query: {
queryKey: ['nads-alerts'] } });` value should queryKey: ['n
not change.
33 ` const baseAlerts = useMemo(() => {` Named const baseAlerts = useMemo(() => {
constant —
value should
not change.
34 ` const raw = apiAlerts ?? [];` Named const raw = apiAlerts ?? [];
constant —
value should
not change.
35 ` return [Link](a => ({ ...a, acknowledged: Exit function return [Link](a => ({ ...a, acknowledged:
[Link]([Link]) }));` and give [Link]([Link]) }))
back a value.
36 ` }, [apiAlerts, acknowledgedAlerts]);` Executable }, [apiAlerts, acknowledgedAlerts]);
statement.
37 `` Blank line for Separator between code blocks.
readability.

Page 474 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
38 ` // Apply filters from anomaly dashboard click- Comment Apply filters from anomaly dashboard click-
through` documenting through
intent.
39 ` useEffect(() => {` Source code useEffect(() => {
line.
40 ` if (anomalyProtocolFilter) {` Conditional if (anomalyProtocolFilter) {
branch — run
code only
when
condition
true.
41 ` setActiveCategory(anomalyProtocolFilter);` Executable setActiveCategory(anomalyProtocolFilter);
statement.
42 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
43 ` }, [anomalyProtocolFilter]);` Executable }, [anomalyProtocolFilter]);
statement.
44 `` Blank line for Separator between code blocks.
readability.
45 ` const displayAlerts = useMemo(() => {` Named const displayAlerts = useMemo(() => {
constant —
value should
not change.
46 ` let filtered = baseAlerts;` Executable let filtered = baseAlerts;
statement.
47 ` if (activeCategory) filtered = [Link](a => Conditional if (activeCategory) filtered = [Link](a =>
[Link] === activeCategory);` branch — run [Link] === activeCategor
code only
when
condition
true.
48 ` if (activeSeverity) filtered = [Link](a => Conditional if (activeSeverity) filtered = [Link](a =>
[Link] === activeSeverity);` branch — run [Link] === activeSeverit
code only
when
condition
true.
49 ` return filtered;` Exit function return filtered;
and give
back a value.
50 ` }, [baseAlerts, activeCategory, Executable }, [baseAlerts, activeCategory, activeSeverity]);
activeSeverity]);` statement.
51 `` Blank line for Separator between code blocks.
readability.
52 ` const selectedAlert = [Link](a => Named const selectedAlert = [Link](a => [Link]
[Link] === selectedAlertId) ?? null;` constant — === selectedAlertId) ?? null;
value should
not change.

Page 475 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
53 ` const isAcknowledged = selectedAlert ? Named const isAcknowledged = selectedAlert ?
[Link]([Link]) : constant — [Link](selectedAlert
false;` value should
not change.
54 `` Blank line for Separator between code blocks.
readability.
55 ` useEffect(() => {` Source code useEffect(() => {
line.
56 ` const el = [Link];` Named const el = [Link];
constant —
value should
not change.
57 ` if (!el) return;` Conditional if (!el) return;
branch — run
code only
when
condition
true.
58 ` const ro = new ResizeObserver(entries => {` Named const ro = new ResizeObserver(entries => {
constant —
value should
not change.
59 ` for (const entry of entries) Loop over for (const entry of entries)
setContainerHeight([Link]);` items or until setContainerHeight([Link]);
condition
changes.
60 ` });` Executable });
statement.
61 ` [Link](el);` Executable [Link](el);
statement.
62 ` Executable setContainerHeight([Link]().
setContainerHeight([Link]().h statement. height);
eight);`
63 ` return () => [Link]();` Exit function return () => [Link]();
and give
back a value.
64 ` }, []);` Executable }, []);
statement.
65 `` Blank line for Separator between code blocks.
readability.
66 ` const Row = ({ index, style }: { index: number; Named const Row = ({ index, style }: { index: number;
style: [Link] }) => {` constant — style: [Link] }) =>
value should
not change.
67 ` const alert = displayAlerts[index];` Named const alert = displayAlerts[index];
constant —
value should
not change.
68 ` if (!alert) return null;` Conditional if (!alert) return null;
branch — run
code only
when

Page 476 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
condition
true.
69 ` const isSelected = selectedAlertId === Named const isSelected = selectedAlertId === [Link];
[Link];` constant —
value should
not change.
70 ` const acked = Named const acked =
[Link]([Link]);` constant — [Link]([Link]);
value should
not change.
71 ` const severityColor = Named const severityColor =
getSeverityColor([Link]);` constant — getSeverityColor([Link]);
value should
not change.
72 `` Blank line for Separator between code blocks.
readability.
73 ` return (` Exit function return (
and give
back a value.
74 ` <div` Source code <div
line.
75 ` style={style}` Source code style={style}
line.
76 ` className={`flex items-center text-xs font- Source code className={`flex items-center text-xs font-sans
sans px-4 cursor-pointer border-b border-[var(-- line. px-4 cursor-pointer border-b border-[var(--
border-subtle)] tr...` border-su
77 ` ${isSelected ? 'bg-[var(--bg-hover)]' : Source code ${isSelected ? 'bg-[var(--bg-hover)]' : 'hover:bg-
'hover:bg-[var(--bg-hover)]'}` line. [var(--bg-hover)]'}
78 ` ${acked ? 'opacity-50' : ''}`}` Source code ${acked ? 'opacity-50' : ''}`}
line.
79 ` onClick={() => setSelectedAlertId([Link])}` Source code onClick={() => setSelectedAlertId([Link])}
line.
80 ` >` Source code >
line.

Line Source Easy Technical Explanation


Explanation
81 ` <div` Source code <div
line.
82 ` className={`absolute left-0 top-0 Source code className={`absolute left-0 top-0 bottom-0
bottom-0 w-[3px] ${[Link] === 'critical' line. w-[3px] ${[Link] === 'critical' &&
&& !acked ? 'animate-pul...` !acked ? 'anim
83 ` style={{ backgroundColor: Source code style={{ backgroundColor: severityColor }}
severityColor }}` line.
84 ` />` Source code />
line.
85 ` <div className="w-20 shrink-0 pl-3">` Source code <div className="w-20 shrink-0 pl-3">
line.

Page 477 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
86 ` <span className="px-1.5 py-0.5 Source code <span className="px-1.5 py-0.5 rounded
rounded text-[9px] font-bold text-white font- line. text-[9px] font-bold text-white font-mono
mono uppercase tracking-wider"` uppercase tracking-
87 ` style={{ backgroundColor: Source code style={{ backgroundColor: severityColor }}>
severityColor }}>` line.
88 ` {[Link]}` Source code {[Link]}
line.
89 ` </span>` Source code </span>
line.
90 ` </div>` Source code </div>
line.
91 ` <div className="w-40 shrink-0 text- Source code <div className="w-40 shrink-0 text-[var(--
[var(--text-muted)] font-mono text-[10px]">` line. text-muted)] font-mono text-[10px]">
92 ` {new Source code {new
Date([Link]).toLocaleTimeString()}` line. Date([Link]).toLocaleTimeString()}
93 ` </div>` Source code </div>
line.
94 ` <div className="w-36 shrink-0 font- Source code <div className="w-36 shrink-0 font-bold
bold text-[var(--text-primary)] truncate text- line. text-[var(--text-primary)] truncate text-
[11px]">` [11px]">
95 ` {[Link]}` Source code {[Link]}
line.
96 ` </div>` Source code </div>
line.
97 ` <div className="w-28 shrink-0">` Source code <div className="w-28 shrink-0">
line.
98 ` {[Link] && (` Source code {[Link] && (
line.
99 ` <span className="px-1.5 py-0.5 Source code <span className="px-1.5 py-0.5 rounded
rounded text-[9px] font-mono bg-[var(--bg- line. text-[9px] font-mono bg-[var(--bg-overlay)]
overlay)] border border-[var(--b...` border border-[va
100 ` {[Link]}` Source code {[Link]}
line.
101 ` </span>` Source code </span>
line.
102 ` )}` Source code )}
line.
103 ` </div>` Source code </div>
line.
104 ` <div className="w-52 shrink-0 font- Source code <div className="w-52 shrink-0 font-mono
mono text-[10px] text-[var(--accent)] line. text-[10px] text-[var(--accent)] truncate">
truncate">`
105 ` {[Link]} → {[Link]}` Source code {[Link]} → {[Link]}
line.
106 ` </div>` Source code </div>
line.
107 ` <div className="flex-1 truncate text- Source code <div className="flex-1 truncate text-[var(--
[var(--text-secondary)] text-[11px]">` line. text-secondary)] text-[11px]">

Page 478 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
108 ` <span className={acked ? 'line- Source code <span className={acked ? 'line-through
through text-[var(--text-muted)]' : line. text-[var(--text-muted)]' :
''}>{[Link]}</span>` ''}>{[Link]}</span>
109 ` </div>` Source code </div>
line.
110 ` <div className="w-24 shrink-0 flex Source code <div className="w-24 shrink-0 flex items-
items-center justify-end pr-2">` line. center justify-end pr-2">
111 ` <div className="w-20 h-1.5 bg- Source code <div className="w-20 h-1.5 bg-[var(--bg-
[var(--bg-overlay)] rounded-full overflow- line. overlay)] rounded-full overflow-hidden
hidden border border-[var(--border-...` border border-[var(--
112 ` <div className="h-full rounded-full" Source code <div className="h-full rounded-full"
style={{` line. style={{
113 ` width: Source code width: `${[Link]([Link] *
`${[Link]([Link] * 100)}%`,` line. 100)}%`,
114 ` backgroundColor: severityColor,` Source code backgroundColor: severityColor,
line.
115 ` }} />` Source code }} />
line.
116 ` </div>` Source code </div>
line.
117 ` </div>` Source code </div>
line.
118 ` </div>` Source code </div>
line.
119 ` );` Executable );
statement.
120 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
121 `` Blank line for Separator between code blocks.
readability.
122 ` return (` Exit function return (
and give back
a value.
123 ` <div className="h-full flex flex-col bg- Source code <div className="h-full flex flex-col bg-
[var(--bg-void)] text-[var(--text-primary)] line. [var(--bg-void)] text-[var(--text-primary)]
relative">` relative">
124 ` {/* Header */}` Source code {/* Header */}
line.
125 ` <div className="border-b border-[var(- Source code <div className="border-b border-[var(--
-border-strong)] bg-[var(--bg-base)] px-6 py- line. border-strong)] bg-[var(--bg-base)] px-6 py-
3 shrink-0">` 3 shrink-0">
126 ` <div className="flex items-center Source code <div className="flex items-center justify-
justify-between mb-2">` line. between mb-2">
127 ` <h1 className="text-base font-bold Source code <h1 className="text-base font-bold font-
font-sans flex items-center gap-2">` line. sans flex items-center gap-2">
128 ` <ShieldAlert className="w-5 h-5 Source code <ShieldAlert className="w-5 h-5 text-[var(-
text-[var(--accent)]" />` line. -accent)]" />

Page 479 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
129 ` Network Anomaly Detection` Source code Network Anomaly Detection
line.
130 ` </h1>` Source code </h1>
line.
131 ` {(anomalyTimeFilter \ \ anomalyProtocolFilter) && (`
132 ` <button` Source code <button
line.
133 ` className="flex items-center gap- Source code className="flex items-center gap-1.5 text-
1.5 text-xs font-mono px-2 py-1 rounded line. xs font-mono px-2 py-1 rounded border
border border-[var(--accent)] ...` border-[var(--accent
134 ` onClick={() => { Source code onClick={() => { clearAnomalyFilter();
clearAnomalyFilter(); line. setActiveCategory(null); }}
setActiveCategory(null); }}`
135 ` >` Source code >
line.
136 ` <RotateCcw className="w-3 h-3" Source code <RotateCcw className="w-3 h-3" />
/>` line.
137 ` Clear anomaly filter` Source code Clear anomaly filter
line.
138 ` </button>` Source code </button>
line.
139 ` )}` Source code )}
line.
140 ` </div>` Source code </div>
line.
141 ` <div className="flex gap-4">` Source code <div className="flex gap-4">
line.
142 ` {[Link](sev => {` Source code {[Link](sev => {
line.
143 ` const count = [Link](a => Named const count = [Link](a =>
[Link] === sev).length;` constant — [Link] === sev).length;
value should
not change.
144 ` const active = activeSeverity === Named const active = activeSeverity === sev;
sev;` constant —
value should
not change.
145 ` return (` Exit function return (
and give back
a value.
146 ` <button` Source code <button
line.
147 ` key={sev}` Source code key={sev}
line.
148 ` onClick={() => Source code onClick={() => setActiveSeverity(active ?
setActiveSeverity(active ? null : sev)}` line. null : sev)}
149 ` className={`flex items-center Source code className={`flex items-center gap-2 text-
gap-2 text-[10px] font-mono rounded px-2 line. [10px] font-mono rounded px-2 py-0.5
py-0.5 transition-colors border` transition-colors bord

Page 480 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
150 ` ${active ? 'border-current' : Source code ${active ? 'border-current' : 'border-
'border-transparent hover:border-[var(-- line. transparent hover:border-[var(--border-
border-strong)]'}`}` strong)]'}`}
151 ` style={{ color: Source code style={{ color: getSeverityColor(sev) }}
getSeverityColor(sev) }}` line.
152 ` >` Source code >
line.
153 ` <div className="w-2 h-2 Source code <div className="w-2 h-2 rounded-full"
rounded-full" style={{ backgroundColor: line. style={{ backgroundColor:
getSeverityColor(sev) }} />` getSeverityColor(sev) }} />
154 ` <span className="uppercase Source code <span className="uppercase tracking-
tracking-wider">{sev}</span>` line. wider">{sev}</span>
155 ` <span className="font-bold text- Source code <span className="font-bold text-[var(--
[var(--text-primary)]">{count}</span>` line. text-primary)]">{count}</span>
156 ` </button>` Source code </button>
line.
157 ` );` Executable );
statement.
158 ` })}` Source code })}
line.
159 ` </div>` Source code </div>
line.
160 ` </div>` Source code </div>
line.

Line Source Easy Technical Explanation


Explanation
161 `` Blank line for Separator between code blocks.
readability.
162 ` {/* Filter Bar */}` Source code {/* Filter Bar */}
line.
163 ` <div className="h-10 border-b Source code <div className="h-10 border-b border-
border-[var(--border-subtle)] flex items- line. [var(--border-subtle)] flex items-center px-
center px-4 gap-2 shrink-0 bg-[var(--bg-...` 4 gap-2 shrink-0 bg
164 ` <span className="font-mono text- Source code <span className="font-mono text-[10px]
[10px] font-bold text-[var(--text-muted)] line. font-bold text-[var(--text-muted)]
uppercase tracking-wider mr-1">Cate...` uppercase tracking-wider m
165 ` {[Link](cat => {` Source code {[Link](cat => {
line.
166 ` const active = activeCategory === Named const active = activeCategory === cat;
cat;` constant —
value should
not change.
167 ` return (` Exit function return (
and give back
a value.
168 ` <button` Source code <button
line.
169 ` key={cat}` Source code key={cat}
line.

Page 481 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
170 ` onClick={() => Source code onClick={() => setActiveCategory(active ?
setActiveCategory(active ? null : cat)}` line. null : cat)}
171 ` className={`px-2 py-0.5 Source code className={`px-2 py-0.5 rounded text-
rounded text-[10px] font-mono border line. [10px] font-mono border transition-colors
transition-colors`
172 ` ${active` Source code ${active
line.
173 ` ? 'border-[var(--accent)] text- Source code ? 'border-[var(--accent)] text-[var(--accent)]
[var(--accent)] bg-[var(--accent-dim)]'` line. bg-[var(--accent-dim)]'
174 ` : 'border-[var(--border-strong)] Source code : 'border-[var(--border-strong)] text-[var(--
text-[var(--text-secondary)] hover:border- line. text-secondary)] hover:border-[var(--
[var(--accent)] hover:te...` accent)] hover:tex
175 ` >` Source code >
line.
176 ` {cat}` Source code {cat}
line.
177 ` </button>` Source code </button>
line.
178 ` );` Executable );
statement.
179 ` })}` Source code })}
line.
180 ` <span className="ml-auto font- Source code <span className="ml-auto font-mono
mono text-[10px] text-[var(--text-muted)]">` line. text-[10px] text-[var(--text-muted)]">
181 ` {[Link]} / Source code {[Link]} / {[Link]}
{[Link]} alerts` line. alerts
182 ` </span>` Source code </span>
line.
183 ` </div>` Source code </div>
line.
184 `` Blank line for Separator between code blocks.
readability.
185 ` <div className="flex-1 flex overflow- Source code <div className="flex-1 flex overflow-
hidden">` line. hidden">
186 ` {/* Main List */}` Source code {/* Main List */}
line.
187 ` <div className="flex-1 flex flex-col Source code <div className="flex-1 flex flex-col
overflow-hidden">` line. overflow-hidden">
188 ` {/* Column headers */}` Source code {/* Column headers */}
line.
189 ` <div className="flex items-center Source code <div className="flex items-center text-
text-[9px] font-mono font-bold text-[var(-- line. [9px] font-mono font-bold text-[var(--text-
text-muted)] uppercase trackin...` muted)] uppercase
190 ` <div className="w-20 shrink-0 pl- Source code <div className="w-20 shrink-0 pl-
3">Severity</div>` line. 3">Severity</div>
191 ` <div className="w-40 shrink- Source code <div className="w-40 shrink-
0">Time</div>` line. 0">Time</div>
192 ` <div className="w-36 shrink- Source code <div className="w-36 shrink-
0">Detector</div>` line. 0">Detector</div>

Page 482 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
193 ` <div className="w-28 shrink- Source code <div className="w-28 shrink-
0">MITRE</div>` line. 0">MITRE</div>
194 ` <div className="w-52 shrink- Source code <div className="w-52 shrink-
0">Flow</div>` line. 0">Flow</div>
195 ` <div className="flex- Source code <div className="flex-
1">Description</div>` line. 1">Description</div>
196 ` <div className="w-24 shrink-0 Source code <div className="w-24 shrink-0 text-right
text-right pr-2">Confidence</div>` line. pr-2">Confidence</div>
197 ` </div>` Source code </div>
line.
198 `` Blank line for Separator between code blocks.
readability.
199 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-hidden
hidden relative" ref={listContainerRef}>` line. relative" ref={listContainerRef}>
200 ` {[Link] === 0 ? (` Source code {[Link] === 0 ? (
line.
201 ` <div className="absolute inset-0 Source code <div className="absolute inset-0 flex
flex flex-col items-center justify-center text- line. flex-col items-center justify-center text-
[var(--text-muted)] opa...` [var(--text-muted)]
202 ` <ShieldCheck className="w-20 Source code <ShieldCheck className="w-20 h-20 mb-
h-20 mb-4 text-[var(--normal)]" line. 4 text-[var(--normal)]" strokeWidth={1} />
strokeWidth={1} />`
203 ` <span className="font-mono Source code <span className="font-mono text-base
text-base text-[var(--text-primary)]">All line. text-[var(--text-primary)]">All clear — no
clear — no alerts detected</span>` alerts detected</spa
204 ` </div>` Source code </div>
line.
205 ` ) : (` Source code ):(
line.
206 ` <List` Source code <List
line.
207 ` height={containerHeight}` Source code height={containerHeight}
line.
208 ` Source code itemCount={[Link]}
itemCount={[Link]}` line.
209 ` itemSize={40}` Source code itemSize={40}
line.
210 ` width="100%"` Source code width="100%"
line.
211 ` >` Source code >
line.
212 ` {Row}` Source code {Row}
line.
213 ` </List>` Source code </List>
line.
214 ` )}` Source code )}
line.
215 ` </div>` Source code </div>
line.

Page 483 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
216 ` </div>` Source code </div>
line.
217 `` Blank line for Separator between code blocks.
readability.
218 ` {/* Slide-in Detail Panel */}` Source code {/* Slide-in Detail Panel */}
line.
219 ` <div className={`w-[400px] border-l Source code <div className={`w-[400px] border-l
border-[var(--border-strong)] bg-[var(--bg- line. border-[var(--border-strong)] bg-[var(--bg-
base)] flex flex-col shrink-0 ...` base)] flex flex-col
220 ` ${selectedAlertId ? 'translate-x-0' : Source code ${selectedAlertId ? 'translate-x-0' :
'translate-x-full absolute right-0 top-0 line. 'translate-x-full absolute right-0 top-0
bottom-0 z-50 shadow-2xl'}`}>` bottom-0 z-50 shadow-
221 ` {selectedAlert ? (` Source code {selectedAlert ? (
line.
222 ` <>` Source code <>
line.
223 ` <div className="h-11 border-b Source code <div className="h-11 border-b border-
border-[var(--border-strong)] flex items- line. [var(--border-strong)] flex items-center
center justify-between px-4 shri...` justify-between px-4 s
224 ` <span className="font-mono Source code <span className="font-mono font-bold
font-bold text-xs">Alert Details</span>` line. text-xs">Alert Details</span>
225 ` <Button variant="ghost" Source code <Button variant="ghost" size="icon"
size="icon" onClick={() => line. onClick={() => setSelectedAlertId(null)}
setSelectedAlertId(null)}`
226 ` className="w-7 h-7 hover:bg- Source code className="w-7 h-7 hover:bg-[var(--bg-
[var(--bg-hover)]">` line. hover)]">
227 ` <X className="w-3.5 h-3.5" Source code <X className="w-3.5 h-3.5" />
/>` line.
228 ` </Button>` Source code </Button>
line.
229 ` </div>` Source code </div>
line.
230 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-auto p-4
auto p-4 flex flex-col gap-4">` line. flex flex-col gap-4">
231 ` {/* Severity + title */}` Source code {/* Severity + title */}
line.
232 ` <div>` Source code <div>
line.
233 ` <span className="px-2 py-1 Source code <span className="px-2 py-1 rounded
rounded text-[10px] font-bold text-white line. text-[10px] font-bold text-white font-mono
font-mono uppercase tracking-wi...` uppercase tracking-wid
234 ` style={{ backgroundColor: Source code style={{ backgroundColor:
getSeverityColor([Link]) line. getSeverityColor([Link])
}}>` }}>
235 ` {[Link]} Source code {[Link]} severity
severity` line.
236 ` </span>` Source code </span>
line.
237 ` {isAcknowledged && (` Source code {isAcknowledged && (
line.

Page 484 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
238 ` <span className="ml-2 px-2 Source code <span className="ml-2 px-2 py-1
py-1 rounded text-[10px] font-mono bg- line. rounded text-[10px] font-mono bg-[var(--
[var(--bg-overlay)] text-[var(--...` bg-overlay)] text-[var(--tex
239 ` acknowledged` Source code acknowledged
line.
240 ` </span>` Source code </span>
line.

Lin Source Easy Technical Explanation


e Explanatio
n
241 ` )}` Source code )}
line.
242 ` <h2 className="text-sm font-bold Source code <h2 className="text-sm font-bold mt-
mt-2">{[Link]}</h2>` line. 2">{[Link]}</h2>
243 ` <p className={`text-[var(--text- Source code <p className={`text-[var(--text-secondary)]
secondary)] text-xs mt-1 ${isAcknowledged ? line. text-xs mt-1 ${isAcknowledged ? 'line-through' :
'line-through' : ''}`}>` ''}`}>
244 ` {[Link]}` Source code {[Link]}
line.
245 ` </p>` Source code </p>
line.
246 ` </div>` Source code </div>
line.
247 `` Blank line for Separator between code blocks.
readability.
248 ` {/* Confidence */}` Source code {/* Confidence */}
line.
249 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)] border
overlay)] border border-[var(--border-subtle)] line. border-[var(--border-subtle)] rounded p-3">
rounded p-3">`
250 ` <div className="font-mono font- Source code <div className="font-mono font-bold text-[9px]
bold text-[9px] text-[var(--text-muted)] mb-2 line. text-[var(--text-muted)] mb-2 uppercase
uppercase tracking-wid...` tracking-wide
251 ` <div className="flex items-center Source code <div className="flex items-center gap-3">
gap-3">` line.
252 ` <div className="flex-1 h-2 bg- Source code <div className="flex-1 h-2 bg-[var(--bg-base)]
[var(--bg-base)] rounded-full overflow-hidden line. rounded-full overflow-hidden border border-
border border-[var(--...` [var(--bor
253 ` <div className="h-full rounded- Source code <div className="h-full rounded-full transition-
full transition-all" style={{` line. all" style={{
254 ` width: Source code width: `${[Link]([Link] *
`${[Link]([Link] * line. 100)}%`,
100)}%`,`
255 ` backgroundColor: Source code backgroundColor:
getSeverityColor([Link]),` line. getSeverityColor([Link]),
256 ` }} />` Source code }} />
line.
257 ` </div>` Source code </div>
line.

Page 485 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
258 ` <span className="font-mono font- Source code <span className="font-mono font-bold text-xs
bold text-xs text-[var(--accent)]">` line. text-[var(--accent)]">
259 ` Source code {[Link]([Link] * 100)}%
{[Link]([Link] * 100)}%` line.
260 ` </span>` Source code </span>
line.
261 ` </div>` Source code </div>
line.
262 ` </div>` Source code </div>
line.
263 `` Blank line for Separator between code blocks.
readability.
264 ` {/* Flow */}` Source code {/* Flow */}
line.
265 ` <div>` Source code <div>
line.
266 ` <div className="font-mono font- Source code <div className="font-mono font-bold text-[9px]
bold text-[9px] text-[var(--text-muted)] mb-1.5 line. text-[var(--text-muted)] mb-1.5 uppercase
uppercase tracking-w...` tracking-wi
267 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)] border
overlay)] border border-[var(--border-subtle)] line. border-[var(--border-subtle)] rounded p-3 font-
rounded p-3 font-mono t...` mono te
268 ` {[['Source', [Link]], Source code {[['Source', [Link]], ['Destination',
['Destination', [Link]],` line. [Link]],
269 ` ['Detected', new Source code ['Detected', new
Date([Link]).toLocaleString()], line. Date([Link]).toLocaleString()]
` ,
270 ` ['Category', Source code ['Category', [Link]]].map(([label,
[Link]]].map(([label, val]) => (` line. val]) => (
271 ` <div key={label} className="flex Source code <div key={label} className="flex justify-
justify-between">` line. between">
272 ` <span className="text-[var(-- Source code <span className="text-[var(--text-
text-muted)]">{label}:</span>` line. muted)]">{label}:</span>
273 ` <span className="text-[var(-- Source code <span className="text-[var(--accent)] font-
accent)] font-bold">{val}</span>` line. bold">{val}</span>
274 ` </div>` Source code </div>
line.
275 ` ))}` Source code ))}
line.
276 ` </div>` Source code </div>
line.
277 ` </div>` Source code </div>
line.
278 `` Blank line for Separator between code blocks.
readability.
279 ` {/* Evidence */}` Source code {/* Evidence */}
line.

Page 486 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
280 ` {[Link] && Source code {[Link] &&
[Link] > 0 && (` line. [Link] > 0 && (
281 ` <div>` Source code <div>
line.
282 ` <div className="font-mono font- Source code <div className="font-mono font-bold text-[9px]
bold text-[9px] text-[var(--text-muted)] mb-1.5 line. text-[var(--text-muted)] mb-1.5 uppercase
uppercase tracking...` tracking-wi
283 ` <ul className="space-y-1">` Source code <ul className="space-y-1">
line.
284 ` {[Link]((ev, Source code {[Link]((ev, i) => (
i) => (` line.
285 ` <li key={i} className="text-xs Source code <li key={i} className="text-xs text-[var(--text-
text-[var(--text-secondary)] flex items-start gap- line. secondary)] flex items-start gap-2">
2">`
286 ` <span className="text-[var(-- Source code <span className="text-[var(--accent)] mt-
accent)] mt-0.5">›</span>` line. 0.5">›</span>
287 ` <span>{ev}</span>` Source code <span>{ev}</span>
line.
288 ` </li>` Source code </li>
line.
289 ` ))}` Source code ))}
line.
290 ` </ul>` Source code </ul>
line.
291 ` </div>` Source code </div>
line.
292 ` )}` Source code )}
line.
293 `` Blank line for Separator between code blocks.
readability.
294 ` {/* MITRE */}` Source code {/* MITRE */}
line.
295 ` {[Link] && Source code {[Link] &&
[Link] > 0 && (` line. [Link] > 0 && (
296 ` <div>` Source code <div>
line.
297 ` <div className="font-mono font- Source code <div className="font-mono font-bold text-[9px]
bold text-[9px] text-[var(--text-muted)] mb-1.5 line. text-[var(--text-muted)] mb-1.5 uppercase
uppercase tracking...` tracking-wi
298 ` <div className="flex flex-wrap Source code <div className="flex flex-wrap gap-1.5">
gap-1.5">` line.
299 ` {[Link] && Source code {[Link] && (
(` line.
300 ` <span className="px-2 py-0.5 Source code <span className="px-2 py-0.5 rounded text-
rounded text-[10px] font-mono bg-[var(--accent- line. [10px] font-mono bg-[var(--accent-dim)] border
dim)] border bord...` border-[var
301 ` {[Link]}` Source code {[Link]}
line.

Page 487 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
302 ` </span>` Source code </span>
line.
303 ` )}` Source code )}
line.
304 ` Source code {[Link]((tac, i) => (
{[Link]((tac, i) => (` line.
305 ` <span key={i} className="px-2 Source code <span key={i} className="px-2 py-0.5 rounded
py-0.5 rounded text-[10px] font-mono bg-[var(-- line. text-[10px] font-mono bg-[var(--bg-hover)]
bg-hover)] borde...` border borde
306 ` {tac}` Source code {tac}
line.
307 ` </span>` Source code </span>
line.
308 ` ))}` Source code ))}
line.
309 ` </div>` Source code </div>
line.
310 ` </div>` Source code </div>
line.
311 ` )}` Source code )}
line.
312 ` </div>` Source code </div>
line.
313 `` Blank line for Separator between code blocks.
readability.
314 ` {/* Footer actions */}` Source code {/* Footer actions */}
line.
315 ` <div className="p-3 border-t border- Source code <div className="p-3 border-t border-[var(--
[var(--border-strong)] bg-[var(--bg-overlay)] flex line. border-strong)] bg-[var(--bg-overlay)] flex gap-2
gap-2 shrink-0">` shrink-
316 ` <Button` Source code <Button
line.
317 ` size="sm"` Source code size="sm"
line.
318 ` className="flex-1 text-xs font-bold Source code className="flex-1 text-xs font-bold h-8"
h-8"` line.
319 ` style={{ backgroundColor: 'var(-- Source code style={{ backgroundColor: 'var(--accent)', color:
accent)', color: 'var(--bg-void)' }}` line. 'var(--bg-void)' }}
320 ` onClick={() => setLocation('/')}` Source code onClick={() => setLocation('/')}
line.

Line Source Easy Technical Explanation


Explanation
321 ` >` Source code >
line.
322 ` Go to Packets` Source code Go to Packets
line.

Page 488 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
323 ` </Button>` Source code </Button>
line.
324 ` <Button` Source code <Button
line.
325 ` size="sm"` Source code size="sm"
line.
326 ` variant="outline"` Source code variant="outline"
line.
327 ` className={`flex-1 text-xs h-8 Source code className={`flex-1 text-xs h-8 border-
border-[var(--border-strong)] flex items- line. [var(--border-strong)] flex items-center
center gap-1.5 transition-c...` gap-1.5 transition-co
328 ` ${isAcknowledged` Source code ${isAcknowledged
line.
329 ` ? 'text-[var(--normal)] border- Source code ? 'text-[var(--normal)] border-[var(--
[var(--normal)]/40 hover:bg-[var(-- line. normal)]/40 hover:bg-[var(--normal)]/10'
normal)]/10'`
330 ` : 'text-[var(--text-primary)] Source code : 'text-[var(--text-primary)] hover:bg-[var(--
hover:bg-[var(--bg-hover)]'}`}` line. bg-hover)]'}`}
331 ` onClick={() => Source code onClick={() =>
toggleAcknowledgeAlert([Link])}` line. toggleAcknowledgeAlert([Link])}
332 ` >` Source code >
line.
333 ` {isAcknowledged ? (` Source code {isAcknowledged ? (
line.
334 ` <><RotateCcw Source code <><RotateCcw className="w-3 h-3" />
className="w-3 h-3" /> line. Unacknowledge</>
Unacknowledge</>`
335 ` ) : (` Source code ):(
line.
336 ` <><CheckCircle Source code <><CheckCircle className="w-3 h-3" />
className="w-3 h-3" /> Acknowledge</>` line. Acknowledge</>
337 ` )}` Source code )}
line.
338 ` </Button>` Source code </Button>
line.
339 ` </div>` Source code </div>
line.
340 ` </>` Source code </>
line.
341 ` ) : null}` Source code ) : null}
line.
342 ` </div>` Source code </div>
line.
343 ` </div>` Source code </div>
line.
344 ` </div>` Source code </div>
line.
345 ` );` Executable );
statement.

Page 489 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
346 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

File: webwireshark/src/pages/[Link]
Total lines: 351

Line Source Easy Technical Explanation


Explanation
1 `import { useMemo } from 'react';` Executable import { useMemo } from 'react';
statement.
2 `import {` Source code line. import {
3 ` AreaChart, Area, XAxis, YAxis, Source code line. AreaChart, Area, XAxis, YAxis,
CartesianGrid, Tooltip as CartesianGrid, Tooltip as
RechartsTooltip,` RechartsTooltip,
4 ` ResponsiveContainer, PieChart, Pie, Source code line. ResponsiveContainer, PieChart, Pie,
Cell,` Cell,
5 `} from 'recharts';` Executable } from 'recharts';
statement.
6 `import { Activity, ArrowUpRight, Executable import { Activity, ArrowUpRight,
ArrowDownRight, ArrowRight } from statement. ArrowDownRight, ArrowRight } from
'lucide-react';` 'lucide-react';
7 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
8 `import { useLocation } from 'wouter';` Executable import { useLocation } from 'wouter';
statement.
9 `import { useGetNadsSummary, Executable import { useGetNadsSummary,
useGetThreatTimeline, useGetThreatIps, statement. useGetThreatTimeline,
useGetNadsFlows, useGetProtocolStats } useGetThreatIps, useGetNadsFlows,
from '@work...` useGetProtocolSt
10 `` Blank line for Separator between code blocks.
readability.
11 `const SEVERITY_COLORS = {` Named constant — const SEVERITY_COLORS = {
value should not
change.
12 ` critical: 'var(--critical)',` Source code line. critical: 'var(--critical)',
13 ` high: 'var(--high)',` Source code line. high: 'var(--high)',
14 ` medium: 'var(--medium)',` Source code line. medium: 'var(--medium)',
15 ` low: 'var(--low)',` Source code line. low: 'var(--low)',
16 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 490 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
17 `` Blank line for Separator between code blocks.
readability.
18 `const PROTOCOL_COLORS = Named constant — const PROTOCOL_COLORS =
['#FF5949', '#FF8A6B', '#FFC4A8', value should not ['#FF5949', '#FF8A6B', '#FFC4A8',
'#CC3D30', '#FF7063', '#E6443A'];` change. '#CC3D30', '#FF7063',
19 `` Blank line for Separator between code blocks.
readability.
20 `function CustomTimelineTooltip({ active, Source code line. function CustomTimelineTooltip({ active,
payload, label, onClickFilter }: any) {` payload, label, onClickFilter }: any) {
21 ` if (!active \ \ !payload?.length) return null;`
22 ` const total = [Link]((s: \ 0), 0);`
number, p: any) => s + ([Link] \
23 ` return (` Exit function and return (
give back a value.
24 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- border border-[var(--border-strong)]
strong)] rounded p-3 text-xs font-mono rounded p-3 text-xs font
shadow-...`
25 ` <div className="text-[var(--text- Source code line. <div className="text-[var(--text-
muted)] mb-2">{label}</div>` muted)] mb-2">{label}</div>
26 ` {[Link]((p: any) => (` Source code line. {[Link]((p: any) => (
27 ` <div key={[Link]} Source code line. <div key={[Link]} className="flex
className="flex items-center justify- items-center justify-between gap-4 mb-
between gap-4 mb-1">` 1">
28 ` <span style={{ color: [Link] Source code line. <span style={{ color: [Link]
}}>{[Link]}</span>` }}>{[Link]}</span>
29 ` <span className="font-bold text- Source code line. <span className="font-bold text-[var(--
[var(--text-primary)]">{[Link]}</span>` text-primary)]">{[Link]}</span>
30 ` </div>` Source code line. </div>
31 ` ))}` Source code line. ))}
32 ` <div className="border-t border- Source code line. <div className="border-t border-[var(--
[var(--border-subtle)] mt-2 pt-2 flex justify- border-subtle)] mt-2 pt-2 flex justify-
between">` between">
33 ` <span className="text-[var(--text- Source code line. <span className="text-[var(--text-
muted)]">total</span>` muted)]">total</span>
34 ` <span className="font-bold text- Source code line. <span className="font-bold text-[var(--
[var(--accent)]">{total}</span>` accent)]">{total}</span>
35 ` </div>` Source code line. </div>
36 ` <button` Source code line. <button
37 ` className="mt-2 w-full text-[9px] Source code line. className="mt-2 w-full text-[9px]
uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
accent)] hover:text-[var(--text-primar...` accent)] hover:text-[var(--te
38 ` onClick={() => onClickFilter && Source code line. onClick={() => onClickFilter &&
onClickFilter(label)}` onClickFilter(label)}
39 ` >` Source code line. >
40 ` <ArrowRight className="w-2.5 h- Source code line. <ArrowRight className="w-2.5 h-2.5"
2.5" /> Filter alerts at {label}` /> Filter alerts at {label}
41 ` </button>` Source code line. </button>

Page 491 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
42 ` </div>` Source code line. </div>
43 ` );` Executable );
statement.
44 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
45 `` Blank line for Separator between code blocks.
readability.
46 `function CustomDonutTooltip({ active, Source code line. function CustomDonutTooltip({ active,
payload, onClickFilter }: any) {` payload, onClickFilter }: any) {
47 ` if (!active \ \ !payload?.length) return null;`
48 ` const entry = payload[0];` Named constant — const entry = payload[0];
value should not
change.
49 ` return (` Exit function and return (
give back a value.
50 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- border border-[var(--border-strong)]
strong)] rounded p-3 text-xs font-mono rounded p-3 text-xs font
shadow-...`
51 ` <div className="font-bold text-[var(- Source code line. <div className="font-bold text-[var(--
-text-primary)] mb-1">{[Link]}</div>` text-primary)] mb-1">{[Link]}</div>
52 ` <div className="flex justify-between Source code line. <div className="flex justify-between
gap-6">` gap-6">
53 ` <span className="text-[var(--text- Source code line. <span className="text-[var(--text-
muted)]">anomalies</span>` muted)]">anomalies</span>
54 ` <span style={{ color: Source code line. <span style={{ color: [Link] }}
[Link] }} className="font- className="font-
bold">{[Link]}</span>` bold">{[Link]}</span>
55 ` </div>` Source code line. </div>
56 ` <button` Source code line. <button
57 ` className="mt-2 w-full text-[9px] Source code line. className="mt-2 w-full text-[9px]
uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
accent)] hover:text-[var(--text-primar...` accent)] hover:text-[var(--te
58 ` onClick={() => onClickFilter && Source code line. onClick={() => onClickFilter &&
onClickFilter([Link])}` onClickFilter([Link])}
59 ` >` Source code line. >
60 ` <ArrowRight className="w-2.5 h- Source code line. <ArrowRight className="w-2.5 h-2.5"
2.5" /> Filter by {[Link]}` /> Filter by {[Link]}
61 ` </button>` Source code line. </button>
62 ` </div>` Source code line. </div>
63 ` );` Executable );
statement.
64 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 492 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
65 `` Blank line for Separator between code blocks.
readability.
66 `export default function Anomaly() {` Source code line. export default function Anomaly() {
67 ` const setAnomalyFilter = useAppStore(s Named constant — const setAnomalyFilter = useAppStore(s
=> [Link]);` value should not => [Link]);
change.
68 ` const [_location, setLocation] = Named constant — const [_location, setLocation] =
useLocation();` value should not useLocation();
change.
69 `` Blank line for Separator between code blocks.
readability.
70 ` const { data: summary } = Named constant — const { data: summary } =
useGetNadsSummary(undefined, { query: value should not useGetNadsSummary(undefined, {
{ queryKey: ['nads-summary'] } });` change. query: { queryKey: ['na
71 ` const { data: timeline } = Named constant — const { data: timeline } =
useGetThreatTimeline(undefined, { query: value should not useGetThreatTimeline(undefined, {
{ queryKey: ['nads-timeline'] } });` change. query: { queryKey:
72 ` const { data: threatIps } = Named constant — const { data: threatIps } =
useGetThreatIps(undefined, { query: { value should not useGetThreatIps(undefined, { query: {
queryKey: ['nads-threat-ips'] } });` change. queryKey: ['na
73 ` const { data: flows } = Named constant — const { data: flows } =
useGetNadsFlows(undefined, { query: { value should not useGetNadsFlows(undefined, { query: {
queryKey: ['nads-flows'] } });` change. queryKey: ['nads-f
74 ` const { data: protocols } = Named constant — const { data: protocols } =
useGetProtocolStats(undefined, { query: { value should not useGetProtocolStats(undefined, { query:
queryKey: ['protocol-stats'] } });` change. { queryKey:
75 `` Blank line for Separator between code blocks.
readability.
76 ` const timelineData = useMemo(() => {` Named constant — const timelineData = useMemo(() => {
value should not
change.
77 ` if (timeline && [Link] > 0) {` Conditional branch if (timeline && [Link] > 0) {
— run code only
when condition
true.
78 ` return [Link](-60).map((p, i) => Exit function and return [Link](-60).map((p, i) => ({
({` give back a value.
79 ` time: `-${60 - i}m`,` Source code line. time: `-${60 - i}m`,
80 ` critical: [Link],` Source code line. critical: [Link],

Line Source Easy Technical Explanation


Explanation
81 ` high: [Link],` Source code line. high: [Link],
82 ` medium: [Link],` Source code line. medium: [Link],
83 ` low: [Link],` Source code line. low: [Link],
84 ` }));` Executable }));
statement.
85 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 493 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
86 ` // FIX: Show zeroed timeline until real Comment FIX: Show zeroed timeline until real
alerts arrive — random mock data` documenting intent. alerts arrive — random mock data
87 ` // was making the dashboard look Comment was making the dashboard look like it
like it was detecting things when it documenting intent. was detecting things when it wasn't.
wasn't.`
88 ` return [Link]({ length: 60 Exit function and return [Link]({ length: 60
}).map((_, i) => ({` give back a value. }).map((_, i) => ({
89 ` time: `-${60 - i}m`,` Source code line. time: `-${60 - i}m`,
90 ` critical: 0,` Source code line. critical: 0,
91 ` high: 0,` Source code line. high: 0,
92 ` medium: 0,` Source code line. medium: 0,
93 ` low: 0,` Source code line. low: 0,
94 ` }));` Executable }));
statement.
95 ` }, [timeline]);` Executable }, [timeline]);
statement.
96 `` Blank line for Separator between code blocks.
readability.
97 ` const protocolData = useMemo(() => {` Named constant — const protocolData = useMemo(() => {
value should not
change.
98 ` if (protocols && [Link] > 0) {` Conditional branch if (protocols && [Link] > 0) {
— run code only
when condition true.
99 ` return (protocols[0]?.children ?? Exit function and return (protocols[0]?.children ??
protocols).slice(0, 6).map((p, i) => ({` give back a value. protocols).slice(0, 6).map((p, i) => ({
100 ` name: [Link],` Source code line. name: [Link],
101 ` value: [Link],` Source code line. value: [Link],
102 ` fill: PROTOCOL_COLORS[i % Source code line. fill: PROTOCOL_COLORS[i %
PROTOCOL_COLORS.length],` PROTOCOL_COLORS.length],
103 ` }));` Executable }));
statement.
104 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
105 ` return [` Exit function and return [
give back a value.
106 ` { name: 'TCP', value: 1240, fill: Source code line. { name: 'TCP', value: 1240, fill:
PROTOCOL_COLORS[0] },` PROTOCOL_COLORS[0] },
107 ` { name: 'UDP', value: 890, fill: Source code line. { name: 'UDP', value: 890, fill:
PROTOCOL_COLORS[1] },` PROTOCOL_COLORS[1] },
108 ` { name: 'DNS', value: 432, fill: Source code line. { name: 'DNS', value: 432, fill:
PROTOCOL_COLORS[2] },` PROTOCOL_COLORS[2] },
109 ` { name: 'TLS', value: 234, fill: Source code line. { name: 'TLS', value: 234, fill:
PROTOCOL_COLORS[3] },` PROTOCOL_COLORS[3] },

Page 494 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
110 ` { name: 'QUIC', value: 178, fill: Source code line. { name: 'QUIC', value: 178, fill:
PROTOCOL_COLORS[4] },` PROTOCOL_COLORS[4] },
111 ` { name: 'ICMP', value: 67, fill: Source code line. { name: 'ICMP', value: 67, fill:
PROTOCOL_COLORS[5] },` PROTOCOL_COLORS[5] },
112 ` ];` Executable ];
statement.
113 ` }, [protocols]);` Executable }, [protocols]);
statement.
114 `` Blank line for Separator between code blocks.
readability.
115 ` const totalProtoAnomalies = Named constant — const totalProtoAnomalies =
[Link]((s, d) => s + [Link], value should not [Link]((s, d) => s +
0);` change. [Link], 0);
116 `` Blank line for Separator between code blocks.
readability.
117 ` const displayFlows = useMemo(() => {` Named constant — const displayFlows = useMemo(() => {
value should not
change.
118 ` const base = flows ?? [];` Named constant — const base = flows ?? [];
value should not
change.
119 ` // FIX: API returns threatScore as Comment FIX: API returns threatScore as integer
integer 0-100, not fraction 0.0-1.0` documenting intent. 0-100, not fraction 0.0-1.0
120 ` return [Link](f => [Link] > Exit function and return [Link](f => [Link] >
50).sort((a, b) => [Link] - give back a value. 50).sort((a, b) => [Link] - [Link]
[Link]).slice(0, 5);`
121 ` }, [flows]);` Executable }, [flows]);
statement.
122 `` Blank line for Separator between code blocks.
readability.
123 ` const displayThreatIps = useMemo(() Named constant — const displayThreatIps = useMemo(()
=> {` value should not => {
change.
124 ` if (threatIps && [Link] > 0) Conditional branch if (threatIps && [Link] > 0)
return [Link](0, 5);` — run code only return [Link](0, 5);
when condition true.
125 ` return [` Exit function and return [
give back a value.
126 ` { ip: '[Link]', country: 'China', Source code line. { ip: '[Link]', country: 'China',
countryCode: 'CN', alertCount: 14, countryCode: 'CN', alertCount: 14,
threatScore: 0.97 },` threatScore: 0.97 },
127 ` { ip: '[Link]', country: Source code line. { ip: '[Link]', country: 'Russia',
'Russia', countryCode: 'RU', alertCount: countryCode: 'RU', alertCount: 9,
9, threatScore: 0.89 },` threatScore: 0.89 },
128 ` { ip: '[Link]', country: Source code line. { ip: '[Link]', country:
'Netherlands', countryCode: 'NL', 'Netherlands', countryCode: 'NL',
alertCount: 6, threatScore: 0.74 },` alertCount: 6, threatScore: 0.74 },
129 ` { ip: '[Link]', country: 'Brazil', Source code line. { ip: '[Link]', country: 'Brazil',
countryCode: 'BR', alertCount: 4, countryCode: 'BR', alertCount: 4,
threatScore: 0.61 },` threatScore: 0.61 },

Page 495 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
130 ` { ip: '[Link]', country: Source code line. { ip: '[Link]', country:
'Ukraine', countryCode: 'UA', alertCount: 'Ukraine', countryCode: 'UA',
3, threatScore: 0.55 },` alertCount: 3, threatScore: 0.55 },
131 ` ];` Executable ];
statement.
132 ` }, [threatIps]);` Executable }, [threatIps]);
statement.
133 `` Blank line for Separator between code blocks.
readability.
134 ` const summaryData = summary ?? {` Named constant — const summaryData = summary ?? {
value should not
change.
135 ` activeFlows: 0, alertsToday: 0, Source code line. activeFlows: 0, alertsToday: 0,
detectionRate: 0,` detectionRate: 0,
136 ` topThreatIp: '', deltaActiveFlows: 0, Source code line. topThreatIp: '', deltaActiveFlows: 0,
deltaAlertsToday: 0,` deltaAlertsToday: 0,
137 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
138 `` Blank line for Separator between code blocks.
readability.
139 ` function handleTimelineClick(label: Source code line. function handleTimelineClick(label:
string) {` string) {
140 ` setAnomalyFilter(label, null);` Executable setAnomalyFilter(label, null);
statement.
141 ` setLocation('/alerts');` Executable setLocation('/alerts');
statement.
142 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
143 `` Blank line for Separator between code blocks.
readability.
144 ` function handleProtocolClick(protocol: Source code line. function handleProtocolClick(protocol:
string) {` string) {
145 ` setAnomalyFilter(null, protocol);` Executable setAnomalyFilter(null, protocol);
statement.
146 ` setLocation('/alerts');` Executable setLocation('/alerts');
statement.
147 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
148 `` Blank line for Separator between code blocks.
readability.
149 ` const StatCard = ({ title, value, delta, Named constant — const StatCard = ({ title, value, delta,
isGood, suffix }: {` value should not isGood, suffix }: {
change.

Page 496 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
150 ` title: string; value: string \ number; delta?: Executable statement.
number; isGood?:
boolean; suffix?:
string;`
151 ` }) => (` Source code line. }) => (
152 ` <div className="bg-[var(--bg-base)] Source code line. <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] border border-[var(--border-default)]
rounded p-4 flex flex-col">` rounded p-4 flex flex-col"
153 ` <span className="text-[var(--text- Source code line. <span className="text-[var(--text-
muted)] font-mono text-[9px] uppercase muted)] font-mono text-[9px] uppercase
tracking-wider mb-2">{title}</span>` tracking-wider mb-2">{title
154 ` <div className="flex items-end gap- Source code line. <div className="flex items-end gap-
2">` 2">
155 ` <span className="text-2xl font- Source code line. <span className="text-2xl font-bold
bold font-space text-[var(--text- font-space text-[var(--text-
primary)]">{value}</span>` primary)]">{value}</span>
156 ` {suffix && <span className="text- Source code line. {suffix && <span className="text-
[var(--text-secondary)] text-sm mb- [var(--text-secondary)] text-sm mb-
0.5">{suffix}</span>}` 0.5">{suffix}</span>}
157 ` {delta !== undefined && delta !== 0 Source code line. {delta !== undefined && delta !== 0 &&
&& (` (
158 ` <span className={`text-xs font- Source code line. <span className={`text-xs font-bold
bold flex items-center mb-0.5 ${isGood ? flex items-center mb-0.5 ${isGood ?
'text-[var(--normal)]' : 'text-[var...` 'text-[var(--normal)]' : 'te
159 ` {isGood ? <ArrowDownRight Source code line. {isGood ? <ArrowDownRight
className="w-3 h-3" /> : <ArrowUpRight className="w-3 h-3" /> :
className="w-3 h-3" />}` <ArrowUpRight className="w-3 h-3"
/>}
160 ` {[Link](delta)}` Source code line. {[Link](delta)}

Lin Source Easy Technical Explanation


e Explanatio
n
161 ` </span>` Source code </span>
line.
162 ` )}` Source code )}
line.
163 ` </div>` Source code </div>
line.
164 ` </div>` Source code </div>
line.
165 ` );` Executable );
statement.
166 `` Blank line for Separator between code blocks.
readability.
167 ` return (` Exit function return (
and give
back a
value.

Page 497 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
168 ` <div className="h-full flex flex-col bg-[var(-- Source code <div className="h-full flex flex-col bg-[var(--bg-
bg-void)] text-[var(--text-primary)] overflow-auto line. void)] text-[var(--text-primary)] overflow-auto p-
p-5 gap-5">`
169 ` <div className="flex items-center gap-2">` Source code <div className="flex items-center gap-2">
line.
170 ` <Activity className="w-5 h-5 text-[var(-- Source code <Activity className="w-5 h-5 text-[var(--
accent)]" />` line. accent)]" />
171 ` <h1 className="text-base font-bold font- Source code <h1 className="text-base font-bold font-sans
sans text-[var(--text-primary)]">Anomaly line. text-[var(--text-primary)]">Anomaly
Dashboard</h1>` Dashboard</h1>
172 ` <span className="ml-auto text-[10px] font- Source code <span className="ml-auto text-[10px] font-
mono text-[var(--text-muted)]">Click any chart line. mono text-[var(--text-muted)]">Click any chart
element to drill int...` element to
173 ` </div>` Source code </div>
line.
174 `` Blank line for Separator between code blocks.
readability.
175 ` {/* Stat Cards */}` Source code {/* Stat Cards */}
line.
176 ` <div className="grid grid-cols-4 gap-4">` Source code <div className="grid grid-cols-4 gap-4">
line.
177 ` <StatCard title="Active Flows" Source code <StatCard title="Active Flows"
value={([Link] ?? line. value={([Link] ??
342).toLocaleString()} delta={summaryData.d...` 342).toLocaleString()} delta={summ
178 ` <StatCard title="Alerts Today" Source code <StatCard title="Alerts Today"
value={[Link] ?? 17} line. value={[Link] ?? 17}
delta={[Link]} isG...` delta={[Link]
179 ` <StatCard title="Top Threat IP" Source code <StatCard title="Top Threat IP"
value={[Link] ?? line. value={[Link] ??
'[Link]'} />` '[Link]'} />
180 ` <StatCard title="Detection Rate" Source code <StatCard title="Detection Rate"
value={[Link](([Link] line. value={[Link](([Link]
?? 0.94) * 100)} suffix="%" del...` ?? 0.94) * 100)} suffi
181 ` </div>` Source code </div>
line.
182 `` Blank line for Separator between code blocks.
readability.
183 ` <div className="grid grid-cols-3 gap-5">` Source code <div className="grid grid-cols-3 gap-5">
line.
184 ` {/* Threat Timeline */}` Source code {/* Threat Timeline */}
line.
185 ` <div className="col-span-2 bg-[var(--bg- Source code <div className="col-span-2 bg-[var(--bg-base)]
base)] border border-[var(--border-default)] line. border border-[var(--border-default)] rounded flex
rounded flex flex-col">` fl
186 ` <div className="px-4 py-2.5 border-b Source code <div className="px-4 py-2.5 border-b border-
border-[var(--border-subtle)] flex items-center line. [var(--border-subtle)] flex items-center justify-
justify-between">` between
187 ` <span className="font-mono text-xs Source code <span className="font-mono text-xs font-bold
font-bold text-[var(--text-secondary)]">Threat line. text-[var(--text-secondary)]">Threat Timeline
Timeline (Last 60m)</span>` (Last 60m

Page 498 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
188 ` <span className="text-[9px] font-mono Source code <span className="text-[9px] font-mono text-
text-[var(--text-muted)]">Click tooltip to filter line. [var(--text-muted)]">Click tooltip to filter
alerts</span>` alerts</span
189 ` </div>` Source code </div>
line.
190 ` <div className="p-4 h-[260px]">` Source code <div className="p-4 h-[260px]">
line.
191 ` <ResponsiveContainer width="100%" Source code <ResponsiveContainer width="100%"
height="100%">` line. height="100%">
192 ` <AreaChart data={timelineData} Source code <AreaChart data={timelineData} margin={{ top:
margin={{ top: 8, right: 8, left: -25, bottom: 0 }}>` line. 8, right: 8, left: -25, bottom: 0 }}>
193 ` <defs>` Source code <defs>
line.
194 ` Source code {[Link](SEVERITY_COLORS).map(([key
{[Link](SEVERITY_COLORS).map(([key, line. , color]) => (
color]) => (`
195 ` <linearGradient key={key} Source code <linearGradient key={key} id={`grad-${key}`}
id={`grad-${key}`} x1="0" y1="0" x2="0" y2="1">` line. x1="0" y1="0" x2="0" y2="1">
196 ` <stop offset="5%" Source code <stop offset="5%" stopColor={color}
stopColor={color} stopOpacity={0.6} />` line. stopOpacity={0.6} />
197 ` <stop offset="95%" Source code <stop offset="95%" stopColor={color}
stopColor={color} stopOpacity={0.05} />` line. stopOpacity={0.05} />
198 ` </linearGradient>` Source code </linearGradient>
line.
199 ` ))}` Source code ))}
line.
200 ` </defs>` Source code </defs>
line.
201 ` <CartesianGrid strokeDasharray="3 3" Source code <CartesianGrid strokeDasharray="3 3"
stroke="var(--border-subtle)" vertical={false} />` line. stroke="var(--border-subtle)" vertical={false} />
202 ` <XAxis dataKey="time" stroke="var(-- Source code <XAxis dataKey="time" stroke="var(--text-
text-muted)" tick={{ fontSize: 9, fontFamily: line. muted)" tick={{ fontSize: 9, fontFamily:
'monospace' }}` 'monospace' }}
203 ` interval={9} />` Source code interval={9} />
line.
204 ` <YAxis stroke="var(--text-muted)" Source code <YAxis stroke="var(--text-muted)" tick={{
tick={{ fontSize: 9, fontFamily: 'monospace' }} />` line. fontSize: 9, fontFamily: 'monospace' }} />
205 ` <RechartsTooltip` Source code <RechartsTooltip
line.
206 ` content={(props) => (` Source code content={(props) => (
line.
207 ` <CustomTimelineTooltip {...props} Source code <CustomTimelineTooltip {...props}
onClickFilter={handleTimelineClick} />` line. onClickFilter={handleTimelineClick} />
208 ` )}` Source code )}
line.
209 ` />` Source code />
line.

Page 499 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
210 ` {(['low', 'medium', 'high', 'critical'] as Source code {(['low', 'medium', 'high', 'critical'] as
const).map((key) => (` line. const).map((key) => (
211 ` <Area key={key} type="monotone" Source code <Area key={key} type="monotone"
dataKey={key} stackId="1"` line. dataKey={key} stackId="1"
212 ` stroke={SEVERITY_COLORS[key]} Source code stroke={SEVERITY_COLORS[key]}
fill={`url(#grad-${key})`}` line. fill={`url(#grad-${key})`}
213 ` strokeWidth={1.5} />` Source code strokeWidth={1.5} />
line.
214 ` ))}` Source code ))}
line.
215 ` </AreaChart>` Source code </AreaChart>
line.
216 ` </ResponsiveContainer>` Source code </ResponsiveContainer>
line.
217 ` </div>` Source code </div>
line.
218 ` </div>` Source code </div>
line.
219 `` Blank line for Separator between code blocks.
readability.
220 ` {/* Protocol Anomaly Donut */}` Source code {/* Protocol Anomaly Donut */}
line.
221 ` <div className="bg-[var(--bg-base)] Source code <div className="bg-[var(--bg-base)] border
border border-[var(--border-default)] rounded flex line. border-[var(--border-default)] rounded flex flex-
flex-col">` col">
222 ` <div className="px-4 py-2.5 border-b Source code <div className="px-4 py-2.5 border-b border-
border-[var(--border-subtle)] flex items-center line. [var(--border-subtle)] flex items-center justify-
justify-between">` between
223 ` <span className="font-mono text-xs Source code <span className="font-mono text-xs font-bold
font-bold text-[var(--text-secondary)]">Protocol line. text-[var(--text-secondary)]">Protocol
Anomalies</span>` Anomalies</span>
224 ` </div>` Source code </div>
line.
225 ` <div className="flex-1 flex flex-col items- Source code <div className="flex-1 flex flex-col items-center
center justify-center relative p-4">` line. justify-center relative p-4">
226 ` <ResponsiveContainer width="100%" Source code <ResponsiveContainer width="100%"
height={200}>` line. height={200}>
227 ` <PieChart onClick={(data) => {` Source code <PieChart onClick={(data) => {
line.
228 ` if Conditional if (data?.activePayload?.[0]?.payload?.name) {
(data?.activePayload?.[0]?.payload?.name) {` branch —
run code
only when
condition
true.
229 ` Executable handleProtocolClick([Link][0].paylo
handleProtocolClick([Link][0].payloa statement. [Link]);
[Link]);`

Page 500 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
230 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/open
ing a block.
231 ` }}>` Source code }}>
line.
232 ` <Pie data={protocolData} cx="50%" Source code <Pie data={protocolData} cx="50%" cy="50%"
cy="50%" innerRadius={55} outerRadius={85}` line. innerRadius={55} outerRadius={85}
233 ` paddingAngle={2} dataKey="value" Source code paddingAngle={2} dataKey="value"
stroke="none" style={{ cursor: 'pointer' }}>` line. stroke="none" style={{ cursor: 'pointer' }}>
234 ` {[Link]((entry, i) => (` Source code {[Link]((entry, i) => (
line.
235 ` <Cell key={i} fill={[Link]} />` Source code <Cell key={i} fill={[Link]} />
line.
236 ` ))}` Source code ))}
line.
237 ` </Pie>` Source code </Pie>
line.
238 ` <RechartsTooltip` Source code <RechartsTooltip
line.
239 ` content={(props) => (` Source code content={(props) => (
line.
240 ` <CustomDonutTooltip {...props} Source code <CustomDonutTooltip {...props}
onClickFilter={handleProtocolClick} />` line. onClickFilter={handleProtocolClick} />

Line Source Easy Technical Explanation


Explanation
241 ` )}` Source code line. )}
242 ` />` Source code line. />
243 ` </PieChart>` Source code line. </PieChart>
244 ` </ResponsiveContainer>` Source code line. </ResponsiveContainer>
245 ` <div className="absolute inset-0 Source code line. <div className="absolute inset-0 flex
flex items-center justify-center pointer- items-center justify-center pointer-
events-none">` events-none">
246 ` <div className="text-center">` Source code line. <div className="text-center">
247 ` <div className="font-space Source code line. <div className="font-space font-bold
font-bold text-xl text-[var(--text-primary)]">` text-xl text-[var(--text-primary)]">
248 ` {(totalProtoAnomalies / Source code line. {(totalProtoAnomalies /
1000).toFixed(1)}k` 1000).toFixed(1)}k
249 ` </div>` Source code line. </div>
250 ` <div className="text-[9px] Source code line. <div className="text-[9px] font-mono
font-mono text-[var(--text-muted)] text-[var(--text-muted)] uppercase
uppercase tracking- tracking-wider">anomalies</d
wider">anomalies</div>`
251 ` </div>` Source code line. </div>
252 ` </div>` Source code line. </div>

Page 501 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
253 ` <div className="flex flex-wrap Source code line. <div className="flex flex-wrap gap-x-3
gap-x-3 gap-y-1 justify-center mt-2">` gap-y-1 justify-center mt-2">
254 ` {[Link]((p) => (` Source code line. {[Link]((p) => (
255 ` <button key={[Link]} Source code line. <button key={[Link]} onClick={() =>
onClick={() => handleProtocolClick([Link])}
handleProtocolClick([Link])}`
256 ` className="flex items-center Source code line. className="flex items-center gap-1
gap-1 text-[9px] font-mono text-[var(--text- text-[9px] font-mono text-[var(--text-
secondary)] hover:text-[va...` secondary)] hover:text-[var
257 ` <div className="w-2 h-2 Source code line. <div className="w-2 h-2 rounded-sm"
rounded-sm" style={{ backgroundColor: style={{ backgroundColor: [Link] }} />
[Link] }} />`
258 ` {[Link]}` Source code line. {[Link]}
259 ` </button>` Source code line. </button>
260 ` ))}` Source code line. ))}
261 ` </div>` Source code line. </div>
262 ` </div>` Source code line. </div>
263 ` </div>` Source code line. </div>
264 ` </div>` Source code line. </div>
265 `` Blank line for Separator between code blocks.
readability.
266 ` <div className="grid grid-cols-2 gap- Source code line. <div className="grid grid-cols-2 gap-5
5 pb-6">` pb-6">
267 ` {/* Top Threat IPs */}` Source code line. {/* Top Threat IPs */}
268 ` <div className="bg-[var(--bg-base)] Source code line. <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] border border-[var(--border-default)]
rounded flex flex-col">` rounded flex flex-col">
269 ` <div className="px-4 py-2.5 Source code line. <div className="px-4 py-2.5 border-b
border-b border-[var(--border-subtle)] font- border-[var(--border-subtle)] font-mono
mono text-xs font-bold text-[var(--...` text-xs font-bold text-
270 ` Top Threat IPs` Source code line. Top Threat IPs
271 ` </div>` Source code line. </div>
272 ` <table className="w-full text-xs">` Source code line. <table className="w-full text-xs">
273 ` <thead className="bg-[var(--bg- Source code line. <thead className="bg-[var(--bg-
overlay)] border-b border-[var(--border- overlay)] border-b border-[var(--border-
subtle)] text-[9px] text-[var(--te...` subtle)] text-[9px] text-[var
274 ` <tr>` Source code line. <tr>
275 ` <th className="px-4 py-2 w-8 Source code line. <th className="px-4 py-2 w-8 text-
text-left">#</th>` left">#</th>
276 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-left">IP
left">IP Address</th>` Address</th>
277 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Country</th>` left">Country</th>
278 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Alerts</th>` left">Alerts</th>
279 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-left w-
left w-1/3">Score</th>` 1/3">Score</th>

Page 502 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
280 ` </tr>` Source code line. </tr>
281 ` </thead>` Source code line. </thead>
282 ` <tbody>` Source code line. <tbody>
283 ` {[Link]((ip, i) => (` Source code line. {[Link]((ip, i) => (
284 ` <tr key={i} className="border- Source code line. <tr key={i} className="border-b
b border-[var(--border-subtle)] hover:bg- border-[var(--border-subtle)] hover:bg-
[var(--bg-hover)] cursor-pointer"` [var(--bg-hover)] cursor-poin
285 ` onClick={() => Source code line. onClick={() => handleProtocolClick('Port
handleProtocolClick('Port Scan')}>` Scan')}>
286 ` <td className="px-4 py-2 Source code line. <td className="px-4 py-2 font-mono
font-mono text-[var(--text-muted)]">{i + text-[var(--text-muted)]">{i + 1}</td>
1}</td>`
287 ` <td className="px-4 py-2 Source code line. <td className="px-4 py-2 font-mono
font-mono font-bold text-[var(-- font-bold text-[var(--
accent)]">{[Link]}</td>` accent)]">{[Link]}</td>
288 ` <td className="px-4 py-2 Source code line. <td className="px-4 py-2 text-[var(--
text-[var(--text-secondary)] text- text-secondary)] text-
[10px]">{[Link]}</td>` [10px]">{[Link]}</td>
289 ` <td className="px-4 py-2 Source code line. <td className="px-4 py-2 font-bold"
font-bold" style={{ color: 'var(--critical)' style={{ color: 'var(--critical)'
}}>{[Link]}</td>` }}>{[Link]}</td>
290 ` <td className="px-4 py-2">` Source code line. <td className="px-4 py-2">
291 ` <div className="h-1.5 w-full Source code line. <div className="h-1.5 w-full bg-[var(--
bg-[var(--bg-overlay)] rounded-full bg-overlay)] rounded-full overflow-
overflow-hidden">` hidden">
292 ` <div className="h-full bg- Source code line. <div className="h-full bg-gradient-to-r
gradient-to-r from-[var(--high)] to-[var(-- from-[var(--high)] to-[var(--critical)]
critical)] rounded-full"` rounded-full"
293 ` style={{ width: Source code line. style={{ width:
`${[Link]([Link] * 100)}%` }} `${[Link]([Link] * 100)}%`
/>` }} />
294 ` </div>` Source code line. </div>
295 ` </td>` Source code line. </td>
296 ` </tr>` Source code line. </tr>
297 ` ))}` Source code line. ))}
298 ` </tbody>` Source code line. </tbody>
299 ` </table>` Source code line. </table>
300 ` </div>` Source code line. </div>
301 `` Blank line for Separator between code blocks.
readability.
302 ` {/* Active Threat Flows */}` Source code line. {/* Active Threat Flows */}
303 ` <div className="bg-[var(--bg-base)] Source code line. <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] border border-[var(--border-default)]
rounded flex flex-col">` rounded flex flex-col">
304 ` <div className="px-4 py-2.5 Source code line. <div className="px-4 py-2.5 border-b
border-b border-[var(--border-subtle)] font- border-[var(--border-subtle)] font-mono
mono text-xs font-bold text-[var(--...` text-xs font-bold text-

Page 503 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
305 ` Active Threat Flows` Source code line. Active Threat Flows
306 ` </div>` Source code line. </div>
307 ` <table className="w-full text-xs">` Source code line. <table className="w-full text-xs">
308 ` <thead className="bg-[var(--bg- Source code line. <thead className="bg-[var(--bg-
overlay)] border-b border-[var(--border- overlay)] border-b border-[var(--border-
subtle)] text-[9px] text-[var(--te...` subtle)] text-[9px] text-[var
309 ` <tr>` Source code line. <tr>
310 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Flow</th>` left">Flow</th>
311 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Proto</th>` left">Proto</th>
312 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Score</th>` left">Score</th>
313 ` <th className="px-4 py-2 text- Source code line. <th className="px-4 py-2 text-
left">Status</th>` left">Status</th>
314 ` </tr>` Source code line. </tr>
315 ` </thead>` Source code line. </thead>
316 ` <tbody>` Source code line. <tbody>
317 ` {[Link]((flow, i) => {` Source code line. {[Link]((flow, i) => {
318 ` const score = Named constant const score =
[Link]([Link] * 100);` — value should [Link]([Link] * 100);
not change.
319 ` const scoreColor = score > 80 ? Named constant const scoreColor = score > 80 ? 'var(--
'var(--critical)' : score > 60 ? 'var(--high)' : — value should critical)' : score > 60 ? 'var(--high)' :
'var(--medium)';` not change.
320 ` return (` Exit function and return (
give back a value.

Lin Source Easy Technical Explanation


e Explanation
321 ` <tr key={i} className="border-b Source code <tr key={i} className="border-b border-[var(--
border-[var(--border-subtle)] hover:bg-[var(--bg- line. border-subtle)] hover:bg-[var(--bg-hover)]
hover)] cursor-poi...` cursor-poin
322 ` onClick={() => Source code onClick={() => setLocation('/flows')}>
setLocation('/flows')}>` line.
323 ` <td className="px-4 py-2 font- Source code <td className="px-4 py-2 font-mono text-
mono text-[10px]">` line. [10px]">
324 ` <div className="text-[var(--text- Source code <div className="text-[var(--text-
secondary)]">{[Link]}:{[Link]}</div> line. secondary)]">{[Link]}:{[Link]}</div
` >
325 ` <div className="text-[var(-- Source code <div className="text-[var(--
accent)]">{[Link]}:{[Link]}</div>` line. accent)]">{[Link]}:{[Link]}</div>
326 ` </td>` Source code </td>
line.
327 ` <td className="px-4 py-2 font- Source code <td className="px-4 py-2 font-mono text-
mono text-[var(--text- line. [var(--text-secondary)]">{[Link]}</td>
secondary)]">{[Link]}</td>`

Page 504 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
328 ` <td className="px-4 py-2">` Source code <td className="px-4 py-2">
line.
329 ` <span className="px-1.5 py-0.5 Source code <span className="px-1.5 py-0.5 rounded text-
rounded text-[9px] font-bold text-[var(--bg-void)] line. [9px] font-bold text-[var(--bg-void)] font-mono"
font-mono"`
330 ` style={{ backgroundColor: Source code style={{ backgroundColor: scoreColor }}>
scoreColor }}>` line.
331 ` {score}` Source code {score}
line.
332 ` </span>` Source code </span>
line.
333 ` </td>` Source code </td>
line.
334 ` <td className="px-4 py-2">` Source code <td className="px-4 py-2">
line.
335 ` <div className="flex items- Source code <div className="flex items-center gap-1.5">
center gap-1.5">` line.
336 ` <div className="w-1.5 h-1.5 Source code <div className="w-1.5 h-1.5 rounded-full
rounded-full animate-pulse" style={{ line. animate-pulse" style={{ backgroundColor:
backgroundColor: scoreColor ...` scoreColor }} />
337 ` <span className="text-[9px] Source code <span className="text-[9px] uppercase
uppercase tracking-wider font-mono text-[var(-- line. tracking-wider font-mono text-[var(--text-
text-muted)]">` muted)]">
338 ` {[Link]}` Source code {[Link]}
line.
339 ` </span>` Source code </span>
line.
340 ` </div>` Source code </div>
line.
341 ` </td>` Source code </td>
line.
342 ` </tr>` Source code </tr>
line.
343 ` );` Executable );
statement.
344 ` })}` Source code })}
line.
345 ` </tbody>` Source code </tbody>
line.
346 ` </table>` Source code </table>
line.
347 ` </div>` Source code </div>
line.
348 ` </div>` Source code </div>
line.
349 ` </div>` Source code </div>
line.
350 ` );` Executable );
statement.

Page 505 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
351 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

File: webwireshark/src/pages/[Link]
Total lines: 613

Line Source Easy Technical Explanation


Explanation
1 `import { useState, useEffect, useMemo, Executable import { useState, useEffect, useMemo,
useRef, useCallback } from 'react';` statement. useRef, useCallback } from 'react';
2 `import {` Source code line. import {
3 ` ResizableHandle,` Source code line. ResizableHandle,
4 ` ResizablePanel,` Source code line. ResizablePanel,
5 ` ResizablePanelGroup,` Source code line. ResizablePanelGroup,
6 `} from "@/components/ui/resizable";` Executable } from "@/components/ui/resizable";
statement.
7 `import { Button } from Executable import { Button } from
"@/components/ui/button";` statement. "@/components/ui/button";
8 `import { Play, Square, Pause, Executable import { Play, Square, Pause,
ShieldCheck, Filter, ChevronRight, statement. ShieldCheck, Filter, ChevronRight,
ChevronDown, Search, ArrowUpDown, ChevronDown, Search, ArrowUpDown, A
ArrowUp, ArrowDown...`
9 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
10 `import { FixedSizeList as List } from Executable import { FixedSizeList as List } from
'react-window';` statement. 'react-window';
11 `import {` Source code line. import {
12 ` useGetPackets,` Source code line. useGetPackets,
13 ` startCapture, stopCapture, Source code line. startCapture, stopCapture,
pauseCapture, resumeCapture,` pauseCapture, resumeCapture,
14 `} from '@workspace/api-client-react';` Executable } from '@workspace/api-client-react';
statement.
15 `import type { Packet, ProtocolLayer } from Executable import type { Packet, ProtocolLayer }
'@workspace/api-client-react';` statement. from '@workspace/api-client-react';
16 `import {` Source code line. import {
17 ` ContextMenu, ContextMenuContent, Source code line. ContextMenu, ContextMenuContent,
ContextMenuItem,` ContextMenuItem,
18 ` ContextMenuTrigger, Source code line. ContextMenuTrigger,
ContextMenuSeparator, ContextMenuSeparator,
ContextMenuSub,` ContextMenuSub,
19 ` ContextMenuSubContent, Source code line. ContextMenuSubContent,
ContextMenuSubTrigger,` ContextMenuSubTrigger,

Page 506 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
20 `} from "@/components/ui/context-menu";` Executable } from "@/components/ui/context-menu";
statement.
21 `import { useToast } from '@/hooks/use- Executable import { useToast } from '@/hooks/use-
toast';` statement. toast';
22 `` Blank line for Separator between code blocks.
readability.
23 `const ROW_HEIGHT = 22;` Named constant const ROW_HEIGHT = 22;
— value should
not change.
24 `` Blank line for Separator between code blocks.
readability.
25 `type SortKey = 'no' \ 'time' \ 'src' \
26 `type SortDir = 'asc' \ 'desc' \ null;`
27 `` Blank line for Separator between code blocks.
readability.
28 `const ProtocolLayerNode = ({ layer }: { Named constant const ProtocolLayerNode = ({ layer }: {
layer: ProtocolLayer }) => {` — value should layer: ProtocolLayer }) => {
not change.
29 ` const [expanded, setExpanded] = Named constant const [expanded, setExpanded] =
useState(true);` — value should useState(true);
not change.
30 ` return (` Exit function and return (
give back a
value.
31 ` <div className="flex flex-col font- Source code line. <div className="flex flex-col font-mono
mono text-[10px]">` text-[10px]">
32 ` <div` Source code line. <div
33 ` className="flex items-center gap-1 Source code line. className="flex items-center gap-1
cursor-pointer hover:bg-[var(--bg-hover)] cursor-pointer hover:bg-[var(--bg-hover)]
py-0.5 px-1 rounded -ml-1"` py-0.5 px-1 rounded -ml
34 ` onClick={() => Source code line. onClick={() => setExpanded(!expanded)}
setExpanded(!expanded)}`
35 ` >` Source code line. >
36 ` {expanded` Source code line. {expanded
37 ` ? <ChevronDown className="w- Source code line. ? <ChevronDown className="w-2.5 h-
2.5 h-2.5 text-[var(--text-muted)] shrink-0" 2.5 text-[var(--text-muted)] shrink-0" />
/>`
38 ` : <ChevronRight className="w- Source code line. : <ChevronRight className="w-2.5 h-
2.5 h-2.5 text-[var(--text-muted)] shrink-0" 2.5 text-[var(--text-muted)] shrink-0" />}
/>}`
39 ` <span className="font-bold text- Source code line. <span className="font-bold text-[var(--
[var(--accent)]">{[Link]}</span>` accent)]">{[Link]}</span>
40 ` </div>` Source code line. </div>
41 ` {expanded && (` Source code line. {expanded && (
42 ` <div className="ml-3 flex flex-col Source code line. <div className="ml-3 flex flex-col
border-l border-[var(--border-subtle)] pl- border-l border-[var(--border-subtle)] pl-
2">` 2">
43 ` {[Link]((field, idx) => (` Source code line. {[Link]((field, idx) => (

Page 507 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
44 ` <div key={idx}` Source code line. <div key={idx}
45 ` className="flex gap-1.5 py-0.5 Source code line. className="flex gap-1.5 py-0.5
hover:bg-[var(--bg-hover)] px-1 rounded - hover:bg-[var(--bg-hover)] px-1 rounded -
ml-1 cursor-default group">` ml-1 cursor-default group">
46 ` <span className="text-[var(-- Source code line. <span className="text-[var(--text-
text-secondary)] shrink- secondary)] shrink-
0">{[Link]}:</span>` 0">{[Link]}:</span>
47 ` <span className="text-[var(-- Source code line. <span className="text-[var(--text-
text-primary)] break- primary)] break-all">{[Link]}</span>
all">{[Link]}</span>`
48 ` {[Link] != null && (` Source code line. {[Link] != null && (
49 ` <span className="ml-auto Source code line. <span className="ml-auto text-[var(--
text-[var(--text-muted)] shrink-0 opacity-0 text-muted)] shrink-0 opacity-0 group-
group-hover:opacity-100 text-[9p...` hover:opacity-100 text-[9
50 ` Source code line. @{[Link](16).padStart(4,
@{[Link](16).padStart(4, '0')} '0')} +{[Link]}
+{[Link]}`
51 ` </span>` Source code line. </span>
52 ` )}` Source code line. )}
53 ` </div>` Source code line. </div>
54 ` ))}` Source code line. ))}
55 ` </div>` Source code line. </div>
56 ` )}` Source code line. )}
57 ` </div>` Source code line. </div>
58 ` );` Executable );
statement.
59 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
60 `` Blank line for Separator between code blocks.
readability.
61 `const ProtocolTree = ({ layers }: { layers: Named constant const ProtocolTree = ({ layers }: { layers:
ProtocolLayer[] }) => {` — value should ProtocolLayer[] }) => {
not change.
62 ` if (![Link]) return (` Conditional if (![Link]) return (
branch — run
code only when
condition true.
63 ` <div className="p-3 text-[var(--text- Source code line. <div className="p-3 text-[var(--text-
muted)] font-mono text-[10px]">No muted)] font-mono text-[10px]">No
protocol details available.</div>` protocol details available.</
64 ` );` Executable );
statement.
65 ` return (` Exit function and return (
give back a
value.
66 ` <div className="flex flex-col gap-0.5 Source code line. <div className="flex flex-col gap-0.5 p-
p-2">` 2">

Page 508 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
67 ` {[Link]((layer, idx) => Source code line. {[Link]((layer, idx) =>
<ProtocolLayerNode key={idx} <ProtocolLayerNode key={idx}
layer={layer} />)}` layer={layer} />)}
68 ` </div>` Source code line. </div>
69 ` );` Executable );
statement.
70 `};` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
71 `` Blank line for Separator between code blocks.
readability.
72 `const HexViewer = ({ hex, packet }: { hex: null }) => {` Named constant — value should not
string; packet: Packet \ change.
73 ` const bytes = useMemo(() => {` Named constant const bytes = useMemo(() => {
— value should
not change.
74 ` if (!hex) return [];` Conditional if (!hex) return [];
branch — run
code only when
condition true.
75 ` const chunks: string[] = [];` Named constant const chunks: string[] = [];
— value should
not change.
76 ` for (let i = 0; i < [Link]; i += 2) Loop over items for (let i = 0; i < [Link]; i += 2)
[Link]([Link](i, i + 2));` or until condition [Link]([Link](i, i + 2));
changes.
77 ` return chunks;` Exit function and return chunks;
give back a
value.
78 ` }, [hex]);` Executable }, [hex]);
statement.
79 `` Blank line for Separator between code blocks.
readability.
80 ` const rows = useMemo(() => {` Named constant const rows = useMemo(() => {
— value should
not change.

Line Source Easy Explanation Technical Explanation


81 ` const r = [];` Named constant — const r = [];
value should not
change.
82 ` for (let i = 0; i < [Link]; i += 16) Loop over items or for (let i = 0; i < [Link]; i += 16) {
{` until condition
changes.
83 ` [Link]({` Source code line. [Link]({
84 ` offset: [Link](16).padStart(4, Source code line. offset: [Link](16).padStart(4, '0'),
'0'),`
85 ` hex: [Link](i, i + 16),` Source code line. hex: [Link](i, i + 16),

Page 509 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


86 ` ascii: [Link](i, i + 16).map(b => Source code line. ascii: [Link](i, i + 16).map(b => {
{`
87 ` const c = parseInt(b, 16);` Named constant — const c = parseInt(b, 16);
value should not
change.
88 ` return (c >= 32 && c <= 126) ? Exit function and give return (c >= 32 && c <= 126) ?
[Link](c) : '.';` back a value. [Link](c) : '.';
89 ` }).join(''),` Source code line. }).join(''),
90 ` });` Executable });
statement.
91 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
92 ` return r;` Exit function and give return r;
back a value.
93 ` }, [bytes]);` Executable }, [bytes]);
statement.
94 `` Blank line for Separator between code blocks.
readability.
95 ` if (!packet) return (` Conditional branch if (!packet) return (
— run code only
when condition true.
96 ` <div className="p-4 text-[var(--text- Source code line. <div className="p-4 text-[var(--text-
muted)] font-mono text-[10px]">Select a muted)] font-mono text-[10px]">Select
packet to view hex data.</div>` a packet to view hex data
97 ` );` Executable );
statement.
98 `` Blank line for Separator between code blocks.
readability.
99 ` const displayRows = [Link] > 0 ? Named constant — const displayRows = [Link] > 0 ?
rows : (() => {` value should not rows : (() => {
change.
100 ` // Build placeholder rows from packet Comment Build placeholder rows from packet
length when no real hex` documenting intent. length when no real hex
101 ` const len = [Link]([Link], Named constant — const len = [Link]([Link],
256);` value should not 256);
change.
102 ` const fakeRows = [];` Named constant — const fakeRows = [];
value should not
change.
103 ` for (let i = 0; i < len; i += 16) {` Loop over items or for (let i = 0; i < len; i += 16) {
until condition
changes.
104 ` const rowBytes = [Link]({ Named constant — const rowBytes = [Link]({ length:
length: [Link](16, len - i) }, (_, j) =>` value should not [Link](16, len - i) }, (_, j) =>
change.
105 ` ((i + j) % Source code line. ((i + j) % 256).toString(16).padStart(2,
256).toString(16).padStart(2, '0')` '0')
106 ` );` Executable );
statement.
107 ` [Link]({` Source code line. [Link]({

Page 510 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


108 ` offset: [Link](16).padStart(4, Source code line. offset: [Link](16).padStart(4, '0'),
'0'),`
109 ` hex: rowBytes,` Source code line. hex: rowBytes,
110 ` ascii: [Link](b => {` Source code line. ascii: [Link](b => {
111 ` const c = parseInt(b, 16);` Named constant — const c = parseInt(b, 16);
value should not
change.
112 ` return (c >= 32 && c <= 126) ? Exit function and give return (c >= 32 && c <= 126) ?
[Link](c) : '.';` back a value. [Link](c) : '.';
113 ` }).join(''),` Source code line. }).join(''),
114 ` });` Executable });
statement.
115 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
116 ` return fakeRows;` Exit function and give return fakeRows;
back a value.
117 ` })();` Executable })();
statement.
118 `` Blank line for Separator between code blocks.
readability.
119 ` const isReal = [Link] > 0;` Named constant — const isReal = [Link] > 0;
value should not
change.
120 `` Blank line for Separator between code blocks.
readability.
121 ` return (` Exit function and give return (
back a value.
122 ` <div className="font-mono text- Source code line. <div className="font-mono text-
[10px] p-2 overflow-auto h-full">` [10px] p-2 overflow-auto h-full">
123 ` {!isReal && (` Source code line. {!isReal && (
124 ` <div className="text-[var(--text- Source code line. <div className="text-[var(--text-
muted)] px-2 pb-1 text-[9px] italic">` muted)] px-2 pb-1 text-[9px] italic">
125 ` hex not available · {[Link]} Source code line. hex not available · {[Link]}
bytes · {[Link]}` bytes · {[Link]}
126 ` </div>` Source code line. </div>
127 ` )}` Source code line. )}
128 ` {[Link]((row, idx) => (` Source code line. {[Link]((row, idx) => (
129 ` <div key={idx} className="flex Source code line. <div key={idx} className="flex gap-3
gap-3 hover:bg-[var(--bg-hover)] px-2 py- hover:bg-[var(--bg-hover)] px-2 py-px
px rounded">` rounded">
130 ` <span className="text-[var(-- Source code line. <span className="text-[var(--text-
text-muted)] select-none w-10 shrink- muted)] select-none w-10 shrink-
0">{[Link]}</span>` 0">{[Link]}</span>
131 ` <span className="text-[var(-- Source code line. <span className="text-[var(--text-
text-primary)] w-[38ch] shrink-0">` primary)] w-[38ch] shrink-0">
132 ` {[Link]((h, i) => (` Source code line. {[Link]((h, i) => (
133 ` <span key={i}` Source code line. <span key={i}

Page 511 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


134 ` className="hover:bg-[var(-- Source code line. className="hover:bg-[var(--accent)]
accent)] hover:text-[var(--bg-void)] hover:text-[var(--bg-void)] cursor-
cursor-pointer px-px rounded-sm mr- pointer px-px rounded-sm mr-p
px...`
135 ` {h}` Source code line. {h}
136 ` </span>` Source code line. </span>
137 ` ))}` Source code line. ))}
138 ` </span>` Source code line. </span>
139 ` <span className="text-[var(-- Source code line. <span className="text-[var(--text-
text-muted)] tracking- muted)] tracking-
widest">{[Link]}</span>` widest">{[Link]}</span>
140 ` </div>` Source code line. </div>
141 ` ))}` Source code line. ))}
142 ` </div>` Source code line. </div>
143 ` );` Executable );
statement.
144 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
145 `` Blank line for Separator between code blocks.
readability.
146 `function getRowBg(proto: string) {` Source code line. function getRowBg(proto: string) {
147 ` const p = [Link]();` Named constant — const p = [Link]();
value should not
change.
148 ` if ([Link]('dns')) return 'var(--proto- Conditional branch if ([Link]('dns')) return 'var(--proto-
dns)';` — run code only dns)';
when condition true.
149 ` if ([Link]('tls')) return 'var(--proto- Conditional branch if ([Link]('tls')) return 'var(--proto-
tls)';` — run code only tls)';
when condition true.
150 ` if ([Link]('http')) return 'var(--proto- Conditional branch if ([Link]('http')) return 'var(--proto-
http)';` — run code only http)';
when condition true.
151 ` if ([Link]('tcp')) return 'var(--proto- Conditional branch if ([Link]('tcp')) return 'var(--proto-
tcp)';` — run code only tcp)';
when condition true.
152 ` if ([Link]('udp')) return 'var(--proto- Conditional branch if ([Link]('udp')) return 'var(--proto-
udp)';` — run code only udp)';
when condition true.
153 ` if ([Link]('icmp')) return 'var(-- Conditional branch if ([Link]('icmp')) return 'var(--
proto-icmp)';` — run code only proto-icmp)';
when condition true.
154 ` if ([Link]('arp')) return 'var(--proto- Conditional branch if ([Link]('arp')) return 'var(--proto-
arp)';` — run code only arp)';
when condition true.
155 ` return 'var(--bg-base)';` Exit function and give return 'var(--bg-base)';
back a value.

Page 512 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


156 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
157 `` Blank line for Separator between code blocks.
readability.
158 `// Left-edge accent stripe per protocol` Comment Left-edge accent stripe per protocol
documenting intent.
159 `function getRowStripe(proto: string) {` Source code line. function getRowStripe(proto: string) {
160 ` const p = [Link]();` Named constant — const p = [Link]();
value should not
change.

Lin Source Easy Technical Explanation


e Explanation
161 ` if ([Link]('dns')) return '#FFAB00';` Conditional if ([Link]('dns')) return '#FFAB00';
branch — run
code only
when condition
true.
162 ` if ([Link]('tls')) return '#CE93D8';` Conditional if ([Link]('tls')) return '#CE93D8';
branch — run
code only
when condition
true.
163 ` if ([Link]('http')) return '#69F0AE';` Conditional if ([Link]('http')) return '#69F0AE';
branch — run
code only
when condition
true.
164 ` if ([Link]('tcp')) return '#40C4FF';` Conditional if ([Link]('tcp')) return '#40C4FF';
branch — run
code only
when condition
true.
165 ` if ([Link]('udp')) return '#00E676';` Conditional if ([Link]('udp')) return '#00E676';
branch — run
code only
when condition
true.
166 ` if ([Link]('icmp')) return '#FF6E40';` Conditional if ([Link]('icmp')) return '#FF6E40';
branch — run
code only
when condition
true.
167 ` if ([Link]('arp')) return '#00B0FF';` Conditional if ([Link]('arp')) return '#00B0FF';
branch — run
code only
when condition
true.
168 ` return 'transparent';` Exit function return 'transparent';
and give back
a value.
169 `}` Brace or C/C++ syntax structure.
parenthesis

Page 513 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
closing/openin
g a block.
170 `` Blank line for Separator between code blocks.
readability.
171 `function SortIcon({ col, sortKey, sortDir }: { col: Source code function SortIcon({ col, sortKey, sortDir }: { col:
SortKey; sortKey: SortKey; sortDir: SortDir }) {` line. SortKey; sortKey: SortKey; sortDir: SortDir }) {
172 ` if (col !== sortKey) return <ArrowUpDown Conditional if (col !== sortKey) return <ArrowUpDown
className="w-2.5 h-2.5 opacity-30" />;` branch — run className="w-2.5 h-2.5 opacity-30" />;
code only
when condition
true.
173 ` if (sortDir === 'asc') return <ArrowUp Conditional if (sortDir === 'asc') return <ArrowUp
className="w-2.5 h-2.5 text-[var(--accent)]" />;` branch — run className="w-2.5 h-2.5 text-[var(--accent
code only
when condition
true.
174 ` return <ArrowDown className="w-2.5 h-2.5 Exit function return <ArrowDown className="w-2.5 h-2.5
text-[var(--accent)]" />;` and give back text-[var(--accent)]" />;
a value.
175 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
176 `` Blank line for Separator between code blocks.
readability.
177 `export default function Capture() {` Source code export default function Capture() {
line.
178 ` const {` Named const {
constant —
value should
not change.
179 ` captureState, setCaptureState,` Source code captureState, setCaptureState,
line.
180 ` selectedPacket, setSelectedPacket,` Source code selectedPacket, setSelectedPacket,
line.
181 ` packets: storePackets, setPackets, Source code packets: storePackets, setPackets,
clearPackets,` line. clearPackets,
182 ` displayFilter, setDisplayFilter,` Source code displayFilter, setDisplayFilter,
line.
183 ` captureInterface, captureFilter,` Source code captureInterface, captureFilter,
line.
184 ` scrollToNew,` Source code scrollToNew,
line.
185 ` } = useAppStore();` Executable } = useAppStore();
statement.
186 ` const [search, setSearch] = useState('');` Named const [search, setSearch] = useState('');
constant —
value should
not change.
187 ` const [localFilter, setLocalFilter] = Named const [localFilter, setLocalFilter] =
useState(displayFilter);` constant — useState(displayFilter);

Page 514 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
value should
not change.
188 ` const [sortKey, setSortKey] = Named const [sortKey, setSortKey] =
useState<SortKey>('no');` constant — useState<SortKey>('no');
value should
not change.
189 ` const [sortDir, setSortDir] = Named const [sortDir, setSortDir] =
useState<SortDir>('asc');` constant — useState<SortDir>('asc');
value should
not change.
190 ` const [listHeight, setListHeight] = Named const [listHeight, setListHeight] =
useState(400);` constant — useState(400);
value should
not change.
191 ` const listContainerRef = Named const listContainerRef =
useRef<HTMLDivElement>(null);` constant — useRef<HTMLDivElement>(null);
value should
not change.
192 ` const listRef = useRef<List>(null);` Named const listRef = useRef<List>(null);
constant —
value should
not change.
193 ` const { toast } = useToast();` Named const { toast } = useToast();
constant —
value should
not change.
194 `` Blank line for Separator between code blocks.
readability.
195 ` // Sync local filter → store` Comment Sync local filter → store
documenting
intent.
196 ` useEffect(() => { setLocalFilter(displayFilter); Executable useEffect(() => { setLocalFilter(displayFilter); },
}, [displayFilter]);` statement. [displayFilter]);
197 `` Blank line for Separator between code blocks.
readability.
198 ` const { data: apiPackets, isError: apiError } = Named const { data: apiPackets, isError: apiError } =
useGetPackets();` constant — useGetPackets();
value should
not change.
199 `` Blank line for Separator between code blocks.
readability.
200 ` // Merge new packets from API polling` Comment Merge new packets from API polling
documenting
intent.
201 ` useEffect(() => {` Source code useEffect(() => {
line.
202 ` if (apiPackets?.packets && Conditional if (apiPackets?.packets &&
[Link] > 0 && captureState branch — run [Link] > 0 && captureState
=== 'capturing') {` code only === 'ca
when condition
true.
203 ` setPackets([Link]);` Executable setPackets([Link]);
statement.

Page 515 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
204 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
205 ` }, [apiPackets, captureState, setPackets]);` Executable }, [apiPackets, captureState, setPackets]);
statement.
206 `` Blank line for Separator between code blocks.
readability.
207 ` // Capture state → backend` Comment Capture state → backend
documenting
intent.
208 ` useEffect(() => {` Source code useEffect(() => {
line.
209 ` if (captureState === 'capturing') {` Conditional if (captureState === 'capturing') {
branch — run
code only
when condition
true.
210 ` startCapture(captureInterface \ \ undefined, captureFilter \
211 ` } else if (captureState === 'stopped') {` Conditional } else if (captureState === 'stopped') {
branch — run
code only
when condition
true.
212 ` stopCapture().catch([Link]);` Executable stopCapture().catch([Link]);
statement.
213 ` } else if (captureState === 'paused') {` Conditional } else if (captureState === 'paused') {
branch — run
code only
when condition
true.
214 ` pauseCapture().catch([Link]);` Executable pauseCapture().catch([Link]);
statement.
215 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
216 ` }, [captureState, captureInterface, Executable }, [captureState, captureInterface,
captureFilter]);` statement. captureFilter]);
217 `` Blank line for Separator between code blocks.
readability.
218 ` // Auto-scroll to newest` Comment Auto-scroll to newest
documenting
intent.
219 ` useEffect(() => {` Source code useEffect(() => {
line.
220 ` if (scrollToNew && captureState === Conditional if (scrollToNew && captureState === 'capturing'
'capturing' && [Link] > 0) {` branch — run && [Link] > 0) {
code only
when condition
true.

Page 516 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
221 ` Executable [Link]?.scrollToItem([Link]
[Link]?.scrollToItem([Link] statement. h - 1, 'end');
h - 1, 'end');`
222 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
223 ` }, [[Link], captureState, Executable }, [[Link], captureState,
scrollToNew]);` statement. scrollToNew]);
224 `` Blank line for Separator between code blocks.
readability.
225 ` // Resize observer for list height` Comment Resize observer for list height
documenting
intent.
226 ` useEffect(() => {` Source code useEffect(() => {
line.
227 ` const el = [Link];` Named const el = [Link];
constant —
value should
not change.
228 ` if (!el) return;` Conditional if (!el) return;
branch — run
code only
when condition
true.
229 ` const ro = new ResizeObserver(entries => {` Named const ro = new ResizeObserver(entries => {
constant —
value should
not change.
230 ` for (const e of entries) Loop over for (const e of entries)
setListHeight([Link]);` items or until setListHeight([Link]);
condition
changes.
231 ` });` Executable });
statement.
232 ` [Link](el);` Executable [Link](el);
statement.
233 ` Executable setListHeight([Link]().height
setListHeight([Link]().height) statement. );
;`
234 ` return () => [Link]();` Exit function return () => [Link]();
and give back
a value.
235 ` }, []);` Executable }, []);
statement.
236 `` Blank line for Separator between code blocks.
readability.
237 ` const filteredAndSorted = useMemo(() => {` Named const filteredAndSorted = useMemo(() => {
constant —
value should
not change.
238 ` const q = (search \ \ localFilter).toLowerCase();`

Page 517 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
239 ` let list = storePackets;` Executable let list = storePackets;
statement.
240 ` if (q) {` Conditional if (q) {
branch — run
code only
when condition
true.

Line Source Easy Technical Explanation


Explanation
241 ` list = [Link](p =>` Source code list = [Link](p =>
line.
242 ` [Link]().includes(q) \ \ `
243 ` [Link]().includes(q) \ \ `
244 ` [Link]().includes(q) \ \ `
245 ` [Link]().includes(q) \ \ `
246 ` String([Link]).includes(q)` Source code String([Link]).includes(q)
line.
247 ` );` Executable );
statement.
248 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
249 ` if (sortDir) {` Conditional if (sortDir) {
branch — run
code only when
condition true.
250 ` list = [...list].sort((a, b) => {` Source code list = [...list].sort((a, b) => {
line.
251 ` let av: string \ number = number;`
a[sortKey as
keyof Packet]
as string \
252 ` let bv: string \ number = number;`
b[sortKey as
keyof Packet]
as string \
253 ` if (typeof av === 'string') av = Conditional if (typeof av === 'string') av =
[Link]();` branch — run [Link]();
code only when
condition true.
254 ` if (typeof bv === 'string') bv = Conditional if (typeof bv === 'string') bv =
[Link]();` branch — run [Link]();
code only when
condition true.
255 ` if (av < bv) return sortDir === 'asc' ? -1 : Conditional if (av < bv) return sortDir === 'asc' ? -1 : 1;
1;` branch — run
code only when
condition true.

Page 518 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
256 ` if (av > bv) return sortDir === 'asc' ? 1 : Conditional if (av > bv) return sortDir === 'asc' ? 1 : -1;
-1;` branch — run
code only when
condition true.
257 ` return 0;` Exit function return 0;
and give back
a value.
258 ` });` Executable });
statement.
259 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
260 ` return list;` Exit function return list;
and give back
a value.
261 ` }, [storePackets, search, localFilter, Executable }, [storePackets, search, localFilter, sortKey,
sortKey, sortDir]);` statement. sortDir]);
262 `` Blank line for Separator between code blocks.
readability.
263 ` const handleSort = useCallback((col: Named const handleSort = useCallback((col:
SortKey) => {` constant — SortKey) => {
value should
not change.
264 ` setSortKey(prev => {` Source code setSortKey(prev => {
line.
265 ` if (prev === col) {` Conditional if (prev === col) {
branch — run
code only when
condition true.
266 ` setSortDir(d => d === 'asc' ? 'desc' : d Executable setSortDir(d => d === 'asc' ? 'desc' : d ===
=== 'desc' ? null : 'asc');` statement. 'desc' ? null : 'asc');
267 ` return col;` Exit function return col;
and give back
a value.
268 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
269 ` setSortDir('asc');` Executable setSortDir('asc');
statement.
270 ` return col;` Exit function return col;
and give back
a value.
271 ` });` Executable });
statement.
272 ` }, []);` Executable }, []);
statement.
273 `` Blank line for Separator between code blocks.
readability.
274 ` const handleFilterSubmit = Named const handleFilterSubmit = useCallback((val:
useCallback((val: string) => {` constant — string) => {

Page 519 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
value should
not change.
275 ` setDisplayFilter(val);` Executable setDisplayFilter(val);
statement.
276 ` if (val) {` Conditional if (val) {
branch — run
code only when
condition true.
277 ` Executable [Link]().addRecentFilter(val);
[Link]().addRecentFilter(val);` statement.
278 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
279 ` }, [setDisplayFilter]);` Executable }, [setDisplayFilter]);
statement.
280 `` Blank line for Separator between code blocks.
readability.
281 ` const copyPacketInfo = Named const copyPacketInfo = useCallback((packet:
useCallback((packet: Packet) => {` constant — Packet) => {
value should
not change.
282 ` const text = `#${[Link]} ${[Link]} Named const text = `#${[Link]} ${[Link]}
${[Link]} → ${[Link]} constant — ${[Link]} → ${[Link]} [${pack
[${[Link]}] ${[Link]}`;` value should
not change.
283 ` [Link]?.writeText(text).then(() Source code [Link]?.writeText(text).then(()
=> {` line. => {
284 ` toast({ title: 'Copied', description: 'Packet Executable toast({ title: 'Copied', description: 'Packet info
info copied to clipboard' });` statement. copied to clipboard' });
285 ` });` Executable });
statement.
286 ` }, [toast]);` Executable }, [toast]);
statement.
287 `` Blank line for Separator between code blocks.
readability.
288 ` const COLS: { key: SortKey; label: string; Named const COLS: { key: SortKey; label: string;
width: string }[] = [` constant — width: string }[] = [
value should
not change.
289 ` { key: 'no', label: 'No.', width: 'w-14' },` Source code { key: 'no', label: 'No.', width: 'w-14' },
line.
290 ` { key: 'time', label: 'Time', width: 'w-44' },` Source code { key: 'time', label: 'Time', width: 'w-44' },
line.
291 ` { key: 'src', label: 'Source', width: 'w-40' },` Source code { key: 'src', label: 'Source', width: 'w-40' },
line.
292 ` { key: 'dst', label: 'Destination', width: 'w- Source code { key: 'dst', label: 'Destination', width: 'w-40' },
40' },` line.
293 ` { key: 'protocol', label: 'Protocol', width: 'w- Source code { key: 'protocol', label: 'Protocol', width: 'w-20'
20' },` line. },

Page 520 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
294 ` { key: 'length', label: 'Length', width: 'w-16' Source code { key: 'length', label: 'Length', width: 'w-16' },
},` line.
295 ` ];` Executable ];
statement.
296 `` Blank line for Separator between code blocks.
readability.
297 ` const Row = useCallback(({ index, style }: { Named const Row = useCallback(({ index, style }: {
index: number; style: [Link] }) constant — index: number; style: [Link]
=> {` value should
not change.
298 ` const packet = filteredAndSorted[index];` Named const packet = filteredAndSorted[index];
constant —
value should
not change.
299 ` if (!packet) return null;` Conditional if (!packet) return null;
branch — run
code only when
condition true.
300 ` const isSelected = selectedPacket?.no Named const isSelected = selectedPacket?.no ===
=== [Link];` constant — [Link];
value should
not change.
301 ` const stripe = Named const stripe = getRowStripe([Link]);
getRowStripe([Link]);` constant —
value should
not change.
302 ` return (` Exit function return (
and give back
a value.
303 ` <ContextMenu>` Source code <ContextMenu>
line.
304 ` <ContextMenuTrigger asChild>` Source code <ContextMenuTrigger asChild>
line.
305 ` <div` Source code <div
line.
306 ` style={{` Source code style={{
line.
307 ` ...style,` Source code ...style,
line.
308 ` backgroundColor: isSelected ? Source code backgroundColor: isSelected ? 'var(--bg-
'var(--bg-hover)' : line. hover)' : getRowBg([Link]),
getRowBg([Link]),`
309 ` borderLeft: `3px solid ${isSelected ? Source code borderLeft: `3px solid ${isSelected ? 'var(--
'var(--accent)' : stripe}`,` line. accent)' : stripe}`,
310 ` }}` Source code }}
line.
311 ` onClick={() => Source code onClick={() => setSelectedPacket(isSelected
setSelectedPacket(isSelected ? null : line. ? null : packet)}
packet)}`
312 ` className={`flex items-center text- Source code className={`flex items-center text-[10px]
[10px] font-mono px-2 cursor-pointer border-b line. font-mono px-2 cursor-pointer border-b
border-black/40 transiti...` border-black/40 tra

Page 521 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
313 ` ${isSelected ? 'ring-1 ring-[var(-- Source code ${isSelected ? 'ring-1 ring-[var(--accent)]
accent)] ring-inset z-10' : 'hover:brightness- line. ring-inset z-10' : 'hover:brightness-[1.8]'}`}
[1.8]'}`}`
314 ` >` Source code >
line.
315 ` <div className="w-14 shrink-0 text- Source code <div className="w-14 shrink-0 text-[var(--
[var(--text-muted)] text-right pr- line. text-muted)] text-right pr-
2">{[Link]}</div>` 2">{[Link]}</div>
316 ` <div className="w-44 shrink-0 px-2 Source code <div className="w-44 shrink-0 px-2
truncate text-[var(--text- line. truncate text-[var(--text-
secondary)]">{[Link]}</div>` secondary)]">{[Link]}</div>
317 ` <div className="w-40 shrink-0 px-2 Source code <div className="w-40 shrink-0 px-2
truncate text-white font-semibold" line. truncate text-white font-semibold"
title={[Link]}>{[Link]}</div>` title={[Link]}>{[Link]
318 ` <div className="w-40 shrink-0 px-2 Source code <div className="w-40 shrink-0 px-2
truncate text-white/85" line. truncate text-white/85"
title={[Link]}>{[Link]}</div>` title={[Link]}>{[Link]}</div>
319 ` <div className="w-20 shrink-0 px-2 Source code <div className="w-20 shrink-0 px-2 font-
font-bold" style={{ color: stripe line. bold" style={{ color: stripe
}}>{[Link]}</div>` }}>{[Link]}</div>
320 ` <div className="w-16 shrink-0 px-2 Source code <div className="w-16 shrink-0 px-2 text-
text-right text-[var(--text- line. right text-[var(--text-
secondary)]">{[Link]}</div>` secondary)]">{[Link]}</div>

Lin Source Easy Technical Explanation


e Explanation
321 ` <div className="flex-1 px-3 truncate Source code <div className="flex-1 px-3 truncate text-
text-white/80" line. white/80" title={[Link]}>{[Link]}</div>
title={[Link]}>{[Link]}</div>`
322 ` </div>` Source code </div>
line.
323 ` </ContextMenuTrigger>` Source code </ContextMenuTrigger>
line.
324 ` <ContextMenuContent className="w-64 Source code <ContextMenuContent className="w-64 bg-
bg-[var(--bg-overlay)] border-[var(--border- line. [var(--bg-overlay)] border-[var(--border-strong)]
strong)] text-[var(--text-pri...` text-[var(-
325 ` <ContextMenuSub>` Source code <ContextMenuSub>
line.
326 ` <ContextMenuSubTrigger Source code <ContextMenuSubTrigger className="font-
className="font-mono cursor-pointer hover:bg- line. mono cursor-pointer hover:bg-[var(--bg-
[var(--bg-hover)]">` hover)]">
327 ` Follow Stream` Source code Follow Stream
line.
328 ` </ContextMenuSubTrigger>` Source code </ContextMenuSubTrigger>
line.
329 ` <ContextMenuSubContent Source code <ContextMenuSubContent className="bg-
className="bg-[var(--bg-overlay)] border-[var(-- line. [var(--bg-overlay)] border-[var(--border-strong)]
border-strong)] text-xs">` text-xs">
330 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"

Page 522 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
331 ` onClick={() => setDisplayFilter(`tcp \ ${[Link](':')[0]}...`
&& (${[Link](':')[0]} \
332 ` Follow TCP Stream` Source code Follow TCP Stream
line.
333 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
334 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
335 ` onClick={() => setDisplayFilter(`udp \ ${[Link](':')[0]}...`
&& (${[Link](':')[0]} \
336 ` Follow UDP Stream` Source code Follow UDP Stream
line.
337 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
338 ` </ContextMenuSubContent>` Source code </ContextMenuSubContent>
line.
339 ` </ContextMenuSub>` Source code </ContextMenuSub>
line.
340 ` <ContextMenuSeparator className="bg- Source code <ContextMenuSeparator className="bg-[var(--
[var(--border-strong)]" />` line. border-strong)]" />
341 ` <ContextMenuSub>` Source code <ContextMenuSub>
line.
342 ` <ContextMenuSubTrigger Source code <ContextMenuSubTrigger className="font-
className="font-mono cursor-pointer hover:bg- line. mono cursor-pointer hover:bg-[var(--bg-
[var(--bg-hover)]">` hover)]">
343 ` Apply as Filter` Source code Apply as Filter
line.
344 ` </ContextMenuSubTrigger>` Source code </ContextMenuSubTrigger>
line.
345 ` <ContextMenuSubContent Source code <ContextMenuSubContent className="bg-
className="bg-[var(--bg-overlay)] border-[var(-- line. [var(--bg-overlay)] border-[var(--border-strong)]
border-strong)] text-xs">` text-xs">
346 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
347 ` onClick={() => Source code onClick={() =>
handleFilterSubmit([Link](':')[0])}>` line. handleFilterSubmit([Link](':')[0])}>
348 ` Source: {[Link](':')[0]}` Source code Source: {[Link](':')[0]}
line.
349 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
350 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
351 ` onClick={() => Source code onClick={() =>
handleFilterSubmit([Link](':')[0])}>` line. handleFilterSubmit([Link](':')[0])}>
352 ` Destination: {[Link](':')[0]}` Source code Destination: {[Link](':')[0]}
line.
353 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.

Page 523 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
354 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
355 ` onClick={() => Source code onClick={() =>
handleFilterSubmit([Link] line. handleFilterSubmit([Link]
())}>` e())}>
356 ` Protocol: {[Link]}` Source code Protocol: {[Link]}
line.
357 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
358 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
359 ` onClick={() => \ ${[Link](':')[0]}`)}>`
handleFilterSubmit(`${[Link](':')[0]} \
360 ` Conversation` Source code Conversation
line.
361 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
362 ` </ContextMenuSubContent>` Source code </ContextMenuSubContent>
line.
363 ` </ContextMenuSub>` Source code </ContextMenuSub>
line.
364 ` <ContextMenuSeparator className="bg- Source code <ContextMenuSeparator className="bg-[var(--
[var(--border-strong)]" />` line. border-strong)]" />
365 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
366 ` onClick={() => Source code onClick={() => copyPacketInfo(packet)}>
copyPacketInfo(packet)}>` line.
367 ` <Copy className="w-3 h-3 mr-2 inline" Source code <Copy className="w-3 h-3 mr-2 inline" />
/> Copy Packet Info` line. Copy Packet Info
368 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
369 ` <ContextMenuItem className="font- Source code <ContextMenuItem className="font-mono
mono cursor-pointer hover:bg-[var(--bg-hover)]"` line. cursor-pointer hover:bg-[var(--bg-hover)]"
370 ` onClick={() => {` Source code onClick={() => {
line.
371 ` setSelectedPacket(packet);` Executable setSelectedPacket(packet);
statement.
372 ` toast({ title: `Packet #${[Link]} Executable toast({ title: `Packet #${[Link]} marked`,
marked`, description: [Link](0, 60) });` statement. description: [Link](0, 60) });
373 ` }}>` Source code }}>
line.
374 ` Mark / Unmark Packet` Source code Mark / Unmark Packet
line.
375 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
376 ` <ContextMenuSeparator className="bg- Source code <ContextMenuSeparator className="bg-[var(--
[var(--border-strong)]" />` line. border-strong)]" />
377 ` <ContextMenuItem` Source code <ContextMenuItem
line.

Page 524 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
378 ` className="font-mono cursor-pointer Source code className="font-mono cursor-pointer hover:bg-
hover:bg-[var(--bg-hover)] text-[var(--critical)]"` line. [var(--bg-hover)] text-[var(--critical)]"
379 ` onClick={() => {` Source code onClick={() => {
line.
380 ` setPackets([Link](p => Executable setPackets([Link](p => [Link] !==
[Link] !== [Link]));` statement. [Link]));
381 ` toast({ title: 'Packet removed', Executable toast({ title: 'Packet removed', description:
description: `Packet #${[Link]} removed from statement. `Packet #${[Link]} removed from view` });
view` });`
382 ` }}>` Source code }}>
line.
383 ` Remove Packet from View` Source code Remove Packet from View
line.
384 ` </ContextMenuItem>` Source code </ContextMenuItem>
line.
385 ` </ContextMenuContent>` Source code </ContextMenuContent>
line.
386 ` </ContextMenu>` Source code </ContextMenu>
line.
387 ` );` Executable );
statement.
388 ` }, [filteredAndSorted, selectedPacket, Executable }, [filteredAndSorted, selectedPacket,
setSelectedPacket, setDisplayFilter, statement. setSelectedPacket, setDisplayFilter,
handleFilterSubmit, copyPacketInfo, sto...` handleFilterSubmit, copy
389 `` Blank line for Separator between code blocks.
readability.
390 ` const handleStartCapture = () => {` Named const handleStartCapture = () => {
constant —
value should
not change.
391 ` clearPackets();` Executable clearPackets();
statement.
392 ` setCaptureState('capturing');` Executable setCaptureState('capturing');
statement.
393 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
394 `` Blank line for Separator between code blocks.
readability.
395 ` const handleStopCapture = () => {` Named const handleStopCapture = () => {
constant —
value should
not change.
396 ` setCaptureState('stopped');` Executable setCaptureState('stopped');
statement.
397 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

Page 525 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
398 `` Blank line for Separator between code blocks.
readability.
399 ` const handlePauseResume = () => {` Named const handlePauseResume = () => {
constant —
value should
not change.
400 ` if (captureState === 'capturing') {` Conditional if (captureState === 'capturing') {
branch — run
code only
when
condition true.

Line Source Easy Technical Explanation


Explanation
401 ` setCaptureState('paused');` Executable setCaptureState('paused');
statement.
402 ` } else if (captureState === 'paused') {` Conditional } else if (captureState === 'paused') {
branch — run
code only when
condition true.
403 ` setCaptureState('capturing');` Executable setCaptureState('capturing');
statement.
404 ` Executable resumeCapture().catch([Link]);
resumeCapture().catch([Link]);` statement.
405 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
406 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
407 `` Blank line for Separator between code blocks.
readability.
408 ` return (` Exit function and return (
give back a
value.
409 ` <div className="h-full flex flex-col bg- Source code line. <div className="h-full flex flex-col bg-
[var(--bg-void)] text-[var(--text-primary)]">` [var(--bg-void)] text-[var(--text-primary)]">
410 ` {/* Toolbar */}` Source code line. {/* Toolbar */}
411 ` <div className="h-11 border-b Source code line. <div className="h-11 border-b border-
border-[var(--border-default)] bg-[var(--bg- [var(--border-default)] bg-[var(--bg-base)]
base)] flex items-center px-4 gap-3 s...` flex items-center p
412 ` <div className="flex items-center Source code line. <div className="flex items-center gap-
gap-0.5">` 0.5">
413 ` {/* Start */}` Source code line. {/* Start */}
414 ` <Button variant="ghost" size="icon" Source code line. <Button variant="ghost" size="icon"
className="w-8 h-8 text-[var(--accent)] className="w-8 h-8 text-[var(--accent)]
hover:bg-[var(--accent-dim)]"` hover:bg-[var(--accent-d
415 ` onClick={handleStartCapture}` Source code line. onClick={handleStartCapture}

Page 526 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
416 ` disabled={captureState === Source code line. disabled={captureState === 'capturing'}
'capturing'} title="Start Capture (clears title="Start Capture (clears screen)">
screen)">`
417 ` <Play className="h-4 w-4" Source code line. <Play className="h-4 w-4"
fill="currentColor" />` fill="currentColor" />
418 ` </Button>` Source code line. </Button>
419 ` {/* Stop */}` Source code line. {/* Stop */}
420 ` <Button variant="ghost" size="icon" Source code line. <Button variant="ghost" size="icon"
className="w-8 h-8 text-[var(--critical)] className="w-8 h-8 text-[var(--critical)]
hover:bg-[var(--critical)]/20"` hover:bg-[var(--critic
421 ` onClick={handleStopCapture}` Source code line. onClick={handleStopCapture}
422 ` disabled={captureState === 'idle' \ \ captureState === 'stopped'} title="Stop
Capture">`
423 ` <Square className="h-4 w-4" Source code line. <Square className="h-4 w-4"
fill="currentColor" />` fill="currentColor" />
424 ` </Button>` Source code line. </Button>
425 ` {/* Pause / Resume */}` Source code line. {/* Pause / Resume */}
426 ` <Button variant="ghost" Source code line. <Button variant="ghost" size="icon"
size="icon"`
427 ` className={`w-8 h-8 hover:bg- Source code line. className={`w-8 h-8 hover:bg-[var(--
[var(--medium)]/20 transition-colors medium)]/20 transition-colors
${captureState === 'paused' ? 'text-[va...` ${captureState === 'paused' ? 'tex
428 ` onClick={handlePauseResume}` Source code line. onClick={handlePauseResume}
429 ` disabled={captureState !== Source code line. disabled={captureState !== 'capturing'
'capturing' && captureState !== 'paused'}` && captureState !== 'paused'}
430 ` title={captureState === 'paused' ? Source code line. title={captureState === 'paused' ?
'Resume Capture' : 'Pause Capture'}>` 'Resume Capture' : 'Pause Capture'}>
431 ` <Pause className="h-4 w-4" Source code line. <Pause className="h-4 w-4"
fill="currentColor" />` fill="currentColor" />
432 ` </Button>` Source code line. </Button>
433 ` </div>` Source code line. </div>
434 `` Blank line for Separator between code blocks.
readability.
435 ` <div className="h-5 w-px bg-[var(-- Source code line. <div className="h-5 w-px bg-[var(--
border-default)]" />` border-default)]" />
436 `` Blank line for Separator between code blocks.
readability.
437 ` {/* Clear Screen */}` Source code line. {/* Clear Screen */}
438 ` <Button variant="ghost" size="icon"` Source code line. <Button variant="ghost" size="icon"
439 ` className="w-8 h-8 text-[var(-- Source code line. className="w-8 h-8 text-[var(--text-
text-muted)] hover:text-[var(--critical)] muted)] hover:text-[var(--critical)]
hover:bg-[var(--critical)]/10"` hover:bg-[var(--critical)]/
440 ` onClick={() => {` Source code line. onClick={() => {
441 ` clearPackets();` Executable clearPackets();
statement.

Page 527 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
442 ` toast({ title: 'Screen cleared', Executable toast({ title: 'Screen cleared', description:
description: 'All packets removed from statement. 'All packets removed from view' });
view' });`
443 ` }}` Source code line. }}
444 ` title="Clear Screen">` Source code line. title="Clear Screen">
445 ` <Trash2 className="h-4 w-4" />` Source code line. <Trash2 className="h-4 w-4" />
446 ` </Button>` Source code line. </Button>
447 `` Blank line for Separator between code blocks.
readability.
448 ` <div className="h-5 w-px bg-[var(-- Source code line. <div className="h-5 w-px bg-[var(--
border-default)]" />` border-default)]" />
449 `` Blank line for Separator between code blocks.
readability.
450 ` {/* Display filter */}` Source code line. {/* Display filter */}
451 ` <div className="relative flex-1 max- Source code line. <div className="relative flex-1 max-w-
w-md">` md">
452 ` <Filter className="absolute left- Source code line. <Filter className="absolute left-2.5 top-
2.5 top-1/2 -translate-y-1/2 w-3 h-3 text- 1/2 -translate-y-1/2 w-3 h-3 text-[var(--
[var(--text-muted)]" />` text-muted)]" />
453 ` <input` Source code line. <input
454 ` type="text"` Source code line. type="text"
455 ` value={localFilter}` Source code line. value={localFilter}
456 ` onChange={e => Source code line. onChange={e =>
setLocalFilter([Link])}` setLocalFilter([Link])}
457 ` onKeyDown={e => {` Source code line. onKeyDown={e => {
458 ` if ([Link] === 'Enter') Conditional if ([Link] === 'Enter')
handleFilterSubmit(localFilter);` branch — run handleFilterSubmit(localFilter);
code only when
condition true.
459 ` if ([Link] === 'Escape') { Conditional if ([Link] === 'Escape') { setLocalFilter('');
setLocalFilter(''); handleFilterSubmit(''); }` branch — run handleFilterSubmit(''); }
code only when
condition true.
460 ` }}` Source code line. }}
461 ` onBlur={() => Source code line. onBlur={() =>
handleFilterSubmit(localFilter)}` handleFilterSubmit(localFilter)}
462 ` placeholder="Display filter… e.g. Source code line. placeholder="Display filter… e.g. tcp,
tcp, [Link], dns [Enter to apply]"` [Link], dns [Enter to apply]"
463 ` className={`w-full h-7 bg-[var(-- Source code line. className={`w-full h-7 bg-[var(--bg-
bg-overlay)] border rounded text-[10px] pl- overlay)] border rounded text-[10px] pl-8
8 pr-8 focus:outline-none fon...` pr-8 focus:outline-non
464 ` ${localFilter ? 'border-[var(-- Source code line. ${localFilter ? 'border-[var(--normal)]' :
normal)]' : 'border-[var(--border-strong)] 'border-[var(--border-strong)]
focus:border-[var(--accent)]'}`}` focus:border-[var(--accent
465 ` />` Source code line. />
466 ` {localFilter && (` Source code line. {localFilter && (
467 ` <button` Source code line. <button

Page 528 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
468 ` className="absolute right-2 top- Source code line. className="absolute right-2 top-1/2 -
1/2 -translate-y-1/2 text-[var(--text-muted)] translate-y-1/2 text-[var(--text-muted)]
hover:text-[var(--text-pr...` hover:text-[var(--text
469 ` onClick={() => { setLocalFilter(''); Source code line. onClick={() => { setLocalFilter('');
handleFilterSubmit(''); }}>` handleFilterSubmit(''); }}>
470 ` ×` Source code line. ×
471 ` </button>` Source code line. </button>
472 ` )}` Source code line. )}
473 ` </div>` Source code line. </div>
474 `` Blank line for Separator between code blocks.
readability.
475 ` {/* Search */}` Source code line. {/* Search */}
476 ` <div className="relative">` Source code line. <div className="relative">
477 ` <Search className="absolute left- Source code line. <Search className="absolute left-2.5
2.5 top-1/2 -translate-y-1/2 w-3 h-3 text- top-1/2 -translate-y-1/2 w-3 h-3 text-[var(-
[var(--text-muted)]" />` -text-muted)]" />
478 ` <input` Source code line. <input
479 ` type="text"` Source code line. type="text"
480 ` value={search}` Source code line. value={search}

Line Source Easy Technical Explanation


Explanation
481 ` onChange={e => Source code onChange={e =>
setSearch([Link])}` line. setSearch([Link])}
482 ` placeholder="Search packets…"` Source code placeholder="Search packets…"
line.
483 ` className="w-44 h-7 bg-[var(--bg- Source code className="w-44 h-7 bg-[var(--bg-
overlay)] border border-[var(--border- line. overlay)] border border-[var(--border-
strong)] rounded text-[10px] pl-8 ...` strong)] rounded text-[10px]
484 ` />` Source code />
line.
485 ` </div>` Source code </div>
line.
486 `` Blank line for Separator between code blocks.
readability.
487 ` {/* Packet count */}` Source code {/* Packet count */}
line.
488 ` {(search \ \ localFilter) && (`
489 ` <span className="text-[9px] font- Source code <span className="text-[9px] font-mono
mono text-[var(--text-muted)]">` line. text-[var(--text-muted)]">
490 ` {[Link]} / Source code {[Link]} /
{[Link]} pkts` line. {[Link]} pkts
491 ` </span>` Source code </span>
line.
492 ` )}` Source code )}
line.

Page 529 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
493 `` Blank line for Separator between code blocks.
readability.
494 ` {/* Backend error indicator */}` Source code {/* Backend error indicator */}
line.
495 ` {apiError && captureState === Source code {apiError && captureState === 'capturing'
'capturing' && (` line. && (
496 ` <span className="text-[9px] font- Source code <span className="text-[9px] font-mono
mono text-[var(--medium)] flex items-center line. text-[var(--medium)] flex items-center gap-
gap-1">` 1">
497 ` <span className="w-1.5 h-1.5 Source code <span className="w-1.5 h-1.5 rounded-
rounded-full bg-[var(--medium)] animate- line. full bg-[var(--medium)] animate-pulse
pulse inline-block" />` inline-block" />
498 ` backend offline` Source code backend offline
line.
499 ` </span>` Source code </span>
line.
500 ` )}` Source code )}
line.
501 ` </div>` Source code </div>
line.
502 `` Blank line for Separator between code blocks.
readability.
503 ` {/* Main Panels */}` Source code {/* Main Panels */}
line.
504 ` <ResizablePanelGroup Source code <ResizablePanelGroup direction="vertical"
direction="vertical" className="flex-1 line. className="flex-1 overflow-hidden">
overflow-hidden">`
505 ` <ResizablePanel defaultSize={55} Source code <ResizablePanel defaultSize={55}
minSize={20}>` line. minSize={20}>
506 ` <div className="h-full flex flex-col Source code <div className="h-full flex flex-col bg-
bg-[var(--bg-base)]">` line. [var(--bg-base)]">
507 ` {/* Column headers */}` Source code {/* Column headers */}
line.
508 ` <div className="flex bg-[var(--bg- Source code <div className="flex bg-[var(--bg-
overlay)] border-b border-[var(--border- line. overlay)] border-b border-[var(--border-
strong)] text-[9px] font-mono f...` strong)] text-[9px] font-m
509 ` {[Link](col => (` Source code {[Link](col => (
line.
510 ` <button` Source code <button
line.
511 ` key={[Link]}` Source code key={[Link]}
line.
512 ` onClick={() => Source code onClick={() => handleSort([Link])}
handleSort([Link])}` line.
513 ` className={`${[Link]} Source code className={`${[Link]} shrink-0 flex
shrink-0 flex items-center gap-1 px-2 line. items-center gap-1 px-2 hover:text-[var(--
hover:text-[var(--text-primary)] tra...` text-primary)] tran
514 ` ${[Link] === 'length' ? 'justify- Source code ${[Link] === 'length' ? 'justify-end' : ''}
end' : ''}` line.

Page 530 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
515 ` ${[Link] === 'no' ? 'justify-end Source code ${[Link] === 'no' ? 'justify-end pr-2' : ''}`}
pr-2' : ''}`}` line.
516 ` >` Source code >
line.
517 ` {[Link]}` Source code {[Link]}
line.
518 ` <SortIcon col={[Link]} Source code <SortIcon col={[Link]} sortKey={sortKey}
sortKey={sortKey} sortDir={sortDir} />` line. sortDir={sortDir} />
519 ` </button>` Source code </button>
line.
520 ` ))}` Source code ))}
line.
521 ` <div className="flex-1 px-3 Source code <div className="flex-1 px-3 uppercase
uppercase tracking-wider">Info</div>` line. tracking-wider">Info</div>
522 ` </div>` Source code </div>
line.
523 `` Blank line for Separator between code blocks.
readability.
524 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-hidden
hidden relative" ref={listContainerRef}>` line. relative" ref={listContainerRef}>
525 ` {[Link] === 0 ? Source code {[Link] === 0 ? (
(` line.
526 ` <div className="absolute inset- Source code <div className="absolute inset-0 flex
0 flex flex-col items-center justify-center line. flex-col items-center justify-center text-
text-[var(--text-muted)] o...` [var(--text-muted)]
527 ` <ShieldCheck className="w- Source code <ShieldCheck className="w-20 h-20 mb-
20 h-20 mb-4 text-[var(--accent)]" line. 4 text-[var(--accent)]" strokeWidth={1} />
strokeWidth={1} />`
528 ` <span className="font-mono Source code <span className="font-mono text-sm
text-sm text-[var(--text-primary)]">` line. text-[var(--text-primary)]">
529 ` {captureState === 'capturing' ? Source code {captureState === 'capturing' ? 'Waiting
'Waiting for packets…' : 'No packets line. for packets…' : 'No packets captured'}
captured'}`
530 ` </span>` Source code </span>
line.
531 ` <span className="font-sans Source code <span className="font-sans text-xs mt-
text-xs mt-1">` line. 1">
532 ` {captureState === 'idle' \ \ captureState === 'stopped'`
533 ` ? 'Press ▶ to start capture'` Source code ? 'Press ▶ to start capture'
line.
534 ` : captureState === 'paused'` Source code : captureState === 'paused'
line.
535 ` ? 'Capture paused'` Source code ? 'Capture paused'
line.
536 ` : 'Start a capture or open a Source code : 'Start a capture or open a PCAP file'}
PCAP file'}` line.
537 ` </span>` Source code </span>
line.

Page 531 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
538 ` </div>` Source code </div>
line.
539 ` ) : (` Source code ):(
line.
540 ` <List` Source code <List
line.
541 ` ref={listRef}` Source code ref={listRef}
line.
542 ` height={listHeight}` Source code height={listHeight}
line.
543 ` Source code itemCount={[Link]}
itemCount={[Link]}` line.
544 ` itemSize={ROW_HEIGHT}` Source code itemSize={ROW_HEIGHT}
line.
545 ` width="100%"` Source code width="100%"
line.
546 ` >` Source code >
line.
547 ` {Row}` Source code {Row}
line.
548 ` </List>` Source code </List>
line.
549 ` )}` Source code )}
line.
550 ` </div>` Source code </div>
line.
551 ` </div>` Source code </div>
line.
552 ` </ResizablePanel>` Source code </ResizablePanel>
line.
553 `` Blank line for Separator between code blocks.
readability.
554 ` <ResizableHandle className="h- Source code <ResizableHandle className="h-[3px]
[3px] bg-[var(--border-strong)] hover:bg- line. bg-[var(--border-strong)] hover:bg-[var(--
[var(--accent)] transition-colors" />` accent)] transition-co
555 `` Blank line for Separator between code blocks.
readability.
556 ` <ResizablePanel defaultSize={45} Source code <ResizablePanel defaultSize={45}
minSize={15}>` line. minSize={15}>
557 ` <ResizablePanelGroup Source code <ResizablePanelGroup
direction="horizontal">` line. direction="horizontal">
558 ` <ResizablePanel defaultSize={50} Source code <ResizablePanel defaultSize={50}
minSize={20}>` line. minSize={20}>
559 ` <div className="h-full flex flex-col Source code <div className="h-full flex flex-col
border-r border-[var(--border-strong)] bg- line. border-r border-[var(--border-strong)] bg-
[var(--bg-base)]">` [var(--bg-base)]">
560 ` <div className="h-6 bg-[var(-- Source code <div className="h-6 bg-[var(--bg-
bg-overlay)] border-b border-[var(--border- line. overlay)] border-b border-[var(--border-
strong)] flex items-center p...` strong)] flex items-center

Page 532 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
561 ` <span className="font-mono text- Source code <span className="font-mono text-[9px] text-
[9px] text-[var(--text-muted)] uppercase tracking- line. [var(--text-muted)] uppercase tracking-
wider">Packet Det...` wider">Packet Deta
562 ` {selectedPacket && (` Source code {selectedPacket && (
line.
563 ` <span className="ml-2 font-mono Source code <span className="ml-2 font-mono text-[9px]
text-[9px] text-[var(--accent)]">` line. text-[var(--accent)]">
564 ` #{[Link]} · Comment {[Link]} · {[Link]}
{[Link]} · documenting · {[Link]}B
{[Link]}B` intent.
565 ` </span>` Source code </span>
line.
566 ` )}` Source code )}
line.
567 ` </div>` Source code </div>
line.
568 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-auto">
auto">` line.
569 ` {selectedPacket ? (` Source code {selectedPacket ? (
line.
570 ` <ProtocolTree Source code <ProtocolTree layers={[Link] ??
layers={[Link] ?? []} />` line. []} />
571 ` ) : (` Source code ):(
line.
572 ` <div className="p-4 font-mono Source code <div className="p-4 font-mono text-[10px] text-
text-[10px] text-[var(--text-muted)]">Select a line. [var(--text-muted)]">Select a packet to view
packet to view proto...` protocol
573 ` )}` Source code )}
line.
574 ` </div>` Source code </div>
line.
575 ` </div>` Source code </div>
line.
576 ` </ResizablePanel>` Source code </ResizablePanel>
line.
577 `` Blank line for Separator between code blocks.
readability.
578 ` <ResizableHandle className="w-[3px] Source code <ResizableHandle className="w-[3px] bg-[var(-
bg-[var(--border-strong)] hover:bg-[var(--accent)] line. -border-strong)] hover:bg-[var(--accent)]
transition-colors" />` transition-co
579 `` Blank line for Separator between code blocks.
readability.
580 ` <ResizablePanel defaultSize={50} Source code <ResizablePanel defaultSize={50}
minSize={20}>` line. minSize={20}>
581 ` <div className="h-full flex flex-col bg- Source code <div className="h-full flex flex-col bg-[var(--bg-
[var(--bg-base)]">` line. base)]">

Page 533 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
582 ` <div className="h-6 bg-[var(--bg- Source code <div className="h-6 bg-[var(--bg-overlay)]
overlay)] border-b border-[var(--border-strong)] line. border-b border-[var(--border-strong)] flex items-
flex items-center p...` center
583 ` <span className="font-mono text- Source code <span className="font-mono text-[9px] text-
[9px] text-[var(--text-muted)] uppercase tracking- line. [var(--text-muted)] uppercase tracking-
wider">Hex Viewer...` wider">Hex Viewer<
584 ` {selectedPacket && (` Source code {selectedPacket && (
line.
585 ` <div className="flex items-center Source code <div className="flex items-center gap-2">
gap-2">` line.
586 ` <span className="font-mono Source code <span className="font-mono text-[9px] text-
text-[9px] text-[var(--text-secondary)]">` line. [var(--text-secondary)]">
587 ` {[Link](0, 35)}` Source code {[Link](0, 35)}
line.
588 ` </span>` Source code </span>
line.
589 ` <button` Source code <button
line.
590 ` title="Copy hex"` Source code title="Copy hex"
line.
591 ` className="text-[var(--text- Source code className="text-[var(--text-muted)] hover:text-
muted)] hover:text-[var(--accent)] transition- line. [var(--accent)] transition-colors"
colors"`
592 ` onClick={() => {` Source code onClick={() => {
line.
593 ` if ([Link]) {` Conditional if ([Link]) {
branch — run
code only
when
condition
true.
594 ` Executable [Link]?.writeText(selectedPacket.r
[Link]?.writeText([Link] statement. awHex);
wHex);`
595 ` toast({ title: 'Hex copied' });` Executable toast({ title: 'Hex copied' });
statement.
596 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
597 ` }}>` Source code }}>
line.
598 ` <Copy className="w-2.5 h-2.5" Source code <Copy className="w-2.5 h-2.5" />
/>` line.
599 ` </button>` Source code </button>
line.
600 ` </div>` Source code </div>
line.
601 ` )}` Source code )}
line.

Page 534 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
602 ` </div>` Source code </div>
line.
603 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-auto">
auto">` line.
604 ` <HexViewer Source code <HexViewer hex={selectedPacket?.rawHex ??
hex={selectedPacket?.rawHex ?? ''} line. ''} packet={selectedPacket} />
packet={selectedPacket} />`
605 ` </div>` Source code </div>
line.
606 ` </div>` Source code </div>
line.
607 ` </ResizablePanel>` Source code </ResizablePanel>
line.
608 ` </ResizablePanelGroup>` Source code </ResizablePanelGroup>
line.
609 ` </ResizablePanel>` Source code </ResizablePanel>
line.
610 ` </ResizablePanelGroup>` Source code </ResizablePanelGroup>
line.
611 ` </div>` Source code </div>
line.
612 ` );` Executable );
statement.
613 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.

File: webwireshark/src/pages/[Link]
Total lines: 309

Lin Source Easy Technical Explanation


e Explanation
1 `import React, { useState, useMemo, useRef, Executable import React, { useState, useMemo, useRef,
useEffect, useCallback } from 'react';` statement. useEffect, useCallback } from 'react';
2 `import { VariableSizeList as List } from 'react- Executable import { VariableSizeList as List } from 'react-
window';` statement. window';
3 `import { GitMerge, Filter, X, ExternalLink, Copy, Executable import { GitMerge, Filter, X, ExternalLink, Copy,
Shield, Loader2 } from 'lucide-react';` statement. Shield, Loader2 } from 'lucide-react';
4 `import { Button } from Executable import { Button } from
'@/components/ui/button';` statement. '@/components/ui/button';
5 `import { useGetNadsFlows } from Executable import { useGetNadsFlows } from
'@workspace/api-client-react';` statement. '@workspace/api-client-react';

Page 535 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
6 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
7 `import { useLocation } from 'wouter';` Executable import { useLocation } from 'wouter';
statement.
8 `import { useToast } from '@/hooks/use-toast';` Executable import { useToast } from '@/hooks/use-toast';
statement.
9 `import type { NetworkFlow } from Executable import type { NetworkFlow } from
'@workspace/api-client-react';` statement. '@workspace/api-client-react';
10 `` Blank line for Separator between code blocks.
readability.
11 `const STATUS_COLORS: Record<string, Named const STATUS_COLORS: Record<string,
string> = {` constant — string> = {
value should
not change.
12 ` active: 'var(--normal)',` Source code active: 'var(--normal)',
line.
13 ` suspicious: 'var(--medium)',` Source code suspicious: 'var(--medium)',
line.
14 ` blocked: 'var(--critical)',` Source code blocked: 'var(--critical)',
line.
15 ` closed: 'var(--text-muted)',` Source code closed: 'var(--text-muted)',
line.
16 `};` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
17 `` Blank line for Separator between code blocks.
readability.
18 `export default function Flows() {` Source code export default function Flows() {
line.
19 ` const [selectedFlowId, setSelectedFlowId] = null>(null);` Named constant — value should not change.
useState<string \
20 ` const [search, setSearch] = useState('');` Named const [search, setSearch] = useState('');
constant —
value should
not change.
21 ` const [statusFilter, setStatusFilter] = null>(null);` Named constant — value should not change.
useState<string \
22 ` const [listHeight, setListHeight] = Named const [listHeight, setListHeight] =
useState(600);` constant — useState(600);
value should
not change.
23 ` const listContainerRef = Named const listContainerRef =
useRef<HTMLDivElement>(null);` constant — useRef<HTMLDivElement>(null);
value should
not change.
24 ` const { data: flows = [], isLoading } = Named const { data: flows = [], isLoading } =
useGetNadsFlows();` constant — useGetNadsFlows();
value should
not change.

Page 536 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
25 ` const [_location, setLocation] = Named const [_location, setLocation] = useLocation();
useLocation();` constant —
value should
not change.
26 ` const { setDisplayFilter } = useAppStore();` Named const { setDisplayFilter } = useAppStore();
constant —
value should
not change.
27 ` const { toast } = useToast();` Named const { toast } = useToast();
constant —
value should
not change.
28 `` Blank line for Separator between code blocks.
readability.
29 ` useEffect(() => {` Source code useEffect(() => {
line.
30 ` const el = [Link];` Named const el = [Link];
constant —
value should
not change.
31 ` if (!el) return;` Conditional if (!el) return;
branch — run
code only
when condition
true.
32 ` const ro = new ResizeObserver(entries => {` Named const ro = new ResizeObserver(entries => {
constant —
value should
not change.
33 ` for (const e of entries) Loop over for (const e of entries)
setListHeight([Link]);` items or until setListHeight([Link]);
condition
changes.
34 ` });` Executable });
statement.
35 ` [Link](el);` Executable [Link](el);
statement.
36 ` Executable setListHeight([Link]().height
setListHeight([Link]().height) statement. );
;`
37 ` return () => [Link]();` Exit function return () => [Link]();
and give back
a value.
38 ` }, []);` Executable }, []);
statement.
39 `` Blank line for Separator between code blocks.
readability.
40 ` const getScoreColor = useCallback((score: Named const getScoreColor = useCallback((score:
number) => {` constant — number) => {
value should
not change.
41 ` if (score >= 80) return 'var(--critical)';` Conditional if (score >= 80) return 'var(--critical)';
branch — run

Page 537 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
code only
when condition
true.
42 ` if (score >= 60) return 'var(--high)';` Conditional if (score >= 60) return 'var(--high)';
branch — run
code only
when condition
true.
43 ` if (score >= 40) return 'var(--medium)';` Conditional if (score >= 40) return 'var(--medium)';
branch — run
code only
when condition
true.
44 ` return 'var(--low)';` Exit function return 'var(--low)';
and give back
a value.
45 ` }, []);` Executable }, []);
statement.
46 `` Blank line for Separator between code blocks.
readability.
47 ` const filteredFlows = useMemo(() => {` Named const filteredFlows = useMemo(() => {
constant —
value should
not change.
48 ` const q = [Link]();` Named const q = [Link]();
constant —
value should
not change.
49 ` return [Link](f => {` Exit function return [Link](f => {
and give back
a value.
50 ` const matchSearch = !q \ \ [`
51 ` [Link], String([Link]),` Source code [Link], String([Link]),
line.
52 ` [Link], String([Link]),` Source code [Link], String([Link]),
line.
53 ` [Link], [Link] ?? '',` Source code [Link], [Link] ?? '',
line.
54 ` ].some(v => [Link]().includes(q));` Executable ].some(v => [Link]().includes(q));
statement.
55 ` const matchStatus = !statusFilter \ \ [Link] === statusFilter;`
56 ` return matchSearch && matchStatus;` Exit function return matchSearch && matchStatus;
and give back
a value.
57 ` });` Executable });
statement.
58 ` }, [flows, search, statusFilter]);` Executable }, [flows, search, statusFilter]);
statement.
59 `` Blank line for Separator between code blocks.
readability.

Page 538 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
60 ` const selectedFlow = [Link](f => [Link] === Named const selectedFlow = [Link](f => [Link] ===
selectedFlowId) ?? null;` constant — selectedFlowId) ?? null;
value should
not change.
61 `` Blank line for Separator between code blocks.
readability.
62 ` const statusCounts = useMemo(() => {` Named const statusCounts = useMemo(() => {
constant —
value should
not change.
63 ` const counts: Record<string, number> = { Named const counts: Record<string, number> = {
active: 0, suspicious: 0, blocked: 0, closed: 0 };` constant — active: 0, suspicious: 0, blocked: 0, c
value should
not change.
64 ` [Link](f => { if (counts[[Link]] != Executable [Link](f => { if (counts[[Link]] != null)
null) counts[[Link]]++; });` statement. counts[[Link]]++; });
65 ` return counts;` Exit function return counts;
and give back
a value.
66 ` }, [flows]);` Executable }, [flows]);
statement.
67 `` Blank line for Separator between code blocks.
readability.
68 ` const Row = useCallback(({ index, style }: { Named const Row = useCallback(({ index, style }: {
index: number; style: [Link] }) => constant — index: number; style: [Link]
{` value should
not change.
69 ` const flow = filteredFlows[index];` Named const flow = filteredFlows[index];
constant —
value should
not change.
70 ` if (!flow) return null;` Conditional if (!flow) return null;
branch — run
code only
when condition
true.
71 ` const isSelected = selectedFlowId === Named const isSelected = selectedFlowId === [Link];
[Link];` constant —
value should
not change.
72 ` const scoreColor = Named const scoreColor =
getScoreColor([Link]);` constant — getScoreColor([Link]);
value should
not change.
73 ` return (` Exit function return (
and give back
a value.
74 ` <div` Source code <div
line.
75 ` style={style}` Source code style={style}
line.

Page 539 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
76 ` className={`flex items-center text-xs Source code className={`flex items-center text-xs font-
font-mono px-4 cursor-pointer border-b border- line. mono px-4 cursor-pointer border-b border-[var(-
[var(--border-subtle)]/50...` -border-su
77 ` onClick={() => Source code onClick={() => setSelectedFlowId([Link])}
setSelectedFlowId([Link])}` line.
78 ` >` Source code >
line.
79 ` <div className="absolute left-0 top-0 Source code <div className="absolute left-0 top-0 bottom-0
bottom-0 w-1" style={{ backgroundColor: line. w-1" style={{ backgroundColor: scoreColor }} />
scoreColor }} />`
80 ` <div className="w-56 shrink-0 pl-2 text- Source code <div className="w-56 shrink-0 pl-2 text-[var(--
[var(--text-secondary)] truncate">` line. text-secondary)] truncate">

Line Source Easy Technical Explanation


Explanation
81 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-
primary)]">{[Link]}</span>:{[Link]}` line. primary)]">{[Link]}</span>:{[Link]}
82 ` </div>` Source code </div>
line.
83 ` <div className="w-8 shrink-0 text-center Source code <div className="w-8 shrink-0 text-center text-
text-[var(--text-muted)]">→</div>` line. [var(--text-muted)]">→</div>
84 ` <div className="w-56 shrink-0 text-[var(- Source code <div className="w-56 shrink-0 text-[var(--
-text-secondary)] truncate">` line. text-secondary)] truncate">
85 ` <span className="text-[var(-- Source code <span className="text-[var(--
accent)]">{[Link]}</span>:{[Link]}` line. accent)]">{[Link]}</span>:{[Link]}
86 ` </div>` Source code </div>
line.
87 ` <div className="w-20 shrink-0 Source code <div className="w-20 shrink-0
uppercase">{[Link]}</div>` line. uppercase">{[Link]}</div>
88 ` <div className="w-24 shrink-0 text- Source code <div className="w-24 shrink-0 text-
right">{[Link]()}</div>` line. right">{[Link]()}</div>
89 ` <div className="w-28 shrink-0 text-right Source code <div className="w-28 shrink-0 text-right text-
text-[var(--text-secondary)]">` line. [var(--text-secondary)]">
90 ` {[Link] > 1024 * 1024 ? Source code {[Link] > 1024 * 1024 ? `${([Link] /
`${([Link] / 1024 / 1024).toFixed(1)} MB` : line. 1024 / 1024).toFixed(1)} MB` : `${([Link] /
`${([Link] / 1024).toFixed(...` 1024).t
91 ` </div>` Source code </div>
line.
92 ` <div className="w-20 shrink-0 text- Source code <div className="w-20 shrink-0 text-
right">{[Link]}s</div>` line. right">{[Link]}s</div>
93 ` <div className="w-16 shrink-0 text- Source code <div className="w-16 shrink-0 text-center">
center">` line.
94 ` <span className="px-1.5 py-0.5 Source code <span className="px-1.5 py-0.5 rounded
rounded text-[10px] font-bold text-[var(--bg- line. text-[10px] font-bold text-[var(--bg-void)]"
void)]" style={{ backgroundColo...` style={{ backgro
95 ` {[Link]}` Source code {[Link]}
line.
96 ` </span>` Source code </span>
line.

Page 540 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
97 ` </div>` Source code </div>
line.
98 ` <div className="w-24 shrink-0 flex Source code <div className="w-24 shrink-0 flex items-
items-center gap-1.5 pl-2">` line. center gap-1.5 pl-2">
99 ` <div` Source code <div
line.
100 ` className={`w-2 h-2 rounded-full Source code className={`w-2 h-2 rounded-full
${[Link] === 'active' ? 'animate-pulse' : line. ${[Link] === 'active' ? 'animate-pulse' :
''}`}` ''}`}
101 ` style={{ backgroundColor: Source code style={{ backgroundColor:
STATUS_COLORS[[Link]] ?? 'var(--text- line. STATUS_COLORS[[Link]] ?? 'var(--text-
muted)' }}` muted)' }}
102 ` />` Source code />
line.
103 ` <span className="text-[9px] uppercase Source code <span className="text-[9px] uppercase
tracking-wider font-mono" style={{ color: line. tracking-wider font-mono" style={{ color:
STATUS_COLORS[[Link]] }}>` STATUS_COLORS[flow.s
104 ` {[Link]}` Source code {[Link]}
line.
105 ` </span>` Source code </span>
line.
106 ` </div>` Source code </div>
line.
107 ` {[Link] && (` Source code {[Link] && (
line.
108 ` <div className="flex-1 text-right pr-2 Source code <div className="flex-1 text-right pr-2 text-
text-[10px] text-[var(--text-muted)] truncate">` line. [10px] text-[var(--text-muted)] truncate">
109 ` {[Link]}` Source code {[Link]}
line.
110 ` </div>` Source code </div>
line.
111 ` )}` Source code )}
line.
112 ` </div>` Source code </div>
line.
113 ` );` Executable );
statement.
114 ` }, [filteredFlows, selectedFlowId, Executable }, [filteredFlows, selectedFlowId,
getScoreColor]);` statement. getScoreColor]);
115 `` Blank line for Separator between code blocks.
readability.
116 ` return (` Exit function return (
and give back
a value.
117 ` <div className="h-full flex flex-col bg-[var(- Source code <div className="h-full flex flex-col bg-[var(--
-bg-void)] text-[var(--text-primary)] overflow- line. bg-void)] text-[var(--text-primary)] overflow-
hidden">` hidden"
118 ` {/* Header */}` Source code {/* Header */}
line.

Page 541 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
119 ` <div className="h-14 border-b border- Source code <div className="h-14 border-b border-[var(--
[var(--border-default)] bg-[var(--bg-base)] flex line. border-default)] bg-[var(--bg-base)] flex items-
items-center px-4 justify...` center p
120 ` <h1 className="text-lg font-bold font- Source code <h1 className="text-lg font-bold font-sans
sans flex items-center gap-2">` line. flex items-center gap-2">
121 ` <GitMerge className="w-5 h-5 text- Source code <GitMerge className="w-5 h-5 text-[var(--
[var(--accent)]" />` line. accent)]" />
122 ` Flow Inspector` Source code Flow Inspector
line.
123 ` {isLoading && <Loader2 className="w- Source code {isLoading && <Loader2 className="w-4 h-4
4 h-4 animate-spin text-[var(--text-muted)]" />}` line. animate-spin text-[var(--text-muted)]" />}
124 ` <span className="text-xs font-normal Source code <span className="text-xs font-normal text-
text-[var(--text-muted)] ml-1">` line. [var(--text-muted)] ml-1">
125 ` {[Link]}/{[Link]} Source code {[Link]}/{[Link]} flows
flows` line.
126 ` </span>` Source code </span>
line.
127 ` </h1>` Source code </h1>
line.
128 `` Blank line for Separator between code blocks.
readability.
129 ` {/* Status filter pills */}` Source code {/* Status filter pills */}
line.
130 ` <div className="flex items-center gap-2 Source code <div className="flex items-center gap-2 ml-
ml-4">` line. 4">
131 ` Source code {[Link](statusCounts).map(([status,
{[Link](statusCounts).map(([status, line. count]) => (
count]) => (`
132 ` <button` Source code <button
line.
133 ` key={status}` Source code key={status}
line.
134 ` onClick={() => Source code onClick={() => setStatusFilter(statusFilter ===
setStatusFilter(statusFilter === status ? null : line. status ? null : status)}
status)}`
135 ` className={`flex items-center gap- Source code className={`flex items-center gap-1.5 px-2
1.5 px-2 py-0.5 rounded text-[10px] font-mono line. py-0.5 rounded text-[10px] font-mono border
border transition-color...` transition-co
136 ` style={{ color: statusFilter === status Source code style={{ color: statusFilter === status ?
? STATUS_COLORS[status] : undefined }}` line. STATUS_COLORS[status] : undefined }}
137 ` >` Source code >
line.
138 ` <div className="w-1.5 h-1.5 Source code <div className="w-1.5 h-1.5 rounded-full"
rounded-full" style={{ backgroundColor: line. style={{ backgroundColor:
STATUS_COLORS[status] }} />` STATUS_COLORS[status] }} />
139 ` <span Source code <span
className="uppercase">{status}</span>` line. className="uppercase">{status}</span>
140 ` <span className="font- Source code <span className="font-bold">{count}</span>
bold">{count}</span>` line.

Page 542 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
141 ` </button>` Source code </button>
line.
142 ` ))}` Source code ))}
line.
143 ` </div>` Source code </div>
line.
144 `` Blank line for Separator between code blocks.
readability.
145 ` <div className="relative ml-auto">` Source code <div className="relative ml-auto">
line.
146 ` <Filter className="absolute left-2.5 Source code <Filter className="absolute left-2.5 top-1/2 -
top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-[var(-- line. translate-y-1/2 w-3.5 h-3.5 text-[var(--text-
text-muted)]" />` muted)]"
147 ` <input` Source code <input
line.
148 ` type="text"` Source code type="text"
line.
149 ` value={search}` Source code value={search}
line.
150 ` onChange={e => Source code onChange={e => setSearch([Link])}
setSearch([Link])}` line.
151 ` placeholder="Search IP, port, protocol, Source code placeholder="Search IP, port, protocol,
country…"` line. country…"
152 ` className="h-8 bg-[var(--bg-overlay)] Source code className="h-8 bg-[var(--bg-overlay)] border
border border-[var(--border-strong)] rounded line. border-[var(--border-strong)] rounded text-xs
text-xs px-8 focus:out...` px-8 focu
153 ` />` Source code />
line.
154 ` {search && (` Source code {search && (
line.
155 ` <button className="absolute right-2.5 Source code <button className="absolute right-2.5 top-1/2
top-1/2 -translate-y-1/2 text-[var(--text-muted)] line. -translate-y-1/2 text-[var(--text-muted)]
hover:text-[var(-...` hover:text-[
156 ` onClick={() => setSearch('')}>` Source code onClick={() => setSearch('')}>
line.
157 ` <X className="w-3.5 h-3.5" />` Source code <X className="w-3.5 h-3.5" />
line.
158 ` </button>` Source code </button>
line.
159 ` )}` Source code )}
line.
160 ` </div>` Source code </div>
line.

Line Source Easy Technical Explanation


Explanation
161 ` </div>` Source code </div>
line.

Page 543 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
162 `` Blank line for Separator between code blocks.
readability.
163 ` <div className="flex-1 flex relative Source code <div className="flex-1 flex relative
overflow-hidden">` line. overflow-hidden">
164 ` <div className="flex-1 flex flex-col Source code <div className="flex-1 flex flex-col
overflow-hidden">` line. overflow-hidden">
165 ` {/* Column headers */}` Source code {/* Column headers */}
line.
166 ` <div className="flex bg-[var(--bg- Source code <div className="flex bg-[var(--bg-
overlay)] border-b border-[var(--border- line. overlay)] border-b border-[var(--border-
strong)] text-xs font-mono font-b...` strong)] text-xs font-mono
167 ` <div className="w-56 pl- Source code <div className="w-56 pl-2">Source</div>
2">Source</div>` line.
168 ` <div className="w-8 text- Source code <div className="w-8 text-center"></div>
center"></div>` line.
169 ` <div className="w- Source code <div className="w-56">Destination</div>
56">Destination</div>` line.
170 ` <div className="w- Source code <div className="w-20">Proto</div>
20">Proto</div>` line.
171 ` <div className="w-24 text- Source code <div className="w-24 text-
right">Packets</div>` line. right">Packets</div>
172 ` <div className="w-28 text- Source code <div className="w-28 text-
right">Bytes</div>` line. right">Bytes</div>
173 ` <div className="w-20 text- Source code <div className="w-20 text-
right">Duration</div>` line. right">Duration</div>
174 ` <div className="w-16 text- Source code <div className="w-16 text-
center">Score</div>` line. center">Score</div>
175 ` <div className="w-24 pl- Source code <div className="w-24 pl-2">Status</div>
2">Status</div>` line.
176 ` <div className="flex-1 text-right Source code <div className="flex-1 text-right pr-
pr-2">Country</div>` line. 2">Country</div>
177 ` </div>` Source code </div>
line.
178 `` Blank line for Separator between code blocks.
readability.
179 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-hidden"
hidden" ref={listContainerRef}>` line. ref={listContainerRef}>
180 ` {[Link] === 0 && !isLoading ? Source code {[Link] === 0 && !isLoading ? (
(` line.
181 ` <div className="flex flex-col Source code <div className="flex flex-col items-center
items-center justify-center h-full text-[var(-- line. justify-center h-full text-[var(--text-muted)]
text-muted)] opacity-50 ga...` opacity-50
182 ` <GitMerge className="w-12 h- Source code <GitMerge className="w-12 h-12"
12" strokeWidth={1} />` line. strokeWidth={1} />
183 ` <span className="font-mono Source code <span className="font-mono text-sm">No
text-sm">No flows detected yet</span>` line. flows detected yet</span>
184 ` <span className="font-sans Source code <span className="font-sans text-
text-xs">Start capture to see network line. xs">Start capture to see network
flows</span>` flows</span>

Page 544 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
185 ` </div>` Source code </div>
line.
186 ` ) : (` Source code ):(
line.
187 ` <List` Source code <List
line.
188 ` height={listHeight}` Source code height={listHeight}
line.
189 ` itemCount={[Link]}` Source code itemCount={[Link]}
line.
190 ` itemSize={() => 32}` Source code itemSize={() => 32}
line.
191 ` width="100%"` Source code width="100%"
line.
192 ` >` Source code >
line.
193 ` {Row}` Source code {Row}
line.
194 ` </List>` Source code </List>
line.
195 ` )}` Source code )}
line.
196 ` </div>` Source code </div>
line.
197 ` </div>` Source code </div>
line.
198 `` Blank line for Separator between code blocks.
readability.
199 ` {/* Slide-in Detail Panel */}` Source code {/* Slide-in Detail Panel */}
line.
200 ` <div className={`w-[480px] border-l Source code <div className={`w-[480px] border-l
border-[var(--border-strong)] bg-[var(--bg- line. border-[var(--border-strong)] bg-[var(--bg-
base)] flex flex-col shrink-0 ...` base)] flex flex-col
201 ` {selectedFlow && (` Source code {selectedFlow && (
line.
202 ` <>` Source code <>
line.
203 ` <div className="h-14 border-b Source code <div className="h-14 border-b border-
border-[var(--border-strong)] flex items- line. [var(--border-strong)] flex items-center
center justify-between px-4 shri...` justify-between px-4 s
204 ` <span className="font-mono Source code <span className="font-mono font-bold
font-bold text-sm tracking-wider">Flow line. text-sm tracking-wider">Flow
Analysis</span>` Analysis</span>
205 ` <Button variant="ghost" Source code <Button variant="ghost" size="icon"
size="icon" onClick={() => line. onClick={() => setSelectedFlowId(null)}
setSelectedFlowId(null)} className="hover:bg-[var
className="hover:bg-[var(...`
206 ` <X className="w-4 h-4" />` Source code <X className="w-4 h-4" />
line.

Page 545 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
207 ` </Button>` Source code </Button>
line.
208 ` </div>` Source code </div>
line.
209 `` Blank line for Separator between code blocks.
readability.
210 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-auto p-4
auto p-4 flex flex-col gap-5">` line. flex flex-col gap-5">
211 ` {/* 5-Tuple Card */}` Source code {/* 5-Tuple Card */}
line.
212 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-void)] border
void)] border border-[var(--border-strong)] line. border-[var(--border-strong)] rounded p-4
rounded p-4 flex flex-col it...` flex flex-col i
213 ` <div className="absolute Source code <div className="absolute inset-0 bg-
inset-0 bg-scan-lines opacity-20 pointer- line. scan-lines opacity-20 pointer-events-none"
events-none" />` />
214 ` <div className="flex items- Source code <div className="flex items-center gap-4
center gap-4 w-full justify-between font- line. w-full justify-between font-mono text-sm">
mono text-sm">`
215 ` <div className="flex flex-col Source code <div className="flex flex-col text-right">
text-right">` line.
216 ` <span className="text-[var(- Source code <span className="text-[var(--text-
-text-secondary)] text-xs mb-1 uppercase line. secondary)] text-xs mb-1 uppercase
tracking-widest">Source</s...` tracking-widest">Source</span>
217 ` <span className="font-bold Source code <span className="font-bold text-[var(--
text-[var(--text- line. text-
primary)]">{[Link]}</span>` primary)]">{[Link]}</span>
218 ` <span className="text-[var(- Source code <span className="text-[var(--
-accent)]">Port line. accent)]">Port
{[Link]}</span>` {[Link]}</span>
219 ` </div>` Source code </div>
line.
220 ` <div className="flex flex-col Source code <div className="flex flex-col items-
items-center">` line. center">
221 ` <span className="text-[var(- Source code <span className="text-[var(--text-muted)]
-text-muted)] text-[10px] mb- line. text-[10px] mb-
1">{[Link]}</span>` 1">{[Link]}</span>
222 ` <div className="h-px w-16 Source code <div className="h-px w-16 bg-gradient-
bg-gradient-to-r from-[var(--border-strong)] line. to-r from-[var(--border-strong)] via-[var(--
via-[var(--accent)] to-[...` accent)] to-[var(-
223 ` </div>` Source code </div>
line.
224 ` <div className="flex flex-col Source code <div className="flex flex-col text-left">
text-left">` line.
225 ` <span className="text-[var(- Source code <span className="text-[var(--text-
-text-secondary)] text-xs mb-1 uppercase line. secondary)] text-xs mb-1 uppercase
tracking-widest">Destinati...` tracking-widest">Destination</s
226 ` <span className="font-bold Source code <span className="font-bold text-[var(--
text-[var(--text- line. text-
primary)]">{[Link]}</span>` primary)]">{[Link]}</span>

Page 546 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
227 ` <span className="text-[var(- Source code <span className="text-[var(--
-accent)]">Port line. accent)]">Port
{[Link]}</span>` {[Link]}</span>
228 ` </div>` Source code </div>
line.
229 ` </div>` Source code </div>
line.
230 ` {[Link] && (` Source code {[Link] && (
line.
231 ` <div className="mt-3 text- Source code <div className="mt-3 text-[10px] font-
[10px] font-mono text-[var(--text-muted)]">` line. mono text-[var(--text-muted)]">
232 ` 🌍 {[Link]}` Source code 🌍 {[Link]}
line.
233 ` {[Link] && Source code {[Link] && [Link] && `
[Link] && ` · line. · ${[Link](2)},
${[Link](2)}, ${[Link]
${[Link]...`
234 ` </div>` Source code </div>
line.
235 ` )}` Source code )}
line.
236 ` </div>` Source code </div>
line.
237 `` Blank line for Separator between code blocks.
readability.
238 ` {/* Stats Grid */}` Source code {/* Stats Grid */}
line.
239 ` <div className="grid grid-cols-2 Source code <div className="grid grid-cols-2 gap-3">
gap-3">` line.
240 ` {[` Source code {[
line.

Lin Source Easy Technical Explanation


e Explanation
241 ` { label: 'Packets', value: Source code { label: 'Packets', value:
[Link]() },` line. [Link]() },
242 ` { label: 'Data Transferred', value: Source code { label: 'Data Transferred', value:
[Link] > 1024 * 1024 ? line. [Link] > 1024 * 1024 ?
`${([Link] / 1...` `${([Link] / 1024
243 ` { label: 'Duration', value: Source code { label: 'Duration', value:
`${[Link]}s` },` line. `${[Link]}s` },
244 ` { label: 'Avg Packet Size', value: Source code { label: 'Avg Packet Size', value:
`${[Link] > 0 ? line. `${[Link] > 0 ?
[Link]([Link] / ...` [Link]([Link] / sel
245 ` ].map(({ label, value }) => (` Source code ].map(({ label, value }) => (
line.
246 ` <div key={label} className="bg- Source code <div key={label} className="bg-[var(--bg-
[var(--bg-overlay)] border border-[var(--border- line. overlay)] border border-[var(--border-subtle)]
subtle)] rounded p...` rounded p-3

Page 547 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
247 ` <div className="text-[10px] Source code <div className="text-[10px] text-[var(--text-
text-[var(--text-muted)] font-mono uppercase line. muted)] font-mono uppercase tracking-widest
tracking-widest mb-1">...` mb-1">{labe
248 ` <div className="text-xl font- Source code <div className="text-xl font-space font-
space font-bold">{value}</div>` line. bold">{value}</div>
249 ` </div>` Source code </div>
line.
250 ` ))}` Source code ))}
line.
251 ` </div>` Source code </div>
line.
252 `` Blank line for Separator between code blocks.
readability.
253 ` {/* Threat Score */}` Source code {/* Threat Score */}
line.
254 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)] border
overlay)] border border-[var(--border-subtle)] line. border-[var(--border-subtle)] rounded p-3"
rounded p-3"`
255 ` style={{ borderBottomColor: Source code style={{ borderBottomColor:
getScoreColor([Link]), line. getScoreColor([Link]),
borderBottomWidth: 2 }}>` borderBottomWidth: 2 }}>
256 ` <div className="text-[10px] text- Source code <div className="text-[10px] text-[var(--text-
[var(--text-muted)] font-mono uppercase line. muted)] font-mono uppercase tracking-widest
tracking-widest mb-2">Thre...` mb-2">Threa
257 ` <div className="flex items-center Source code <div className="flex items-center gap-3">
gap-3">` line.
258 ` <div className="flex-1 h-2 bg- Source code <div className="flex-1 h-2 bg-[var(--bg-base)]
[var(--bg-base)] rounded-full overflow-hidden">` line. rounded-full overflow-hidden">
259 ` <div className="h-full rounded- Source code <div className="h-full rounded-full transition-
full transition-all"` line. all"
260 ` style={{ width: Source code style={{ width: `${[Link]}%`,
`${[Link]}%`, line. backgroundColor:
backgroundColor: getScoreColor([Link]
getScoreColor(selectedFlow.t...`
261 ` </div>` Source code </div>
line.
262 ` <span className="font-space Source code <span className="font-space font-bold text-lg"
font-bold text-lg" style={{ color: line. style={{ color:
getScoreColor([Link]...` getScoreColor([Link]
263 ` {[Link]}/100` Source code {[Link]}/100
line.
264 ` </span>` Source code </span>
line.
265 ` </div>` Source code </div>
line.
266 ` </div>` Source code </div>
line.
267 `` Blank line for Separator between code blocks.
readability.

Page 548 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
268 ` {/* Status */}` Source code {/* Status */}
line.
269 ` <div className="flex items-center Source code <div className="flex items-center gap-3 p-3
gap-3 p-3 bg-[var(--bg-overlay)] border border- line. bg-[var(--bg-overlay)] border border-[var(--
[var(--border-subtle...` border-subtl
270 ` <div className="w-3 h-3 rounded- Source code <div className="w-3 h-3 rounded-full" style={{
full" style={{ backgroundColor: line. backgroundColor:
STATUS_COLORS[[Link]] ...` STATUS_COLORS[[Link]] }
271 ` <span className="font-mono font- Source code <span className="font-mono font-bold text-sm
bold text-sm uppercase" style={{ color: line. uppercase" style={{ color:
STATUS_COLORS[selectedFlow....` STATUS_COLORS[selectedFlow.s
272 ` {[Link]}` Source code {[Link]}
line.
273 ` </span>` Source code </span>
line.
274 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-muted)] text-
muted)] text-xs">flow state</span>` line. xs">flow state</span>
275 ` </div>` Source code </div>
line.
276 ` </div>` Source code </div>
line.
277 `` Blank line for Separator between code blocks.
readability.
278 ` <div className="p-4 border-t border- Source code <div className="p-4 border-t border-[var(--
[var(--border-strong)] bg-[var(--bg-overlay)] flex line. border-strong)] bg-[var(--bg-overlay)] flex gap-2
gap-2 shrink-0">` shrink-
279 ` <Button` Source code <Button
line.
280 ` className="flex-1 bg-[var(-- Source code className="flex-1 bg-[var(--accent)] text-[var(--
accent)] text-[var(--bg-void)] hover:brightness- line. bg-void)] hover:brightness-110 font-bold text-xs
110 font-bold text-xs h-8"` h-
281 ` onClick={() => {` Source code onClick={() => {
line.
282 ` const filter = \ ${[Link]}`;`
`${[Link]} \
283 ` setDisplayFilter(filter);` Executable setDisplayFilter(filter);
statement.
284 ` Executable [Link]().addRecentFilter(filter);
[Link]().addRecentFilter(filter);` statement.
285 ` setLocation('/');` Executable setLocation('/');
statement.
286 ` toast({ title: 'Filter applied', Executable toast({ title: 'Filter applied', description:
description: `Showing packets for this flow` });` statement. `Showing packets for this flow` });
287 ` }}` Source code }}
line.
288 ` >` Source code >
line.
289 ` <ExternalLink className="w-3 h-3 Source code <ExternalLink className="w-3 h-3 mr-1.5" />
mr-1.5" /> Filter in Packets` line. Filter in Packets

Page 549 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
290 ` </Button>` Source code </Button>
line.
291 ` <Button` Source code <Button
line.
292 ` variant="outline"` Source code variant="outline"
line.
293 ` className="flex-1 border-[var(-- Source code className="flex-1 border-[var(--border-strong)]
border-strong)] text-[var(--text-primary)] line. text-[var(--text-primary)] hover:bg-[var(--bg-
hover:bg-[var(--bg-hover...` hover)
294 ` onClick={() => {` Source code onClick={() => {
line.
295 ` const text = Named const text =
`${[Link]}:${[Link] constant — `${[Link]}:${[Link]
rt} → ${[Link]}:${selecte...` value should rt} → ${selectedFlow.d
not change.
296 ` Executable [Link]?.writeText(text);
[Link]?.writeText(text);` statement.
297 ` toast({ title: 'Copied', description: Executable toast({ title: 'Copied', description: 'Flow info
'Flow info copied to clipboard' });` statement. copied to clipboard' });
298 ` }}` Source code }}
line.
299 ` >` Source code >
line.
300 ` <Copy className="w-3 h-3 mr-1.5" Source code <Copy className="w-3 h-3 mr-1.5" /> Copy
/> Copy Info` line. Info
301 ` </Button>` Source code </Button>
line.
302 ` </div>` Source code </div>
line.
303 ` </>` Source code </>
line.
304 ` )}` Source code )}
line.
305 ` </div>` Source code </div>
line.
306 ` </div>` Source code </div>
line.
307 ` </div>` Source code </div>
line.
308 ` );` Executable );
statement.
309 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 550 of 629


NADS Complete Technical Reference

File: webwireshark/src/pages/[Link]
Total lines: 633

Li Source Easy Technical Explanation


n Expla
e nation
1 `import React, { useState, useEffect } from 'react';` Executa import React, { useState, useEffect } from 'react';
ble
stateme
nt.
2 `import {` Source import {
code
line.
3 ` Settings as SettingsIcon, Save, RefreshCw, Source Settings as SettingsIcon, Save, RefreshCw, Shield,
Shield, Monitor, Camera,` code Monitor, Camera,
line.
4 ` Columns, Palette, Zap, HardDrive, CheckCircle, Source Columns, Palette, Zap, HardDrive, CheckCircle,
AlertCircle, Loader2,` code AlertCircle, Loader2,
line.
5 `} from 'lucide-react';` Executa } from 'lucide-react';
ble
stateme
nt.
6 `import { Button } from '@/components/ui/button';` Executa import { Button } from '@/components/ui/button';
ble
stateme
nt.
7 `import { useAppStore } from Executa import { useAppStore } from '@/store/useAppStore';
'@/store/useAppStore';` ble
stateme
nt.
8 `import { useGetNadsConfig, useGetInterfaces, Executa import { useGetNadsConfig, useGetInterfaces,
saveNadsConfig, recalculateBaseline, resetBaseline ble saveNadsConfig, recalculateBaseline, resetBaseline
} from '@workspace/ap...` stateme } fr
nt.
9 `import { useToast } from '@/hooks/use-toast';` Executa import { useToast } from '@/hooks/use-toast';
ble
stateme
nt.
10 `import type { DetectorConfig } from Executa import type { DetectorConfig } from
'@workspace/api-client-react';` ble '@workspace/api-client-react';
stateme
nt.
11 `` Blank Separator between code blocks.
line for
readabil
ity.
12 `// ─── Reusable field components Comme ─── Reusable field components
───────────────────────────────── nt ────────────────────────────────
───────────────` docume ────────────────
nting
intent.
13 `` Blank Separator between code blocks.
line for

Page 551 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
readabil
ity.
14 `function ToggleSwitch({ checked, onChange }: { Source function ToggleSwitch({ checked, onChange }: {
checked: boolean; onChange: (v: boolean) => void }) code checked: boolean; onChange: (v: boolean) => void
{` line. }) {
15 ` return (` Exit return (
function
and
give
back a
value.
16 ` <button` Source <button
code
line.
17 ` role="switch"` Source role="switch"
code
line.
18 ` aria-checked={checked}` Source aria-checked={checked}
code
line.
19 ` onClick={() => onChange(!checked)}` Source onClick={() => onChange(!checked)}
code
line.
20 ` style={{` Source style={{
code
line.
21 ` width: 40,` Source width: 40,
code
line.
22 ` height: 22,` Source height: 22,
code
line.
23 ` borderRadius: 11,` Source borderRadius: 11,
code
line.
24 ` backgroundColor: checked ? '#FF5949' : Source backgroundColor: checked ? '#FF5949' : '#444',
'#444',` code
line.
25 ` border: checked ? 'none' : '1px solid #555',` Source border: checked ? 'none' : '1px solid #555',
code
line.
26 ` display: 'flex',` Source display: 'flex',
code
line.
27 ` alignItems: 'center',` Source alignItems: 'center',
code
line.
28 ` padding: '2px',` Source padding: '2px',
code
line.

Page 552 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
29 ` cursor: 'pointer',` Source cursor: 'pointer',
code
line.
30 ` transition: 'background-color 0.2s',` Source transition: 'background-color 0.2s',
code
line.
31 ` flexShrink: 0,` Source flexShrink: 0,
code
line.
32 ` }}` Source }}
code
line.
33 ` >` Source >
code
line.
34 ` <div` Source <div
code
line.
35 ` style={{` Source style={{
code
line.
36 ` width: 18,` Source width: 18,
code
line.
37 ` height: 18,` Source height: 18,
code
line.
38 ` borderRadius: '50%',` Source borderRadius: '50%',
code
line.
39 ` backgroundColor: '#fff',` Source backgroundColor: '#fff',
code
line.
40 ` boxShadow: '0 1px 3px rgba(0,0,0,0.4)',` Source boxShadow: '0 1px 3px rgba(0,0,0,0.4)',
code
line.
41 ` transform: checked ? 'translateX(18px)' : Source transform: checked ? 'translateX(18px)' :
'translateX(0px)',` code 'translateX(0px)',
line.
42 ` transition: 'transform 0.2s',` Source transition: 'transform 0.2s',
code
line.
43 ` }}` Source }}
code
line.
44 ` />` Source />
code
line.
45 ` </button>` Source </button>
code
line.

Page 553 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
46 ` );` Executa );
ble
stateme
nt.
47 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
48 `` Blank Separator between code blocks.
line for
readabil
ity.
49 `function SettingRow({` Source function SettingRow({
code
line.
50 ` label, description, children,` Source label, description, children,
code
line.
51 `}: { label: string; description?: string; children: Source }: { label: string; description?: string; children:
[Link] }) {` code [Link] }) {
line.
52 ` return (` Exit return (
function
and
give
back a
value.
53 ` <div className="flex items-center justify- Source <div className="flex items-center justify-between
between gap-6 py-3 border-b border-[var(--border- code gap-6 py-3 border-b border-[var(--border-subtle)]
subtle)] last:border-0">` line.
54 ` <div className="flex flex-col min-w-0">` Source <div className="flex flex-col min-w-0">
code
line.
55 ` <span className="text-sm font-medium text- Source <span className="text-sm font-medium text-[var(--
[var(--text-primary)]">{label}</span>` code text-primary)]">{label}</span>
line.
56 ` {description && <span className="text-xs Source {description && <span className="text-xs text-
text-[var(--text-muted)] mt- code [var(--text-muted)] mt-0.5">{description}</span>}
0.5">{description}</span>}` line.
57 ` </div>` Source </div>
code
line.
58 ` <div className="shrink-0">{children}</div>` Source <div className="shrink-0">{children}</div>
code
line.
59 ` </div>` Source </div>
code
line.
60 ` );` Executa );
ble

Page 554 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
stateme
nt.
61 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/
opening
a block.
62 `` Blank Separator between code blocks.
line for
readabil
ity.
63 `function SectionHeader({ icon: Icon, title, Source function SectionHeader({ icon: Icon, title, description
description }: { icon: any; title: string; description?: code }: { icon: any; title: string; description?:
string }) {` line.
64 ` return (` Exit return (
function
and
give
back a
value.
65 ` <div className="mb-6">` Source <div className="mb-6">
code
line.
66 ` <h2 className="text-base font-bold flex items- Source <h2 className="text-base font-bold flex items-
center gap-2">` code center gap-2">
line.
67 ` <Icon className="w-5 h-5 text-[var(--accent)]" Source <Icon className="w-5 h-5 text-[var(--accent)]" />
/>` code
line.
68 ` {title}` Source {title}
code
line.
69 ` </h2>` Source </h2>
code
line.
70 ` {description && <p className="text-[var(--text- Source {description && <p className="text-[var(--text-
muted)] text-sm mt-1">{description}</p>}` code muted)] text-sm mt-1">{description}</p>}
line.
71 ` </div>` Source </div>
code
line.
72 ` );` Executa );
ble
stateme
nt.
73 `}` Brace C/C++ syntax structure.
or
parenth
esis
closing/

Page 555 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


n Expla
e nation
opening
a block.
74 `` Blank Separator between code blocks.
line for
readabil
ity.
75 `// ─── Tab panels Comme ─── Tab panels
───────────────────────────────── nt ────────────────────────────────
──────────────────────────────` docume ───────────────────────────────
nting
intent.
76 `` Blank Separator between code blocks.
line for
readabil
ity.
77 `function AppearancePanel() {` Source function AppearancePanel() {
code
line.
78 ` const { theme, setTheme, colorRulesEnabled, Named const { theme, setTheme, colorRulesEnabled,
setColorRulesEnabled, scrollToNew, constan setColorRulesEnabled, scrollToNew, s
setScrollToNew, showRelativeTime, se...` t—
value
should
not
change.
79 ` const { toast } = useToast();` Named const { toast } = useToast();
constan
t—
value
should
not
change.
80 `` Blank Separator between code blocks.
line for
readabil
ity.

Line Source Easy Technical Explanation


Explanation
81 ` const themes = [` Named constant const themes = [
— value should
not change.
82 ` { id: 'dark', label: 'Dark (Default)', Source code line. { id: 'dark', label: 'Dark (Default)',
preview: 'bg-gray-900' },` preview: 'bg-gray-900' },
83 ` { id: 'darker', label: 'Deep Black', Source code line. { id: 'darker', label: 'Deep Black',
preview: 'bg-black' },` preview: 'bg-black' },
84 ` { id: 'light', label: 'Light', preview: 'bg- Source code line. { id: 'light', label: 'Light', preview: 'bg-
gray-100 border border-gray-300' },` gray-100 border border-gray-300' },
85 ` ];` Executable ];
statement.
86 `` Blank line for Separator between code blocks.
readability.

Page 556 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
87 ` return (` Exit function and return (
give back a value.
88 ` <div className="space-y-8 animate-in Source code line. <div className="space-y-8 animate-in
fade-in slide-in-from-bottom-4 duration- fade-in slide-in-from-bottom-4 duration-
300">` 300">
89 ` <SectionHeader icon={Palette} Source code line. <SectionHeader icon={Palette}
title="Theme" description="Choose the title="Theme" description="Choose the
application color scheme." />` application color scheme." />
90 ` <div className="flex gap-3 mb-6">` Source code line. <div className="flex gap-3 mb-6">
91 ` {[Link](t => (` Source code line. {[Link](t => (
92 ` <button` Source code line. <button
93 ` key={[Link]}` Source code line. key={[Link]}
94 ` onClick={() => { setTheme([Link]); Source code line. onClick={() => { setTheme([Link]); toast({
toast({ title: `Theme: ${[Link]}` }); }}` title: `Theme: ${[Link]}` }); }}
95 ` className={`flex flex-col items- Source code line. className={`flex flex-col items-center
center gap-2 p-3 rounded border gap-2 p-3 rounded border transition-
transition-colors ${theme === [Link] ? 'bor...` colors ${theme === [Link] ?
96 ` >` Source code line. >
97 ` <div className={`w-16 h-10 Source code line. <div className={`w-16 h-10 rounded
rounded ${[Link]}`} />` ${[Link]}`} />
98 ` <span className="text-xs font- Source code line. <span className="text-xs font-mono
mono text-[var(--text- text-[var(--text-
secondary)]">{[Link]}</span>` secondary)]">{[Link]}</span>
99 ` {theme === [Link] && <CheckCircle Source code line. {theme === [Link] && <CheckCircle
className="w-3.5 h-3.5 text-[var(-- className="w-3.5 h-3.5 text-[var(--
accent)]" />}` accent)]" />}
100 ` </button>` Source code line. </button>
101 ` ))}` Source code line. ))}
102 ` </div>` Source code line. </div>
103 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- border border-[var(--border-subtle)]
subtle)] rounded p-4">` rounded p-4">
104 ` <SettingRow label="Protocol Color Source code line. <SettingRow label="Protocol Color
Rules" description="Color-code packets by Rules" description="Color-code packets
protocol in capture view.">` by protocol in capture view
105 ` <ToggleSwitch Source code line. <ToggleSwitch
checked={colorRulesEnabled} checked={colorRulesEnabled}
onChange={setColorRulesEnabled} />` onChange={setColorRulesEnabled} />
106 ` </SettingRow>` Source code line. </SettingRow>
107 ` <SettingRow label="Auto-scroll to Source code line. <SettingRow label="Auto-scroll to New
New Packets" description="Automatically Packets" description="Automatically
scroll to newest packet during capt...` scroll to newest packet du
108 ` <ToggleSwitch Source code line. <ToggleSwitch checked={scrollToNew}
checked={scrollToNew} onChange={setScrollToNew} />
onChange={setScrollToNew} />`
109 ` </SettingRow>` Source code line. </SettingRow>
110 ` <SettingRow label="Relative Source code line. <SettingRow label="Relative
Timestamps" description="Show packet Timestamps" description="Show packet
timestamps relative to first packet.">` timestamps relative to first packet

Page 557 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
111 ` <ToggleSwitch Source code line. <ToggleSwitch
checked={showRelativeTime} checked={showRelativeTime}
onChange={setShowRelativeTime} />` onChange={setShowRelativeTime} />
112 ` </SettingRow>` Source code line. </SettingRow>
113 ` <SettingRow label="Resolve DNS Source code line. <SettingRow label="Resolve DNS
Names" description="Attempt to resolve IP Names" description="Attempt to resolve
addresses to hostnames.">` IP addresses to hostnames.">
114 ` <ToggleSwitch Source code line. <ToggleSwitch
checked={resolveNames} checked={resolveNames}
onChange={setResolveNames} />` onChange={setResolveNames} />
115 ` </SettingRow>` Source code line. </SettingRow>
116 ` </div>` Source code line. </div>
117 ` </div>` Source code line. </div>
118 ` );` Executable );
statement.
119 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
120 `` Blank line for Separator between code blocks.
readability.
121 `function CaptureDefaultsPanel() {` Source code line. function CaptureDefaultsPanel() {
122 ` const { captureInterface, Named constant const { captureInterface,
setCaptureInterface, captureFilter, — value should setCaptureInterface, captureFilter,
setCaptureFilter, maxPackets, not change. setCaptureFilter,
setMaxPackets } = useAp...`
123 ` const { data: interfaces = [], isError: Named constant const { data: interfaces = [], isError:
ifaceError } = useGetInterfaces();` — value should ifaceError } = useGetInterfaces();
not change.
124 ` const { toast } = useToast();` Named constant const { toast } = useToast();
— value should
not change.
125 ` const [localFilter, setLocalFilter] = Named constant const [localFilter, setLocalFilter] =
useState(captureFilter);` — value should useState(captureFilter);
not change.
126 ` const [localMax, setLocalMax] = Named constant const [localMax, setLocalMax] =
useState(String(maxPackets));` — value should useState(String(maxPackets));
not change.
127 `` Blank line for Separator between code blocks.
readability.
128 ` const handleSave = () => {` Named constant const handleSave = () => {
— value should
not change.
129 ` setCaptureFilter(localFilter);` Executable setCaptureFilter(localFilter);
statement.
130 ` const n = parseInt(localMax);` Named constant const n = parseInt(localMax);
— value should
not change.
131 ` if (!isNaN(n) && n > 0) Conditional if (!isNaN(n) && n > 0)
setMaxPackets(n);` branch — run setMaxPackets(n);

Page 558 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
code only when
condition true.
132 ` toast({ title: 'Capture defaults saved', Executable toast({ title: 'Capture defaults saved',
description: 'Settings will apply on next statement. description: 'Settings will apply on next
capture start.' });` capture start.' }
133 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
134 `` Blank line for Separator between code blocks.
readability.
135 ` return (` Exit function and return (
give back a value.
136 ` <div className="space-y-6 animate-in Source code line. <div className="space-y-6 animate-in
fade-in slide-in-from-bottom-4 duration- fade-in slide-in-from-bottom-4 duration-
300">` 300">
137 ` <SectionHeader icon={Camera} Source code line. <SectionHeader icon={Camera}
title="Capture Defaults" title="Capture Defaults"
description="These settings apply when description="These settings apply when
you start a new ca...` you sta
138 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- border border-[var(--border-subtle)]
subtle)] rounded p-4 space-y-4">` rounded p-4 space-y-4">
139 ` {/* Interface */}` Source code line. {/* Interface */}
140 ` <div>` Source code line. <div>
141 ` <label className="text-xs font- Source code line. <label className="text-xs font-bold
bold uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--text-
text-muted)] font-mono block mb-1.5">` muted)] font-mono bloc
142 ` Network Interface` Source code line. Network Interface
143 ` </label>` Source code line. </label>
144 ` {ifaceError ? (` Source code line. {ifaceError ? (
145 ` <div className="flex items- Source code line. <div className="flex items-center gap-
center gap-2 text-xs text-[var(--medium)] 2 text-xs text-[var(--medium)] font-
font-mono">` mono">
146 ` <AlertCircle className="w-4 h- Source code line. <AlertCircle className="w-4 h-4" />
4" />`
147 ` Backend offline — interface list Source code line. Backend offline — interface list
unavailable` unavailable
148 ` </div>` Source code line. </div>
149 ` ) : [Link] === 0 ? (` Source code line. ) : [Link] === 0 ? (
150 ` <div className="flex items- Source code line. <div className="flex items-center gap-
center gap-2 text-xs text-[var(--text- 2 text-xs text-[var(--text-muted)] font-
muted)] font-mono">` mono">
151 ` <Loader2 className="w-3.5 h- Source code line. <Loader2 className="w-3.5 h-3.5
3.5 animate-spin" /> Loading interfaces…` animate-spin" /> Loading interfaces…
152 ` </div>` Source code line. </div>
153 ` ) : (` Source code line. ):(
154 ` <select` Source code line. <select

Page 559 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
155 ` value={captureInterface}` Source code line. value={captureInterface}
156 ` onChange={e => Source code line. onChange={e =>
setCaptureInterface([Link])}` setCaptureInterface([Link])}
157 ` className="w-full h-8 bg-[var(-- Source code line. className="w-full h-8 bg-[var(--bg-
bg-base)] border border-[var(--border- base)] border border-[var(--border-
strong)] rounded text-sm px-3 fon...` strong)] rounded text-sm px-3
158 ` >` Source code line. >
159 ` <option value="">— Select Source code line. <option value="">— Select interface —
interface —</option>` </option>
160 ` {[Link](iface => (` Source code line. {[Link](iface => (

Line Source Easy Technical Explanation


Explanation
161 ` <option key={iface} Source code line. <option key={iface}
value={iface}>{iface}</option>` value={iface}>{iface}</option>
162 ` ))}` Source code line. ))}
163 ` </select>` Source code line. </select>
164 ` )}` Source code line. )}
165 ` {captureInterface && (` Source code line. {captureInterface && (
166 ` <div className="mt-1 text-[10px] Source code line. <div className="mt-1 text-[10px] font-
font-mono text-[var(--normal)]">` mono text-[var(--normal)]">
167 ` ✓ Will capture on: Source code line. ✓ Will capture on: {captureInterface}
{captureInterface}`
168 ` </div>` Source code line. </div>
169 ` )}` Source code line. )}
170 ` </div>` Source code line. </div>
171 `` Blank line for Separator between code blocks.
readability.
172 ` {/* BPF Filter */}` Source code line. {/* BPF Filter */}
173 ` <div>` Source code line. <div>
174 ` <label className="text-xs font- Source code line. <label className="text-xs font-bold
bold uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
text-muted)] font-mono block mb-1.5">` text-muted)] font-mono bloc
175 ` Capture Filter (BPF)` Source code line. Capture Filter (BPF)
176 ` </label>` Source code line. </label>
177 ` <input` Source code line. <input
178 ` type="text"` Source code line. type="text"
179 ` value={localFilter}` Source code line. value={localFilter}
180 ` onChange={e => Source code line. onChange={e =>
setLocalFilter([Link])}` setLocalFilter([Link])}
181 ` placeholder="e.g. tcp port 80, not Source code line. placeholder="e.g. tcp port 80, not arp,
arp, host [Link]"` host [Link]"
182 ` className="w-full h-8 bg-[var(-- Source code line. className="w-full h-8 bg-[var(--bg-
bg-base)] border border-[var(--border- base)] border border-[var(--border-
strong)] rounded text-sm px-3 font-...` strong)] rounded text-sm px-3

Page 560 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
183 ` />` Source code line. />
184 ` <p className="text-[10px] text- Source code line. <p className="text-[10px] text-[var(--
[var(--text-muted)] mt-1 font- text-muted)] mt-1 font-mono">Standard
mono">Standard BPF syntax. Leave BPF syntax. Leave empty
empty to capt...`
185 ` </div>` Source code line. </div>
186 `` Blank line for Separator between code blocks.
readability.
187 ` {/* Max Packets */}` Source code line. {/* Max Packets */}
188 ` <div>` Source code line. <div>
189 ` <label className="text-xs font- Source code line. <label className="text-xs font-bold
bold uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
text-muted)] font-mono block mb-1.5">` text-muted)] font-mono bloc
190 ` Packet Buffer Limit` Source code line. Packet Buffer Limit
191 ` </label>` Source code line. </label>
192 ` <input` Source code line. <input
193 ` type="number"` Source code line. type="number"
194 ` value={localMax}` Source code line. value={localMax}
195 ` onChange={e => Source code line. onChange={e =>
setLocalMax([Link])}` setLocalMax([Link])}
196 ` min={1000}` Source code line. min={1000}
197 ` max={10000000}` Source code line. max={10000000}
198 ` step={1000}` Source code line. step={1000}
199 ` className="w-40 h-8 bg-[var(-- Source code line. className="w-40 h-8 bg-[var(--bg-
bg-base)] border border-[var(--border- base)] border border-[var(--border-
strong)] rounded text-sm px-3 font-mo...` strong)] rounded text-sm px-3 fo
200 ` />` Source code line. />
201 ` <p className="text-[10px] text- Source code line. <p className="text-[10px] text-[var(--
[var(--text-muted)] mt-1 font-mono">Max text-muted)] mt-1 font-mono">Max
packets to keep in memory. Older one...` packets to keep in memory. Ol
202 ` </div>` Source code line. </div>
203 ` </div>` Source code line. </div>
204 ` <Button onClick={handleSave} Source code line. <Button onClick={handleSave}
className="bg-[var(--accent)] text-[var(-- className="bg-[var(--accent)] text-
bg-void)] hover:brightness-110 font- [var(--bg-void)] hover:brightness-11
bold">`
205 ` <Save className="w-4 h-4 mr-2" /> Source code line. <Save className="w-4 h-4 mr-2" />
Save Capture Defaults` Save Capture Defaults
206 ` </Button>` Source code line. </Button>
207 ` </div>` Source code line. </div>
208 ` );` Executable );
statement.
209 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 561 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
210 `` Blank line for Separator between code blocks.
readability.
211 `function ColumnsPanel() {` Source code line. function ColumnsPanel() {
212 ` const { columns, toggleColumnVisible } Named constant — const { columns, toggleColumnVisible }
= useAppStore();` value should not = useAppStore();
change.
213 ` const { toast } = useToast();` Named constant — const { toast } = useToast();
value should not
change.
214 ` return (` Exit function and return (
give back a value.
215 ` <div className="space-y-6 animate-in Source code line. <div className="space-y-6 animate-in
fade-in slide-in-from-bottom-4 duration- fade-in slide-in-from-bottom-4 duration-
300">` 300">
216 ` <SectionHeader icon={Columns} Source code line. <SectionHeader icon={Columns}
title="Packet List Columns" title="Packet List Columns"
description="Toggle which columns description="Toggle which columns
appear in the captu...` appear i
217 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- border border-[var(--border-subtle)]
subtle)] rounded divide-y divide-[var(-- rounded divide-y divide-
bord...`
218 ` {[Link](col => (` Source code line. {[Link](col => (
219 ` <div key={[Link]} className="flex Source code line. <div key={[Link]} className="flex
items-center justify-between px-4 py-3">` items-center justify-between px-4 py-
3">
220 ` <div>` Source code line. <div>
221 ` <span className="text-sm font- Source code line. <span className="text-sm font-
medium text-[var(--text- medium text-[var(--text-
primary)]">{[Link]}</span>` primary)]">{[Link]}</span>
222 ` <span className="ml-2 text- Source code line. <span className="ml-2 text-[10px]
[10px] font-mono text-[var(--text- font-mono text-[var(--text-
muted)]">field: {[Link]}</span>` muted)]">field: {[Link]}</span>
223 ` </div>` Source code line. </div>
224 ` <ToggleSwitch` Source code line. <ToggleSwitch
225 ` checked={[Link]}` Source code line. checked={[Link]}
226 ` onChange={() => {` Source code line. onChange={() => {
227 ` toggleColumnVisible([Link]);` Executable toggleColumnVisible([Link]);
statement.
228 ` toast({ title: `Column Executable toast({ title: `Column "${[Link]}"
"${[Link]}" ${[Link] ? 'hidden' : statement. ${[Link] ? 'hidden' : 'shown'}` });
'shown'}` });`
229 ` }}` Source code line. }}
230 ` />` Source code line. />
231 ` </div>` Source code line. </div>
232 ` ))}` Source code line. ))}
233 ` </div>` Source code line. </div>

Page 562 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
234 ` <p className="text-xs text-[var(-- Source code line. <p className="text-xs text-[var(--text-
text-muted)] font-sans">` muted)] font-sans">
235 ` Changes take effect immediately in Source code line. Changes take effect immediately in the
the capture view.` capture view.
236 ` </p>` Source code line. </p>
237 ` </div>` Source code line. </div>
238 ` );` Executable );
statement.
239 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
240 `` Blank line for Separator between code blocks.
readability.

Lin Source Easy Technical Explanation


e Explanation
241 `const COLOR_RULES = [` Named const COLOR_RULES = [
constant —
value should
not change.
242 ` { name: 'TCP', color: 'var(--proto-tcp)', label: Source code { name: 'TCP', color: 'var(--proto-tcp)', label:
'TCP Packets', bg: '#1a3050' },` line. 'TCP Packets', bg: '#1a3050' },
243 ` { name: 'UDP', color: 'var(--proto-udp)', label: Source code { name: 'UDP', color: 'var(--proto-udp)', label:
'UDP Packets', bg: '#1f2a1a' },` line. 'UDP Packets', bg: '#1f2a1a' },
244 ` { name: 'DNS', color: 'var(--proto-dns)', label: Source code { name: 'DNS', color: 'var(--proto-dns)', label:
'DNS Queries/Responses', bg: '#2a2010' },` line. 'DNS Queries/Responses', bg: '#2a2010' },
245 ` { name: 'HTTP', color: 'var(--proto-http)', label: Source code { name: 'HTTP', color: 'var(--proto-http)', label:
'HTTP Traffic', bg: '#1f2a20' },` line. 'HTTP Traffic', bg: '#1f2a20' },
246 ` { name: 'TLS', color: 'var(--proto-tls)', label: Source code { name: 'TLS', color: 'var(--proto-tls)', label:
'TLS/SSL Encrypted', bg: '#1a1a30' },` line. 'TLS/SSL Encrypted', bg: '#1a1a30' },
247 ` { name: 'ICMP', color: 'var(--proto-icmp)', Source code { name: 'ICMP', color: 'var(--proto-icmp)', label:
label: 'ICMP Echo/Error', bg: '#2a1a1a' },` line. 'ICMP Echo/Error', bg: '#2a1a1a' },
248 ` { name: 'ARP', color: 'var(--proto-arp)', label: Source code { name: 'ARP', color: 'var(--proto-arp)', label:
'ARP Broadcast', bg: '#281e10' },` line. 'ARP Broadcast', bg: '#281e10' },
249 `];` Executable ];
statement.
250 `` Blank line for Separator between code blocks.
readability.
251 `function ColorRulesPanel() {` Source code function ColorRulesPanel() {
line.
252 ` const { colorRulesEnabled, Named const { colorRulesEnabled,
setColorRulesEnabled } = useAppStore();` constant — setColorRulesEnabled } = useAppStore();
value should
not change.
253 ` return (` Exit function return (
and give back
a value.

Page 563 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
254 ` <div className="space-y-6 animate-in Source code <div className="space-y-6 animate-in fade-in
fade-in slide-in-from-bottom-4 duration-300">` line. slide-in-from-bottom-4 duration-300">
255 ` <SectionHeader icon={Palette} title="Color Source code <SectionHeader icon={Palette} title="Color
Rules" description="Protocol-based packet row line. Rules" description="Protocol-based packet row
coloring in the captur...` coloring in
256 ` <div className="flex items-center gap-3 Source code <div className="flex items-center gap-3 p-4
p-4 bg-[var(--bg-overlay)] border border-[var(-- line. bg-[var(--bg-overlay)] border border-[var(--
border-subtle)] rounded">` border-subtl
257 ` <ToggleSwitch Source code <ToggleSwitch checked={colorRulesEnabled}
checked={colorRulesEnabled} line. onChange={setColorRulesEnabled} />
onChange={setColorRulesEnabled} />`
258 ` <span className="text-sm text-[var(-- Source code <span className="text-sm text-[var(--text-
text-primary)]">Color rules {colorRulesEnabled line. primary)]">Color rules {colorRulesEnabled ?
? 'enabled' : 'disabled'}...` 'enabled' : 'd
259 ` </div>` Source code </div>
line.
260 ` <div className="space-y-2">` Source code <div className="space-y-2">
line.
261 ` {COLOR_RULES.map(rule => (` Source code {COLOR_RULES.map(rule => (
line.
262 ` <div` Source code <div
line.
263 ` key={[Link]}` Source code key={[Link]}
line.
264 ` className="flex items-center gap-4 Source code className="flex items-center gap-4 px-4 py-
px-4 py-2.5 rounded border border-[var(-- line. 2.5 rounded border border-[var(--border-subtle)]
border-subtle)] font-mono tex...` font-mon
265 ` style={{ backgroundColor: Source code style={{ backgroundColor: colorRulesEnabled ?
colorRulesEnabled ? [Link] : 'var(--bg- line. [Link] : 'var(--bg-overlay)', opacity:
overlay)', opacity: colorRulesEnabled ?...` colorRulesEnab
266 ` >` Source code >
line.
267 ` <div className="w-3 h-3 rounded-sm Source code <div className="w-3 h-3 rounded-sm shrink-0"
shrink-0" style={{ backgroundColor: [Link] }} line. style={{ backgroundColor: [Link] }} />
/>`
268 ` <span className="w-16 font-bold" Source code <span className="w-16 font-bold" style={{
style={{ color: [Link] }}>{[Link]}</span>` line. color: [Link] }}>{[Link]}</span>
269 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-secondary)]
secondary)] text-xs">{[Link]}</span>` line. text-xs">{[Link]}</span>
270 ` <span className="ml-auto text-[9px] Source code <span className="ml-auto text-[9px] font-
font-mono text-[var(--text-muted)] uppercase line. mono text-[var(--text-muted)] uppercase
tracking-wider">built-in...` tracking-wider">bui
271 ` </div>` Source code </div>
line.
272 ` ))}` Source code ))}
line.
273 ` </div>` Source code </div>
line.

Page 564 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
274 ` <p className="text-xs text-[var(--text- Source code <p className="text-xs text-[var(--text-muted)]
muted)] font-sans">Custom color rules can be line. font-sans">Custom color rules can be added in
added in a future update.</p>` a futur
275 ` </div>` Source code </div>
line.
276 ` );` Executable );
statement.
277 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
278 `` Blank line for Separator between code blocks.
readability.
279 `function PerformancePanel() {` Source code function PerformancePanel() {
line.
280 ` const { maxPackets, setMaxPackets } = Named const { maxPackets, setMaxPackets } =
useAppStore();` constant — useAppStore();
value should
not change.
281 ` const [bufSize, setBufSize] = Named const [bufSize, setBufSize] =
useState(String(maxPackets));` constant — useState(String(maxPackets));
value should
not change.
282 ` const { toast } = useToast();` Named const { toast } = useToast();
constant —
value should
not change.
283 `` Blank line for Separator between code blocks.
readability.
284 ` return (` Exit function return (
and give back
a value.
285 ` <div className="space-y-6 animate-in Source code <div className="space-y-6 animate-in fade-in
fade-in slide-in-from-bottom-4 duration-300">` line. slide-in-from-bottom-4 duration-300">
286 ` <SectionHeader icon={Zap} Source code <SectionHeader icon={Zap} title="Performance"
title="Performance" description="Tune memory line. description="Tune memory and rendering
and rendering settings for heavy traffic...` settings for he
287 ` <div className="bg-[var(--bg-overlay)] Source code <div className="bg-[var(--bg-overlay)] border
border border-[var(--border-subtle)] rounded p- line. border-[var(--border-subtle)] rounded p-4
4 space-y-4">` space-y-4">
288 ` <div>` Source code <div>
line.
289 ` <label className="text-xs font-bold Source code <label className="text-xs font-bold uppercase
uppercase tracking-wider text-[var(--text- line. tracking-wider text-[var(--text-muted)] font-
muted)] font-mono block mb-1.5">` mono bloc
290 ` Max Packet Buffer` Source code Max Packet Buffer
line.
291 ` </label>` Source code </label>
line.
292 ` <div className="flex items-center gap- Source code <div className="flex items-center gap-3">
3">` line.

Page 565 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
293 ` <input` Source code <input
line.
294 ` type="range" min={1000} Source code type="range" min={1000} max={500000}
max={500000} step={1000}` line. step={1000}
295 ` value={parseInt(bufSize) \ \ 100000}`
296 ` onChange={e => Source code onChange={e => setBufSize([Link])}
setBufSize([Link])}` line.
297 ` className="flex-1 accent-[var(-- Source code className="flex-1 accent-[var(--accent)]"
accent)]"` line.
298 ` />` Source code />
line.
299 ` <input` Source code <input
line.
300 ` type="number" min={1000} Source code type="number" min={1000} max={500000}
max={500000} step={1000}` line. step={1000}
301 ` value={bufSize}` Source code value={bufSize}
line.
302 ` onChange={e => Source code onChange={e => setBufSize([Link])}
setBufSize([Link])}` line.
303 ` className="w-28 h-8 bg-[var(--bg- Source code className="w-28 h-8 bg-[var(--bg-base)]
base)] border border-[var(--border-strong)] line. border border-[var(--border-strong)] rounded
rounded text-sm px-3 font-...` text-sm px-3 fo
304 ` />` Source code />
line.
305 ` </div>` Source code </div>
line.
306 ` <p className="text-[10px] font-mono Source code <p className="text-[10px] font-mono text-
text-[var(--text-muted)] mt-1">` line. [var(--text-muted)] mt-1">
307 ` Current: <span className="text-[var(-- Source code Current: <span className="text-[var(--
accent)]">{[Link]()}</span line. accent)]">{[Link]()}</span
> packets. Higher valu...` > packets. Higher
308 ` </p>` Source code </p>
line.
309 ` </div>` Source code </div>
line.
310 `` Blank line for Separator between code blocks.
readability.
311 ` <div className="pt-3 border-t border- Source code <div className="pt-3 border-t border-[var(--
[var(--border-subtle)]">` line. border-subtle)]">
312 ` <div className="text-xs font-bold Source code <div className="text-xs font-bold uppercase
uppercase tracking-wider text-[var(--text- line. tracking-wider text-[var(--text-muted)] font-
muted)] font-mono mb-3">Renderi...` mono mb-3">
313 ` <div className="grid grid-cols-2 gap-3 Source code <div className="grid grid-cols-2 gap-3 text-xs
text-xs font-mono text-[var(--text-secondary)]">` line. font-mono text-[var(--text-secondary)]">
314 ` {[` Source code {[
line.
315 ` ['List Virtualization', 'react-window · Source code ['List Virtualization', 'react-window · enabled'],
enabled'],` line.

Page 566 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
316 ` ['Row Height', '22px fixed'],` Source code ['Row Height', '22px fixed'],
line.
317 ` ['Batch Rendering', 'enabled'],` Source code ['Batch Rendering', 'enabled'],
line.
318 ` ['WebSocket Feed', 'auto-reconnect Source code ['WebSocket Feed', 'auto-reconnect x5'],
x5'],` line.
319 ` ].map(([k, v]) => (` Source code ].map(([k, v]) => (
line.
320 ` <div key={k} className="bg-[var(-- Source code <div key={k} className="bg-[var(--bg-base)]
bg-base)] border border-[var(--border-subtle)] line. border border-[var(--border-subtle)] rounded p-
rounded p-2">` 2">

Line Source Easy Explanation Technical Explanation


321 ` <div className="text-[var(-- Source code line. <div className="text-[var(--text-
text-muted)] text-[9px] uppercase muted)] text-[9px] uppercase tracking-
tracking-wider mb-1">{k}</div>` wider mb-1">{k}</div>
322 ` <div className="text-[var(-- Source code line. <div className="text-[var(--
normal)]">{v}</div>` normal)]">{v}</div>
323 ` </div>` Source code line. </div>
324 ` ))}` Source code line. ))}
325 ` </div>` Source code line. </div>
326 ` </div>` Source code line. </div>
327 ` </div>` Source code line. </div>
328 ` <Button onClick={() => {` Source code line. <Button onClick={() => {
329 ` const n = parseInt(bufSize);` Named constant — const n = parseInt(bufSize);
value should not
change.
330 ` if (!isNaN(n) && n > 0) {` Conditional branch if (!isNaN(n) && n > 0) {
— run code only
when condition true.
331 ` setMaxPackets(n);` Executable setMaxPackets(n);
statement.
332 ` toast({ title: 'Performance settings Executable toast({ title: 'Performance settings
saved', description: `Buffer set to statement. saved', description: `Buffer set to
${[Link]()} packets` });` ${[Link]()} packe
333 ` }` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
334 ` }} className="bg-[var(--accent)] Source code line. }} className="bg-[var(--accent)] text-
text-[var(--bg-void)] hover:brightness-110 [var(--bg-void)] hover:brightness-110
font-bold">` font-bold">
335 ` <Save className="w-4 h-4 mr-2" Source code line. <Save className="w-4 h-4 mr-2" />
/> Save` Save
336 ` </Button>` Source code line. </Button>
337 ` </div>` Source code line. </div>
338 ` );` Executable );
statement.

Page 567 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


339 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
340 `` Blank line for Separator between code blocks.
readability.
341 `function FileStoragePanel() {` Source code line. function FileStoragePanel() {
342 ` const { toast } = useToast();` Named constant — const { toast } = useToast();
value should not
change.
343 ` const [autoSave, setAutoSave] = Named constant — const [autoSave, setAutoSave] =
useState(false);` value should not useState(false);
change.
344 ` const [savePath, setSavePath] = Named constant — const [savePath, setSavePath] =
useState('/tmp/nads-capture');` value should not useState('/tmp/nads-capture');
change.
345 ` const [rotateSize, setRotateSize] = Named constant — const [rotateSize, setRotateSize] =
useState('100');` value should not useState('100');
change.
346 `` Blank line for Separator between code blocks.
readability.
347 ` return (` Exit function and return (
give back a value.
348 ` <div className="space-y-6 animate- Source code line. <div className="space-y-6 animate-
in fade-in slide-in-from-bottom-4 duration- in fade-in slide-in-from-bottom-4
300">` duration-300">
349 ` <SectionHeader icon={HardDrive} Source code line. <SectionHeader icon={HardDrive}
title="File & Storage" description="PCAP title="File & Storage"
file saving and rotation settings." />` description="PCAP file saving and
rotation se
350 ` <div className="bg-[var(--bg- Source code line. <div className="bg-[var(--bg-
overlay)] border border-[var(--border- overlay)] border border-[var(--border-
subtle)] rounded p-4 space-y-4">` subtle)] rounded p-4 space-y-4">
351 ` <SettingRow label="Auto-save Source code line. <SettingRow label="Auto-save
Capture" description="Automatically save Capture" description="Automatically
capture to disk on stop.">` save capture to disk on stop.">
352 ` <ToggleSwitch Source code line. <ToggleSwitch checked={autoSave}
checked={autoSave} onChange={setAutoSave} />
onChange={setAutoSave} />`
353 ` </SettingRow>` Source code line. </SettingRow>
354 `` Blank line for Separator between code blocks.
readability.
355 ` <div>` Source code line. <div>
356 ` <label className="text-xs font- Source code line. <label className="text-xs font-bold
bold uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
text-muted)] font-mono block mb-1.5">` text-muted)] font-mono bloc
357 ` Save Directory` Source code line. Save Directory
358 ` </label>` Source code line. </label>
359 ` <input` Source code line. <input
360 ` type="text"` Source code line. type="text"
361 ` value={savePath}` Source code line. value={savePath}

Page 568 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


362 ` onChange={e => Source code line. onChange={e =>
setSavePath([Link])}` setSavePath([Link])}
363 ` placeholder="/path/to/save"` Source code line. placeholder="/path/to/save"
364 ` className="w-full h-8 bg-[var(-- Source code line. className="w-full h-8 bg-[var(--bg-
bg-base)] border border-[var(--border- base)] border border-[var(--border-
strong)] rounded text-sm px-3 font-...` strong)] rounded text-sm px-3
365 ` disabled={!autoSave}` Source code line. disabled={!autoSave}
366 ` />` Source code line. />
367 ` </div>` Source code line. </div>
368 `` Blank line for Separator between code blocks.
readability.
369 ` <div>` Source code line. <div>
370 ` <label className="text-xs font- Source code line. <label className="text-xs font-bold
bold uppercase tracking-wider text-[var(-- uppercase tracking-wider text-[var(--
text-muted)] font-mono block mb-1.5">` text-muted)] font-mono bloc
371 ` File Rotation Size (MB)` Source code line. File Rotation Size (MB)
372 ` </label>` Source code line. </label>
373 ` <input` Source code line. <input
374 ` type="number" min={1} Source code line. type="number" min={1} max={10000}
max={10000}`
375 ` value={rotateSize}` Source code line. value={rotateSize}
376 ` onChange={e => Source code line. onChange={e =>
setRotateSize([Link])}` setRotateSize([Link])}
377 ` className="w-32 h-8 bg-[var(-- Source code line. className="w-32 h-8 bg-[var(--bg-
bg-base)] border border-[var(--border- base)] border border-[var(--border-
strong)] rounded text-sm px-3 font-mo...` strong)] rounded text-sm px-3 fo
378 ` disabled={!autoSave}` Source code line. disabled={!autoSave}
379 ` />` Source code line. />
380 ` </div>` Source code line. </div>
381 ` </div>` Source code line. </div>
382 ` <div className="flex gap-3">` Source code line. <div className="flex gap-3">
383 ` <Button` Source code line. <Button
384 ` onClick={() => toast({ title: 'File Source code line. onClick={() => toast({ title: 'File settings
settings saved' })}` saved' })}
385 ` className="bg-[var(--accent)] Source code line. className="bg-[var(--accent)] text-
text-[var(--bg-void)] hover:brightness-110 [var(--bg-void)] hover:brightness-110
font-bold"` font-bold"
386 ` >` Source code line. >
387 ` <Save className="w-4 h-4 mr-2" Source code line. <Save className="w-4 h-4 mr-2" />
/> Save` Save
388 ` </Button>` Source code line. </Button>
389 ` <Button variant="outline" Source code line. <Button variant="outline"
className="border-[var(--border-strong)] className="border-[var(--border-
text-[var(--text-primary)] hover:bg-[var(-...` strong)] text-[var(--text-primary)] hover:
390 ` onClick={() => toast({ title: 'Export Source code line. onClick={() => toast({ title: 'Export not
not yet configured', description: 'Connect yet configured', description: 'Connect
backend for PCAP export.' ...` backend for PCAP ex

Page 569 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


391 ` Export Last Capture as PCAP` Source code line. Export Last Capture as PCAP
392 ` </Button>` Source code line. </Button>
393 ` </div>` Source code line. </div>
394 ` </div>` Source code line. </div>
395 ` );` Executable );
statement.
396 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
397 `` Blank line for Separator between code blocks.
readability.
398 `function NadsConfigPanel() {` Source code line. function NadsConfigPanel() {
399 ` const { data: config, isError, refetch } = Named constant — const { data: config, isError, refetch } =
useGetNadsConfig();` value should not useGetNadsConfig();
change.
400 ` const { toast } = useToast();` Named constant — const { toast } = useToast();
value should not
change.

Line Source Easy Technical Explanation


Explanation
401 ` const [detectors, setDetectors] = Named constant const [detectors, setDetectors] =
useState<DetectorConfig[]>([]);` — value should useState<DetectorConfig[]>([]);
not change.
402 ` const [thresholds, setThresholds] = Named constant const [thresholds, setThresholds] =
useState<Record<string, number>>({});` — value should useState<Record<string, number>>({});
not change.
403 ` const [baselineRecalcing, Named constant const [baselineRecalcing,
setBaselineRecalcing] = useState(false);` — value should setBaselineRecalcing] =
not change. useState(false);
404 ` const [saving, setSaving] = Named constant const [saving, setSaving] =
useState(false);` — value should useState(false);
not change.
405 `` Blank line for Separator between code blocks.
readability.
406 ` // Seed defaults if backend returns Comment Seed defaults if backend returns empty
empty detectors` documenting detectors
intent.
407 ` const DEFAULT_DETECTORS: Named constant const DEFAULT_DETECTORS:
DetectorConfig[] = [` — value should DetectorConfig[] = [
not change.
408 ` { name: 'Port Scanner', desc: 'Detects Source code line. { name: 'Port Scanner', desc: 'Detects
sequential port access patterns', enabled: sequential port access patterns',
true, threshold: 15 },` enabled: true, threshold: 1
409 ` { name: 'DDoS Detector', desc: Source code line. { name: 'DDoS Detector', desc:
'Volumetric packet rate anomaly detection', 'Volumetric packet rate anomaly
enabled: true, threshold: 10000 },` detection', enabled: true, threshold:
410 ` { name: 'Brute Force Guard', desc: Source code line. { name: 'Brute Force Guard', desc:
'Repeated authentication failure detection', 'Repeated authentication failure
enabled: true, threshold: 5 },` detection', enabled: true, thres

Page 570 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
411 ` { name: 'Data Exfil Monitor', desc: Source code line. { name: 'Data Exfil Monitor', desc:
'Large outbound data transfer monitoring', 'Large outbound data transfer
enabled: false, threshold: 1000000 },` monitoring', enabled: false, thres
412 ` { name: 'C2 Beacon', desc: 'Periodic Source code line. { name: 'C2 Beacon', desc: 'Periodic
connection pattern detection', enabled: connection pattern detection', enabled:
true, threshold: 60 },` true, threshold: 60 },
413 ` { name: 'Lateral Movement', desc: Source code line. { name: 'Lateral Movement', desc:
'Internal network scan sweep detection', 'Internal network scan sweep detection',
enabled: true, threshold: 20 },` enabled: true, threshold:
414 ` ].map(d => ({ ...d, description: [Link] } Executable ].map(d => ({ ...d, description: [Link] }
as DetectorConfig));` statement. as DetectorConfig));
415 `` Blank line for Separator between code blocks.
readability.
416 ` useEffect(() => {` Source code line. useEffect(() => {
417 ` const d = (config?.detectors && Named constant const d = (config?.detectors &&
[Link] > 0)` — value should [Link] > 0)
not change.
418 ` ? [Link]` Source code line. ? [Link]
419 ` : DEFAULT_DETECTORS;` Executable : DEFAULT_DETECTORS;
statement.
420 ` setDetectors(d);` Executable setDetectors(d);
statement.
421 ` const t: Record<string, number> = {};` Named constant const t: Record<string, number> = {};
— value should
not change.
422 ` [Link](det => { if ([Link] != Executable [Link](det => { if ([Link] !=
null) t[[Link]] = [Link]; });` statement. null) t[[Link]] = [Link]; });
423 ` setThresholds(t);` Executable setThresholds(t);
statement.
424 ` }, [config]);` Executable }, [config]);
statement.
425 `` Blank line for Separator between code blocks.
readability.
426 ` const toggleDetector = (name: string) => Named constant const toggleDetector = (name: string)
{` — value should => {
not change.
427 ` setDetectors(prev => [Link](d => Executable setDetectors(prev => [Link](d =>
[Link] === name ? { ...d, enabled: statement. [Link] === name ? { ...d, enabled:
![Link] } : d));` ![Link] } : d));
428 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
429 `` Blank line for Separator between code blocks.
readability.
430 ` const handleSave = async () => {` Named constant const handleSave = async () => {
— value should
not change.
431 ` setSaving(true);` Executable setSaving(true);
statement.

Page 571 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
432 ` const updated = [Link](d => ({` Named constant const updated = [Link](d => ({
— value should
not change.
433 ` ...d,` Source code line. ...d,
434 ` threshold: thresholds[[Link]] ?? Source code line. threshold: thresholds[[Link]] ??
[Link],` [Link],
435 ` }));` Executable }));
statement.
436 ` try {` Source code line. try {
437 ` await saveNadsConfig({ detectors: Executable await saveNadsConfig({ detectors:
updated });` statement. updated });
438 ` toast({ title: 'NADS config saved', Executable toast({ title: 'NADS config saved',
description: 'Detector settings applied.' });` statement. description: 'Detector settings applied.'
});
439 ` refetch();` Executable refetch();
statement.
440 ` } catch {` Source code line. } catch {
441 ` toast({ title: 'Save failed', description: Executable toast({ title: 'Save failed', description:
'Could not reach backend. Settings saved statement. 'Could not reach backend. Settings
locally.' });` saved locally.' });
442 ` } finally {` Source code line. } finally {
443 ` setSaving(false);` Executable setSaving(false);
statement.
444 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
445 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
446 `` Blank line for Separator between code blocks.
readability.
447 ` const handleRecalculate = async () => {` Named constant const handleRecalculate = async () => {
— value should
not change.
448 ` setBaselineRecalcing(true);` Executable setBaselineRecalcing(true);
statement.
449 ` try {` Source code line. try {
450 ` await recalculateBaseline();` Executable await recalculateBaseline();
statement.
451 ` toast({ title: 'Baseline recalculation Executable toast({ title: 'Baseline recalculation
started', description: 'This may take statement. started', description: 'This may take
several minutes.' });` several minutes.' });
452 ` } catch {` Source code line. } catch {
453 ` toast({ title: 'Recalculate failed', Executable toast({ title: 'Recalculate failed',
description: 'Backend unreachable.' });` statement. description: 'Backend unreachable.' });
454 ` } finally {` Source code line. } finally {

Page 572 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
455 ` setBaselineRecalcing(false);` Executable setBaselineRecalcing(false);
statement.
456 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
457 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
458 `` Blank line for Separator between code blocks.
readability.
459 ` return (` Exit function and return (
give back a value.
460 ` <div className="space-y-8 animate-in Source code line. <div className="space-y-8 animate-in
fade-in slide-in-from-bottom-4 duration- fade-in slide-in-from-bottom-4 duration-
300">` 300">
461 ` <SectionHeader icon={Shield} Source code line. <SectionHeader icon={Shield}
title="NADS Anomaly Detectors" title="NADS Anomaly Detectors"
description="Configure thresholds for the description="Configure thresholds for th
Network A...`
462 `` Blank line for Separator between code blocks.
readability.
463 ` {isError && (` Source code line. {isError && (
464 ` <div className="flex items-center Source code line. <div className="flex items-center gap-
gap-2 p-3 bg-[var(--medium)]/10 border 2 p-3 bg-[var(--medium)]/10 border
border-[var(--medium)]/30 rounded te...` border-[var(--medium)]/30 r
465 ` <AlertCircle className="w-4 h-4 Source code line. <AlertCircle className="w-4 h-4
shrink-0" />` shrink-0" />
466 ` Backend offline — showing Source code line. Backend offline — showing defaults.
defaults. Changes saved locally until Changes saved locally until backend
backend reconnects.` reconnects.
467 ` </div>` Source code line. </div>
468 ` )}` Source code line. )}
469 `` Blank line for Separator between code blocks.
readability.
470 ` <div className="grid grid-cols-1 Source code line. <div className="grid grid-cols-1
md:grid-cols-2 gap-4">` md:grid-cols-2 gap-4">
471 ` {[Link](det => (` Source code line. {[Link](det => (
472 ` <div` Source code line. <div
473 ` key={[Link]}` Source code line. key={[Link]}
474 ` className={`bg-[var(--bg- Source code line. className={`bg-[var(--bg-overlay)]
overlay)] border rounded p-4 transition- border rounded p-4 transition-colors
colors ${[Link] ? 'border-[var(--bo...` ${[Link] ? 'border-[var
475 ` >` Source code line. >
476 ` <div className="flex justify- Source code line. <div className="flex justify-between
between items-start mb-1">` items-start mb-1">

Page 573 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
477 ` <span className="font-bold Source code line. <span className="font-bold text-[var(-
text-[var(--text-primary)] text- -text-primary)] text-
sm">{[Link]}</span>` sm">{[Link]}</span>
478 ` <button` Source code line. <button
479 ` role="switch"` Source code line. role="switch"
480 ` aria-checked={[Link]}` Source code line. aria-checked={[Link]}

Line Source Easy Technical Explanation


Explanation
481 ` onClick={() => Source code onClick={() => toggleDetector([Link])}
toggleDetector([Link])}` line.
482 ` style={{` Source code style={{
line.
483 ` width: 36, height: 20, Source code width: 36, height: 20, borderRadius: 10,
borderRadius: 10,` line.
484 ` backgroundColor: [Link] Source code backgroundColor: [Link] ? '#FF5949'
? '#FF5949' : '#444',` line. : '#444',
485 ` border: [Link] ? 'none' : Source code border: [Link] ? 'none' : '1px solid
'1px solid #666',` line. #666',
486 ` display: 'flex', alignItems: Source code display: 'flex', alignItems: 'center', padding:
'center', padding: '2px',` line. '2px',
487 ` cursor: 'pointer', transition: Source code cursor: 'pointer', transition: 'background-
'background-color 0.2s',` line. color 0.2s',
488 ` flexShrink: 0, marginLeft: 8,` Source code flexShrink: 0, marginLeft: 8,
line.
489 ` }}` Source code }}
line.
490 ` >` Source code >
line.
491 ` <div style={{` Source code <div style={{
line.
492 ` width: 16, height: 16, Source code width: 16, height: 16, borderRadius: '50%',
borderRadius: '50%',` line.
493 ` backgroundColor: '#fff', Source code backgroundColor: '#fff', boxShadow: '0 1px
boxShadow: '0 1px 3px rgba(0,0,0,0.4)',` line. 3px rgba(0,0,0,0.4)',
494 ` transform: [Link] ? Source code transform: [Link] ? 'translateX(16px)'
'translateX(16px)' : 'translateX(0px)',` line. : 'translateX(0px)',
495 ` transition: 'transform 0.2s',` Source code transition: 'transform 0.2s',
line.
496 ` }} />` Source code }} />
line.
497 ` </button>` Source code </button>
line.
498 ` </div>` Source code </div>
line.
499 ` <p className="text-xs text-[var(-- Source code <p className="text-xs text-[var(--text-
text-secondary)] mb- line. secondary)] mb-3">{[Link]}</p>
3">{[Link]}</p>`

Page 574 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
500 ` {[Link] && Source code {[Link] && thresholds[[Link]] !=
thresholds[[Link]] != null && (` line. null && (
501 ` <div className="pt-3 border-t Source code <div className="pt-3 border-t border-
border-[var(--border-subtle)]">` line. [var(--border-subtle)]">
502 ` <label className="text-[10px] Source code <label className="text-[10px] uppercase
uppercase font-mono text-[var(--text- line. font-mono text-[var(--text-muted)] tracking-
muted)] tracking-wider block mb-1.5">` wider block mb-1
503 ` Threshold` Source code Threshold
line.
504 ` </label>` Source code </label>
line.
505 ` <div className="flex items- Source code <div className="flex items-center gap-2">
center gap-2">` line.
506 ` <input` Source code <input
line.
507 ` type="number"` Source code type="number"
line.
508 ` Source code value={thresholds[[Link]]}
value={thresholds[[Link]]}` line.
509 ` onChange={e => Source code onChange={e => setThresholds(prev => ({
setThresholds(prev => ({ ...prev, line. ...prev, [[Link]]: Number([Link])
[[Link]]: Number([Link]) }))}` }))}
510 ` className="w-28 h-7 bg- Source code className="w-28 h-7 bg-[var(--bg-base)]
[var(--bg-base)] border border-[var(-- line. border border-[var(--border-strong)]
border-strong)] rounded text-xs px-2...` rounded text-xs px-2 fo
511 ` />` Source code />
line.
512 ` <span className="text-[10px] Source code <span className="text-[10px] text-[var(--
text-[var(--text-muted)] font-mono">` line. text-muted)] font-mono">
513 ` {[Link] === 'DDoS Source code {[Link] === 'DDoS Detector' ? 'pps' :
Detector' ? 'pps' : [Link] === 'Data Exfil line. [Link] === 'Data Exfil Monitor' ? 'bytes'
Monitor' ? 'bytes' : [Link] ==...` : [Link] === '
514 ` </span>` Source code </span>
line.
515 ` </div>` Source code </div>
line.
516 ` </div>` Source code </div>
line.
517 ` )}` Source code )}
line.
518 ` </div>` Source code </div>
line.
519 ` ))}` Source code ))}
line.
520 ` </div>` Source code </div>
line.
521 `` Blank line for Separator between code blocks.
readability.

Page 575 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
522 ` {/* Baseline Controls */}` Source code {/* Baseline Controls */}
line.
523 ` <div className="pt-6 border-t border- Source code <div className="pt-6 border-t border-
[var(--border-default)]">` line. [var(--border-default)]">
524 ` <h2 className="text-base font-bold Source code <h2 className="text-base font-bold mb-
mb-4">Baseline Engine</h2>` line. 4">Baseline Engine</h2>
525 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)]
overlay)] border border-[var(--border- line. border border-[var(--border-subtle)] p-5
subtle)] p-5 rounded flex flex-col gap-4">` rounded flex flex-co
526 ` <div className="flex justify- Source code <div className="flex justify-between
between items-center">` line. items-center">
527 ` <div>` Source code <div>
line.
528 ` <div className="font-bold text- Source code <div className="font-bold text-[var(--text-
[var(--text-primary)] text-sm mb-1">Host line. primary)] text-sm mb-1">Host Behavior
Behavior Baseline</div>` Baseline</div>
529 ` <div className="text-xs text- Source code <div className="text-xs text-[var(--text-
[var(--text-secondary)]">` line. secondary)]">
530 ` {config?.baselinePackets` Source code {config?.baselinePackets
line.
531 ` ? Source code ?
`${[Link]()} line. `${[Link]()}
historical packets · ${[Link] historical packets · ${[Link]
?? 7} days`` ?? 7} days`
532 ` : 'Calculated from historical Source code : 'Calculated from historical traffic. Used to
traffic. Used to detect deviations.'}` line. detect deviations.'}
533 ` </div>` Source code </div>
line.
534 ` </div>` Source code </div>
line.
535 ` <div className="flex gap-2">` Source code <div className="flex gap-2">
line.
536 ` <Button` Source code <Button
line.
537 ` variant="outline"` Source code variant="outline"
line.
538 ` className="border-[var(-- Source code className="border-[var(--border-strong)]
border-strong)] text-xs h-8"` line. text-xs h-8"
539 ` onClick={handleRecalculate}` Source code onClick={handleRecalculate}
line.
540 ` disabled={baselineRecalcing}` Source code disabled={baselineRecalcing}
line.
541 ` >` Source code >
line.
542 ` {baselineRecalcing` Source code {baselineRecalcing
line.
543 ` ? <><Loader2 className="w- Source code ? <><Loader2 className="w-3 h-3 mr-2
3 h-3 mr-2 animate-spin" /> line. animate-spin" /> Recalculating…</>
Recalculating…</>`

Page 576 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
544 ` : <><RefreshCw Source code : <><RefreshCw className="w-3 h-3 mr-
className="w-3 h-3 mr-2" /> line. 2" /> Recalculate</>}
Recalculate</>}`
545 ` </Button>` Source code </Button>
line.
546 ` <Button` Source code <Button
line.
547 ` variant="ghost"` Source code variant="ghost"
line.
548 ` className="text-[var(--critical)] Source code className="text-[var(--critical)] hover:text-
hover:text-[var(--critical)] hover:bg-[var(-- line. [var(--critical)] hover:bg-[var(--critical)]/10
critical)]/10 text-xs ...` text-xs
549 ` onClick={async () => {` Source code onClick={async () => {
line.
550 ` try {` Source code try {
line.
551 ` await resetBaseline();` Executable await resetBaseline();
statement.
552 ` toast({ title: 'Baseline reset', Executable toast({ title: 'Baseline reset', description:
description: 'Baseline will rebuild on next statement. 'Baseline will rebuild on next capture.' });
capture.' });`
553 ` } catch {` Source code } catch {
line.
554 ` toast({ title: 'Reset failed', Executable toast({ title: 'Reset failed', description:
description: 'Backend unreachable.' });` statement. 'Backend unreachable.' });
555 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
556 ` }}` Source code }}
line.
557 ` >` Source code >
line.
558 ` Reset Baseline` Source code Reset Baseline
line.
559 ` </Button>` Source code </Button>
line.
560 ` </div>` Source code </div>
line.

Li Source Easy Technical Explanation


ne Explana
tion
56 ` </div>` Source </div>
1 code line.
56 ` </div>` Source </div>
2 code line.
56 ` </div>` Source </div>
3 code line.

Page 577 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
56 `` Blank line Separator between code blocks.
4 for
readabilit
y.
56 ` <Button onClick={handleSave} Source <Button onClick={handleSave} disabled={saving}
5 disabled={saving} className="bg-[var(--accent)] code line. className="bg-[var(--accent)] text-[var(--bg-void)]
text-[var(--bg-void)] hover:bright...` h
56 ` {saving` Source {saving
6 code line.
56 ` ? <><Loader2 className="w-4 h-4 mr-2 Source ? <><Loader2 className="w-4 h-4 mr-2 animate-
7 animate-spin" /> Saving…</>` code line. spin" /> Saving…</>
56 ` : <><Save className="w-4 h-4 mr-2" /> Source : <><Save className="w-4 h-4 mr-2" /> Save
8 Save NADS Config</>}` code line. NADS Config</>}
56 ` </Button>` Source </Button>
9 code line.
57 ` </div>` Source </div>
0 code line.
57 ` );` Executabl );
1 e
statement
.
57 `}` Brace or C/C++ syntax structure.
2 parenthes
is
closing/o
pening a
block.
57 `` Blank line Separator between code blocks.
3 for
readabilit
y.
57 `// ─── Main Settings component Comment ─── Main Settings component
4 ──────────────────────────────── document ────────────────────────────────
──────────────────` ing intent. ──────────────────
57 `` Blank line Separator between code blocks.
5 for
readabilit
y.
57 `const TABS = [` Named const TABS = [
6 constant
— value
should
not
change.
57 ` { id: 'appearance', label: 'Appearance', icon: Source { id: 'appearance', label: 'Appearance', icon:
7 Monitor },` code line. Monitor },
57 ` { id: 'capture', label: 'Capture Defaults', icon: Source { id: 'capture', label: 'Capture Defaults', icon:
8 Camera },` code line. Camera },
57 ` { id: 'columns', label: 'Columns', icon: Columns },` Source { id: 'columns', label: 'Columns', icon: Columns },
9 code line.
58 ` { id: 'colorRules', label: 'Color Rules', icon: Palette Source { id: 'colorRules', label: 'Color Rules', icon: Palette
0 },` code line. },

Page 578 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
58 ` { id: 'performance', label: 'Performance', icon: Zap Source { id: 'performance', label: 'Performance', icon: Zap
1 },` code line. },
58 ` { id: 'file', label: 'File & Storage', icon: HardDrive Source { id: 'file', label: 'File & Storage', icon: HardDrive },
2 },` code line.
58 ` { id: 'nads', label: 'NADS Configuration', icon: Source { id: 'nads', label: 'NADS Configuration', icon:
3 Shield },` code line. Shield },
58 `];` Executabl ];
4 e
statement
.
58 `` Blank line Separator between code blocks.
5 for
readabilit
y.
58 `export default function Settings() {` Source export default function Settings() {
6 code line.
58 ` const [activeTab, setActiveTab] = Named const [activeTab, setActiveTab] = useState('nads');
7 useState('nads');` constant
— value
should
not
change.
58 `` Blank line Separator between code blocks.
8 for
readabilit
y.
58 ` return (` Exit return (
9 function
and give
back a
value.
59 ` <div className="h-full flex flex-col bg-[var(--bg- Source <div className="h-full flex flex-col bg-[var(--bg-
0 void)] text-[var(--text-primary)]">` code line. void)] text-[var(--text-primary)]">
59 ` <div className="h-16 border-b border-[var(-- Source <div className="h-16 border-b border-[var(--
1 border-default)] bg-[var(--bg-base)] flex items- code line. border-default)] bg-[var(--bg-base)] flex items-
center px-6 shrink-0">` center p
59 ` <h1 className="text-xl font-bold font-sans Source <h1 className="text-xl font-bold font-sans flex
2 flex items-center gap-2 text-[var(--text-primary)]">` code line. items-center gap-2 text-[var(--text-primary)]">
59 ` <SettingsIcon className="w-6 h-6 text- Source <SettingsIcon className="w-6 h-6 text-[var(--text-
3 [var(--text-muted)]" />` code line. muted)]" />
59 ` Settings` Source Settings
4 code line.
59 ` </h1>` Source </h1>
5 code line.
59 ` </div>` Source </div>
6 code line.
59 `` Blank line Separator between code blocks.
7 for
readabilit
y.

Page 579 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
59 ` <div className="flex-1 flex overflow-hidden">` Source <div className="flex-1 flex overflow-hidden">
8 code line.
59 ` {/* Tab List */}` Source {/* Tab List */}
9 code line.
60 ` <div className="w-56 border-r border-[var(-- Source <div className="w-56 border-r border-[var(--
0 border-default)] bg-[var(--bg-raised)] flex flex-col code line. border-default)] bg-[var(--bg-raised)] flex flex-col
py-4 shrink-...` py-
60 ` {[Link](tab => {` Source {[Link](tab => {
1 code line.
60 ` const Icon = [Link];` Named const Icon = [Link];
2 constant
— value
should
not
change.
60 ` return (` Exit return (
3 function
and give
back a
value.
60 ` <button` Source <button
4 code line.
60 ` key={[Link]}` Source key={[Link]}
5 code line.
60 ` onClick={() => setActiveTab([Link])}` Source onClick={() => setActiveTab([Link])}
6 code line.
60 ` className={`px-4 py-2.5 text-left text- Source className={`px-4 py-2.5 text-left text-sm font-sans
7 sm font-sans transition-colors flex items-center code line. transition-colors flex items-center gap-2.5 ${ac
gap-2.5 ${act...`
60 ` ? 'bg-[var(--bg-hover)] text-[var(-- Source ? 'bg-[var(--bg-hover)] text-[var(--accent)] border-r-
8 accent)] border-r-2 border-[var(--accent)] font-bold'` code line. 2 border-[var(--accent)] font-bold'
60 ` : 'text-[var(--text-secondary)] hover:bg- Source : 'text-[var(--text-secondary)] hover:bg-[var(--bg-
9 [var(--bg-hover)] hover:text-[var(--text-primary)]'}`}` code line. hover)] hover:text-[var(--text-primary)]'}`}
61 ` >` Source >
0 code line.
61 ` <Icon className={`w-4 h-4 shrink-0 Source <Icon className={`w-4 h-4 shrink-0 ${activeTab
1 ${activeTab === [Link] ? 'text-[var(--accent)]' : 'text- code line. === [Link] ? 'text-[var(--accent)]' : 'text-[var(--te
[var(--tex...`
61 ` {[Link]}` Source {[Link]}
2 code line.
61 ` </button>` Source </button>
3 code line.
61 ` );` Executabl );
4 e
statement
.
61 ` })}` Source })}
5 code line.
61 ` </div>` Source </div>
6 code line.

Page 580 of 629


NADS Complete Technical Reference

Li Source Easy Technical Explanation


ne Explana
tion
61 `` Blank line Separator between code blocks.
7 for
readabilit
y.
61 ` {/* Content Area */}` Source {/* Content Area */}
8 code line.
61 ` <div className="flex-1 overflow-auto p-8 bg- Source <div className="flex-1 overflow-auto p-8 bg-[var(-
9 [var(--bg-base)]">` code line. -bg-base)]">
62 ` <div className="max-w-3xl mx-auto">` Source <div className="max-w-3xl mx-auto">
0 code line.
62 ` {activeTab === 'appearance' && Source {activeTab === 'appearance' &&
1 <AppearancePanel />}` code line. <AppearancePanel />}
62 ` {activeTab === 'capture' && Source {activeTab === 'capture' &&
2 <CaptureDefaultsPanel />}` code line. <CaptureDefaultsPanel />}
62 ` {activeTab === 'columns' && Source {activeTab === 'columns' && <ColumnsPanel />}
3 <ColumnsPanel />}` code line.
62 ` {activeTab === 'colorRules' && Source {activeTab === 'colorRules' && <ColorRulesPanel
4 <ColorRulesPanel />}` code line. />}
62 ` {activeTab === 'performance' && Source {activeTab === 'performance' &&
5 <PerformancePanel />}` code line. <PerformancePanel />}
62 ` {activeTab === 'file' && <FileStoragePanel Source {activeTab === 'file' && <FileStoragePanel />}
6 />}` code line.
62 ` {activeTab === 'nads' && Source {activeTab === 'nads' && <NadsConfigPanel />}
7 <NadsConfigPanel />}` code line.
62 ` </div>` Source </div>
8 code line.
62 ` </div>` Source </div>
9 code line.
63 ` </div>` Source </div>
0 code line.
63 ` </div>` Source </div>
1 code line.
63 ` );` Executabl );
2 e
statement
.
63 `}` Brace or C/C++ syntax structure.
3 parenthes
is
closing/o
pening a
block.

File: webwireshark/src/pages/[Link]
Total lines: 333

Page 581 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
1 `import React, { useMemo, useState } Executable import React, { useMemo, useState }
from 'react';` statement. from 'react';
2 `import {` Source code line. import {
3 ` AreaChart, Area, XAxis, YAxis, Source code line. AreaChart, Area, XAxis, YAxis,
CartesianGrid, Tooltip, CartesianGrid, Tooltip,
ResponsiveContainer,` ResponsiveContainer,
4 ` BarChart, Bar, Cell, PieChart, Pie, Source code line. BarChart, Bar, Cell, PieChart, Pie,
Legend,` Legend,
5 `} from 'recharts';` Executable } from 'recharts';
statement.
6 `import { useGetNadsFlows, Executable import { useGetNadsFlows,
useGetProtocolStats, useGetIoGraph } statement. useGetProtocolStats, useGetIoGraph }
from '@workspace/api-client-react';` from '@workspace/api-client-react';
7 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
8 `import { BarChart2, Loader2 } from Executable import { BarChart2, Loader2 } from
'lucide-react';` statement. 'lucide-react';
9 `` Blank line for Separator between code blocks.
readability.
10 `function EmptyState({ label }: { label: Source code line. function EmptyState({ label }: { label:
string }) {` string }) {
11 ` return (` Exit function and return (
give back a value.
12 ` <div className="flex flex-col items- Source code line. <div className="flex flex-col items-
center justify-center h-full text-[var(--text- center justify-center h-full text-[var(--text-
muted)] py-12 gap-2 opacity-50">` muted)] py-12 gap-
13 ` <BarChart2 className="w-10 h-10" Source code line. <BarChart2 className="w-10 h-10"
strokeWidth={1} />` strokeWidth={1} />
14 ` <span className="text-xs font- Source code line. <span className="text-xs font-
mono">{label}</span>` mono">{label}</span>
15 ` </div>` Source code line. </div>
16 ` );` Executable );
statement.
17 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
18 `` Blank line for Separator between code blocks.
readability.
19 `const PROTO_COLORS = [` Named constant const PROTO_COLORS = [
— value should
not change.
20 ` '#40C4FF', // TCP — electric blue` Source code line. '#40C4FF', // TCP — electric blue
21 ` '#69F0AE', // UDP — vivid mint green` Source code line. '#69F0AE', // UDP — vivid mint green
22 ` '#FFAB00', // DNS — bright amber` Source code line. '#FFAB00', // DNS — bright amber
23 ` '#B9F6CA', // HTTP — lime` Source code line. '#B9F6CA', // HTTP — lime
24 ` '#EA80FC', // TLS — vivid purple/pink` Source code line. '#EA80FC', // TLS — vivid purple/pink

Page 582 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
25 ` '#FF6E40', // ICMP — bright orange` Source code line. '#FF6E40', // ICMP — bright orange
26 ` '#80D8FF', // ARP — sky blue` Source code line. '#80D8FF', // ARP — sky blue
27 ` '#FF5252', // other — coral red` Source code line. '#FF5252', // other — coral red
28 `];` Executable ];
statement.
29 `` Blank line for Separator between code blocks.
readability.
30 `export default function Stats() {` Source code line. export default function Stats() {
31 ` const { data: flows = [], isLoading: Named constant const { data: flows = [], isLoading:
flowsLoading } = useGetNadsFlows();` — value should flowsLoading } = useGetNadsFlows();
not change.
32 ` const { data: protocolStats = [], Named constant const { data: protocolStats = [],
isLoading: protoLoading } = — value should isLoading: protoLoading } =
useGetProtocolStats();` not change. useGetProtocolStat
33 ` const { data: ioGraphData = [], Named constant const { data: ioGraphData = [], isLoading:
isLoading: ioLoading } = — value should ioLoading } = useGetIoGraph();
useGetIoGraph();` not change.
34 ` const { stats, packets: storePackets } = Named constant const { stats, packets: storePackets } =
useAppStore();` — value should useAppStore();
not change.
35 ` const [activeProto, setActiveProto] = null>(null);` Named constant — value should not
useState<string \ change.
36 `` Blank line for Separator between code blocks.
readability.
37 ` // Build I/O graph data — real if Comment Build I/O graph data — real if available,
available, else derive from stats` documenting else derive from stats
intent.
38 ` const ioData = useMemo(() => {` Named constant const ioData = useMemo(() => {
— value should
not change.
39 ` if ([Link] > 0) return Conditional if ([Link] > 0) return
[Link](-60);` branch — run [Link](-60);
code only when
condition true.
40 ` // Build from store as fallback` Comment Build from store as fallback
documenting
intent.
41 ` if ([Link] > 0) {` Conditional if ([Link] > 0) {
branch — run
code only when
condition true.
42 ` const buckets: Record<string, { in: Named constant const buckets: Record<string, { in:
number; out: number }> = {};` — value should number; out: number }> = {};
not change.
43 ` [Link](p => {` Source code line. [Link](p => {
44 ` const t = new Named constant const t = new
Date([Link]).toLocaleTimeString('en', { — value should Date([Link]).toLocaleTimeString('en', {
hour: '2-digit', minute: '2-digit', second: '2- not change. hour: '2-digit', minute: '
digit' });`

Page 583 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
45 ` if (!buckets[t]) buckets[t] = { in: 0, Conditional if (!buckets[t]) buckets[t] = { in: 0, out: 0 };
out: 0 };` branch — run
code only when
condition true.
46 ` buckets[t].in += [Link]([Link] * Executable buckets[t].in += [Link]([Link] * 0.6);
0.6);` statement.
47 ` buckets[t].out += [Link]([Link] Executable buckets[t].out += [Link]([Link] *
* 0.4);` statement. 0.4);
48 ` });` Executable });
statement.
49 ` return [Link](buckets).slice(- Exit function and return [Link](buckets).slice(-
30).map(([time, v]) => ({ time, ...v }));` give back a value. 30).map(([time, v]) => ({ time, ...v }));
50 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.
51 ` return [{ time: 'now', in: [Link] > 0 ? Exit function and return [{ time: 'now', in: [Link] > 0 ?
[Link]([Link] * 0.6 / 8) : 0, out: give back a value. [Link]([Link] * 0.6 / 8) : 0,
[Link] > 0 ? [Link](s...`
52 ` }, [ioGraphData, storePackets, stats]);` Executable }, [ioGraphData, storePackets, stats]);
statement.
53 `` Blank line for Separator between code blocks.
readability.
54 ` // Build protocol hierarchy from real Comment Build protocol hierarchy from real data
data` documenting
intent.
55 ` const protoHierarchy = useMemo(() => Named constant const protoHierarchy = useMemo(() => {
{` — value should
not change.
56 ` if ([Link] > 0) {` Conditional if ([Link] > 0) {
branch — run
code only when
condition true.
57 ` const total = [Link]((s, \ 1;`
p) => s + [Link], 0) \
58 ` return [Link](0, Exit function and return [Link](0, 8).map((p, i)
8).map((p, i) => ({` give back a value. => ({
59 ` name: [Link],` Source code line. name: [Link],
60 ` packets: [Link],` Source code line. packets: [Link],
61 ` bytes: [Link],` Source code line. bytes: [Link],
62 ` pct: [Link](([Link] / total) * Source code line. pct: [Link](([Link] / total) * 100),
100),`
63 ` color: PROTO_COLORS[i % Source code line. color: PROTO_COLORS[i %
PROTO_COLORS.length],` PROTO_COLORS.length],
64 ` children: [Link],` Source code line. children: [Link],
65 ` }));` Executable }));
statement.
66 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 584 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
67 ` // Derive from captured packets` Comment Derive from captured packets
documenting
intent.
68 ` if ([Link] > 0) {` Conditional if ([Link] > 0) {
branch — run
code only when
condition true.
69 ` const map: Record<string, { packets: Named constant const map: Record<string, { packets:
number; bytes: number }> = {};` — value should number; bytes: number }> = {};
not change.
70 ` [Link](p => {` Source code line. [Link](p => {
71 ` if (!map[[Link]]) map[[Link]] Conditional if (!map[[Link]]) map[[Link]] = {
= { packets: 0, bytes: 0 };` branch — run packets: 0, bytes: 0 };
code only when
condition true.
72 ` map[[Link]].packets += 1;` Executable map[[Link]].packets += 1;
statement.
73 ` map[[Link]].bytes += [Link];` Executable map[[Link]].bytes += [Link];
statement.
74 ` });` Executable });
statement.
75 ` const total = [Link];` Named constant const total = [Link];
— value should
not change.
76 ` return [Link](map)` Exit function and return [Link](map)
give back a value.
77 ` .sort((a, b) => b[1].packets - Source code line. .sort((a, b) => b[1].packets - a[1].packets)
a[1].packets)`
78 ` .slice(0, 8)` Source code line. .slice(0, 8)
79 ` .map(([name, v], i) => ({` Source code line. .map(([name, v], i) => ({
80 ` name,` Source code line. name,

Line Source Easy Technical Explanation


Explanation
81 ` packets: [Link],` Source code line. packets: [Link],
82 ` bytes: [Link],` Source code line. bytes: [Link],
83 ` pct: [Link](([Link] / total) * Source code line. pct: [Link](([Link] / total) * 100),
100),`
84 ` color: PROTO_COLORS[i % Source code line. color: PROTO_COLORS[i %
PROTO_COLORS.length],` PROTO_COLORS.length],
85 ` children: undefined as any,` Source code line. children: undefined as any,
86 ` }));` Executable }));
statement.
87 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

Page 585 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
88 ` return [];` Exit function and return [];
give back a
value.
89 ` }, [protocolStats, storePackets]);` Executable }, [protocolStats, storePackets]);
statement.
90 `` Blank line for Separator between code blocks.
readability.
91 ` // Endpoint table from real flows` Comment Endpoint table from real flows
documenting
intent.
92 ` const endpointStats = useMemo(() => {` Named constant const endpointStats = useMemo(() => {
— value should
not change.
93 ` const map = new Map<string, { pkts: Named constant const map = new Map<string, { pkts:
number; bytes: number; country: string — value should number; bytes: number; country: string
}>();` not change. }>();
94 ` [Link](f => {` Source code line. [Link](f => {
95 ` const e = [Link]([Link]) ?? { Named constant const e = [Link]([Link]) ?? { pkts: 0,
pkts: 0, bytes: 0, country: [Link] ?? — value should bytes: 0, country: [Link] ?? 'Unkn
'Unknown' };` not change.
96 ` [Link] += [Link];` Executable [Link] += [Link];
statement.
97 ` [Link] += [Link];` Executable [Link] += [Link];
statement.
98 ` [Link]([Link], e);` Executable [Link]([Link], e);
statement.
99 ` });` Executable });
statement.
100 ` // Also fold in store packets if flows Comment Also fold in store packets if flows empty
empty` documenting
intent.
101 ` if ([Link] === 0 && Conditional if ([Link] === 0 &&
[Link] > 0) {` branch — run [Link] > 0) {
code only when
condition true.
102 ` [Link](p => {` Source code line. [Link](p => {
103 ` const e = [Link]([Link]) ?? { pkts: Named constant const e = [Link]([Link]) ?? { pkts: 0,
0, bytes: 0, country: '—' };` — value should bytes: 0, country: '—' };
not change.
104 ` [Link] += 1;` Executable [Link] += 1;
statement.
105 ` [Link] += [Link];` Executable [Link] += [Link];
statement.
106 ` [Link]([Link], e);` Executable [Link]([Link], e);
statement.
107 ` });` Executable });
statement.
108 ` }` Brace or C/C++ syntax structure.
parenthesis

Page 586 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
closing/opening a
block.
109 ` return [Link]([Link]())` Exit function and return [Link]([Link]())
give back a
value.
110 ` .map(([ip, v]) => ({ ip, ...v }))` Source code line. .map(([ip, v]) => ({ ip, ...v }))
111 ` .sort((a, b) => [Link] - [Link])` Source code line. .sort((a, b) => [Link] - [Link])
112 ` .slice(0, 10);` Executable .slice(0, 10);
statement.
113 ` }, [flows, storePackets]);` Executable }, [flows, storePackets]);
statement.
114 `` Blank line for Separator between code blocks.
readability.
115 ` // Conversations from flows` Comment Conversations from flows
documenting
intent.
116 ` const conversations = useMemo(() => {` Named constant const conversations = useMemo(() => {
— value should
not change.
117 ` return [Link](0, 8).map(f => ({` Exit function and return [Link](0, 8).map(f => ({
give back a
value.
118 ` src: `${[Link]}:${[Link]}`,` Source code line. src: `${[Link]}:${[Link]}`,
119 ` dst: `${[Link]}:${[Link]}`,` Source code line. dst: `${[Link]}:${[Link]}`,
120 ` pkts: [Link],` Source code line. pkts: [Link],
121 ` bytes: [Link],` Source code line. bytes: [Link],
122 ` proto: [Link],` Source code line. proto: [Link],
123 ` }));` Executable }));
statement.
124 ` }, [flows]);` Executable }, [flows]);
statement.
125 `` Blank line for Separator between code blocks.
readability.
126 ` // Bar chart data for protocol distribution` Comment Bar chart data for protocol distribution
documenting
intent.
127 ` const barData = useMemo(() =>` Named constant const barData = useMemo(() =>
— value should
not change.
128 ` [Link](0, 6).map(p => ({ Source code line. [Link](0, 6).map(p => ({
name: [Link], packets: [Link], bytes: name: [Link], packets: [Link], bytes:
[Link] })),` [Link] })),
129 ` [protoHierarchy]` Source code line. [protoHierarchy]
130 ` );` Executable );
statement.
131 `` Blank line for Separator between code blocks.
readability.

Page 587 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
132 ` const totalPackets = \ [Link]((s, f) => s + [Link], 0);`
[Link] \
133 `` Blank line for Separator between code blocks.
readability.
134 ` return (` Exit function and return (
give back a
value.
135 ` <div className="h-full flex flex-col bg- Source code line. <div className="h-full flex flex-col bg-
[var(--bg-void)] text-[var(--text-primary)] p- [var(--bg-void)] text-[var(--text-primary)]
6 overflow-auto gap-6">` p-6 overflow-aut
136 ` <div className="flex items-center Source code line. <div className="flex items-center
justify-between">` justify-between">
137 ` <h1 className="text-2xl font-bold Source code line. <h1 className="text-2xl font-bold font-
font-sans text-[var(--text-primary)]">Traffic sans text-[var(--text-primary)]">Traffic
Statistics</h1>` Statistics</h1>
138 ` <div className="flex items-center Source code line. <div className="flex items-center gap-4
gap-4 text-xs font-mono text-[var(--text- text-xs font-mono text-[var(--text-
muted)]">` muted)]">
139 ` Source code line. <span>{[Link]()}
<span>{[Link]()} total packets</span>
total packets</span>`
140 ` <span>{[Link]} pps</span>` Source code line. <span>{[Link]} pps</span>
141 ` <span>{[Link] > 0 ? ([Link] / Source code line. <span>{[Link] > 0 ? ([Link] /
1000000).toFixed(2) : '0.00'} 1000000).toFixed(2) : '0.00'}
Mbps</span>` Mbps</span>
142 ` </div>` Source code line. </div>
143 ` </div>` Source code line. </div>
144 `` Blank line for Separator between code blocks.
readability.
145 ` {/* I/O Graph */}` Source code line. {/* I/O Graph */}
146 ` <div className="bg-[var(--bg-base)] Source code line. <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] border border-[var(--border-default)]
rounded flex flex-col">` rounded flex flex-col">
147 ` <div className="px-4 py-3 border- Source code line. <div className="px-4 py-3 border-b
b border-[var(--border-subtle)] font-mono border-[var(--border-subtle)] font-mono
text-sm font-bold text-[var(--text...` text-sm font-bold text-[v
148 ` I/O Graph (Bytes/s)` Source code line. I/O Graph (Bytes/s)
149 ` {ioLoading && <Loader2 Source code line. {ioLoading && <Loader2 className="w-
className="w-3.5 h-3.5 animate-spin 3.5 h-3.5 animate-spin text-[var(--text-
text-[var(--text-muted)]" />}` muted)]" />}
150 ` {[Link] > 0 && <span Source code line. {[Link] > 0 && <span
className="text-[10px] text-[var(-- className="text-[10px] text-[var(--
normal)] ml-auto">● live</span>}` normal)] ml-auto">● live</span>}
151 ` </div>` Source code line. </div>
152 ` <div className="p-4 h-[280px]">` Source code line. <div className="p-4 h-[280px]">
153 ` {[Link] === 0 ? (` Source code line. {[Link] === 0 ? (
154 ` <EmptyState label="No traffic Source code line. <EmptyState label="No traffic data yet —
data yet — start capture" />` start capture" />
155 ` ) : (` Source code line. ):(

Page 588 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
156 ` <ResponsiveContainer Source code line. <ResponsiveContainer width="100%"
width="100%" height="100%">` height="100%">
157 ` <AreaChart data={ioData} Source code line. <AreaChart data={ioData} margin={{ top:
margin={{ top: 10, right: 10, left: 10, 10, right: 10, left: 10, bottom: 0 }}>
bottom: 0 }}>`
158 ` <defs>` Source code line. <defs>
159 ` <linearGradient id="colorIn" Source code line. <linearGradient id="colorIn" x1="0"
x1="0" y1="0" x2="0" y2="1">` y1="0" x2="0" y2="1">
160 ` <stop offset="5%" Source code line. <stop offset="5%" stopColor="#40C4FF"
stopColor="#40C4FF" stopOpacity={0.9} stopOpacity={0.9} />
/>`

Line Source Easy Technical Explanation


Explanation
161 ` <stop offset="95%" Source code <stop offset="95%" stopColor="#40C4FF"
stopColor="#40C4FF" stopOpacity={0.05} line. stopOpacity={0.05} />
/>`
162 ` </linearGradient>` Source code </linearGradient>
line.
163 ` <linearGradient id="colorOut" Source code <linearGradient id="colorOut" x1="0" y1="0"
x1="0" y1="0" x2="0" y2="1">` line. x2="0" y2="1">
164 ` <stop offset="5%" Source code <stop offset="5%" stopColor="#69F0AE"
stopColor="#69F0AE" stopOpacity={0.9} line. stopOpacity={0.9} />
/>`
165 ` <stop offset="95%" Source code <stop offset="95%" stopColor="#69F0AE"
stopColor="#69F0AE" stopOpacity={0.05} line. stopOpacity={0.05} />
/>`
166 ` </linearGradient>` Source code </linearGradient>
line.
167 ` </defs>` Source code </defs>
line.
168 ` <CartesianGrid Source code <CartesianGrid strokeDasharray="3 3"
strokeDasharray="3 3" stroke="var(-- line. stroke="var(--border-subtle)" vertical={false}
border-subtle)" vertical={false} />` />
169 ` <XAxis dataKey="time" Source code <XAxis dataKey="time" stroke="var(--text-
stroke="var(--text-muted)" tick={{ fontSize: line. muted)" tick={{ fontSize: 10, fontFamily:
10, fontFamily: 'monospace' }} int...` 'monospace' }} in
170 ` <YAxis stroke="var(--text- Source code <YAxis stroke="var(--text-muted)" tick={{
muted)" tick={{ fontSize: 10, fontFamily: line. fontSize: 10, fontFamily: 'monospace' }} />
'monospace' }} />`
171 ` <Tooltip` Source code <Tooltip
line.
172 ` contentStyle={{ Source code contentStyle={{ backgroundColor: 'var(--bg-
backgroundColor: 'var(--bg-overlay)', line. overlay)', borderColor: 'var(--border-strong)',
borderColor: 'var(--border-strong)', color: color: 'v
'...`
173 ` />` Source code />
line.
174 ` <Area type="monotone" Source code <Area type="monotone" dataKey="in"
dataKey="in" name="Bytes In" line. name="Bytes In" stroke="#40C4FF"
fill="url(#colorIn)" strokeWidth

Page 589 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
stroke="#40C4FF" fill="url(#colorIn)"
strokeWidth=...`
175 ` <Area type="monotone" Source code <Area type="monotone" dataKey="out"
dataKey="out" name="Bytes Out" line. name="Bytes Out" stroke="#69F0AE"
stroke="#69F0AE" fill="url(#colorOut)" fill="url(#colorOut)" strokeWi
strokeWid...`
176 ` </AreaChart>` Source code </AreaChart>
line.
177 ` </ResponsiveContainer>` Source code </ResponsiveContainer>
line.
178 ` )}` Source code )}
line.
179 ` </div>` Source code </div>
line.
180 ` </div>` Source code </div>
line.
181 `` Blank line for Separator between code blocks.
readability.
182 ` <div className="grid grid-cols-1 Source code <div className="grid grid-cols-1 lg:grid-
lg:grid-cols-2 gap-6">` line. cols-2 gap-6">
183 ` {/* Protocol Hierarchy */}` Source code {/* Protocol Hierarchy */}
line.
184 ` <div className="bg-[var(--bg-base)] Source code <div className="bg-[var(--bg-base)] border
border border-[var(--border-default)] line. border-[var(--border-default)] rounded flex
rounded flex flex-col">` flex-col">
185 ` <div className="px-4 py-3 border- Source code <div className="px-4 py-3 border-b
b border-[var(--border-subtle)] font-mono line. border-[var(--border-subtle)] font-mono text-
text-sm font-bold text-[var(--te...` sm font-bold text-[v
186 ` Protocol Hierarchy` Source code Protocol Hierarchy
line.
187 ` {protoLoading && <Loader2 Source code {protoLoading && <Loader2 className="w-
className="w-3.5 h-3.5 animate-spin line. 3.5 h-3.5 animate-spin text-[var(--text-
text-[var(--text-muted)]" />}` muted)]" />}
188 ` {[Link] > 0 && Source code {[Link] > 0 && <span
<span className="text-[10px] text-[var(-- line. className="text-[10px] text-[var(--normal)]
normal)] ml-auto">● live data</span>}` ml-auto">● live data<
189 ` </div>` Source code </div>
line.
190 ` <div className="p-4">` Source code <div className="p-4">
line.
191 ` {[Link] === 0 ? (` Source code {[Link] === 0 ? (
line.
192 ` <EmptyState label="No protocol Source code <EmptyState label="No protocol data" />
data" />` line.
193 ` ) : (` Source code ):(
line.
194 ` <div className="flex flex-col Source code <div className="flex flex-col gap-2 font-
gap-2 font-mono text-sm">` line. mono text-sm">
195 ` {[Link](p => (` Source code {[Link](p => (
line.

Page 590 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
196 ` <div key={[Link]}>` Source code <div key={[Link]}>
line.
197 ` <button` Source code <button
line.
198 ` className={`w-full flex Source code className={`w-full flex items-center gap-2
items-center gap-2 hover:bg-[var(--bg- line. hover:bg-[var(--bg-hover)] px-1 rounded
hover)] px-1 rounded transition-c...` transition-colors
199 ` onClick={() => Source code onClick={() => setActiveProto(activeProto
setActiveProto(activeProto === [Link] ? line. === [Link] ? null : [Link])}
null : [Link])}`
200 ` >` Source code >
line.
201 ` <span className="w-20 Source code <span className="w-20 text-left" style={{
text-left" style={{ color: [Link] line. color: [Link] }}>{[Link]}</span>
}}>{[Link]}</span>`
202 ` <div className="flex-1 h-2 Source code <div className="flex-1 h-2 bg-[var(--bg-
bg-[var(--bg-overlay)] rounded overflow- line. overlay)] rounded overflow-hidden">
hidden">`
203 ` <div className="h-full Source code <div className="h-full rounded transition-
rounded transition-all" style={{ width: line. all" style={{ width: `${[Link]}%`,
`${[Link]}%`, backgroundColor: ...` backgroundColor: [Link]
204 ` </div>` Source code </div>
line.
205 ` <span className="w-10 Source code <span className="w-10 text-right text-xs"
text-right text-xs" style={{ color: [Link] line. style={{ color: [Link] }}>{[Link]}%</span>
}}>{[Link]}%</span>`
206 ` <span className="w-20 Source code <span className="w-20 text-right text-
text-right text-[10px] text-[var(--text- line. [10px] text-[var(--text-
muted)]">{[Link]...` muted)]">{[Link]()}
207 ` </button>` Source code </button>
line.
208 ` {activeProto === [Link] && Source code {activeProto === [Link] && [Link] &&
[Link] && [Link] > 0 && (` line. [Link] > 0 && (
209 ` <div className="ml-4 mt-1 Source code <div className="ml-4 mt-1 space-y-1">
space-y-1">` line.
210 ` {[Link]((c: any, ci: Source code {[Link]((c: any, ci: number) => (
number) => (` line.
211 ` <div key={ci} Source code <div key={ci} className="flex items-center
className="flex items-center gap-2 px- line. gap-2 px-1">
1">`
212 ` <span className="w- Source code <span className="w-16 text-[10px] text-
16 text-[10px] text-[var(--text- line. [var(--text-secondary)]">{[Link]}</span>
secondary)]">{[Link]}</span>`
213 ` <div className="flex-1 Source code <div className="flex-1 h-1.5 bg-[var(--bg-
h-1.5 bg-[var(--bg-overlay)] rounded line. overlay)] rounded overflow-hidden">
overflow-hidden">`
214 ` <div className="h-full Source code <div className="h-full rounded" style={{
rounded" style={{` line.
215 ` width: \ 1)) * 100)}%`,`
`${[Link](([Link] / ([Link] \

Page 591 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
216 ` backgroundColor: Source code backgroundColor: [Link],
[Link],` line.
217 ` opacity: 0.6,` Source code opacity: 0.6,
line.
218 ` }} />` Source code }} />
line.
219 ` </div>` Source code </div>
line.
220 ` <span className="w- Source code <span className="w-16 text-right text-
16 text-right text-[9px] text-[var(--text- line. [9px] text-[var(--text-
muted)]">{[Link]...` muted)]">{[Link]()}</
221 ` </div>` Source code </div>
line.
222 ` ))}` Source code ))}
line.
223 ` </div>` Source code </div>
line.
224 ` )}` Source code )}
line.
225 ` </div>` Source code </div>
line.
226 ` ))}` Source code ))}
line.
227 ` </div>` Source code </div>
line.
228 ` )}` Source code )}
line.
229 ` </div>` Source code </div>
line.
230 ` </div>` Source code </div>
line.
231 `` Blank line for Separator between code blocks.
readability.
232 ` {/* Protocol Bar Chart */}` Source code {/* Protocol Bar Chart */}
line.
233 ` <div className="bg-[var(--bg-base)] Source code <div className="bg-[var(--bg-base)] border
border border-[var(--border-default)] line. border-[var(--border-default)] rounded flex
rounded flex flex-col">` flex-col">
234 ` <div className="px-4 py-3 border- Source code <div className="px-4 py-3 border-b
b border-[var(--border-subtle)] font-mono line. border-[var(--border-subtle)] font-mono text-
text-sm font-bold text-[var(--te...` sm font-bold text-[v
235 ` Protocol Distribution` Source code Protocol Distribution
line.
236 ` </div>` Source code </div>
line.
237 ` <div className="p-4 h-[220px]">` Source code <div className="p-4 h-[220px]">
line.
238 ` {[Link] === 0 ? (` Source code {[Link] === 0 ? (
line.

Page 592 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
239 ` <EmptyState label="No data" />` Source code <EmptyState label="No data" />
line.
240 ` ) : (` Source code ):(
line.

Line Source Easy Technical Explanation


Explanation
241 ` <ResponsiveContainer Source code <ResponsiveContainer width="100%"
width="100%" height="100%">` line. height="100%">
242 ` <BarChart data={barData} Source code <BarChart data={barData} margin={{ top:
margin={{ top: 5, right: 10, left: -20, bottom: line. 5, right: 10, left: -20, bottom: 5 }}>
5 }}>`
243 ` <CartesianGrid Source code <CartesianGrid strokeDasharray="3 3"
strokeDasharray="3 3" stroke="var(--border- line. stroke="var(--border-subtle)"
subtle)" vertical={false} />` vertical={false} />
244 ` <XAxis dataKey="name" Source code <XAxis dataKey="name" stroke="var(--
stroke="var(--text-muted)" tick={{ fontSize: line. text-muted)" tick={{ fontSize: 10,
10, fontFamily: 'monospace' }} />` fontFamily: 'monospace' }} />
245 ` <YAxis stroke="var(--text- Source code <YAxis stroke="var(--text-muted)" tick={{
muted)" tick={{ fontSize: 10, fontFamily: line. fontSize: 10, fontFamily: 'monospace' }} />
'monospace' }} />`
246 ` <Tooltip` Source code <Tooltip
line.
247 ` contentStyle={{ Source code contentStyle={{ backgroundColor: 'var(--
backgroundColor: 'var(--bg-overlay)', line. bg-overlay)', borderColor: 'var(--border-
borderColor: 'var(--border-strong)', color:...` strong)', color: 'v
248 ` />` Source code />
line.
249 ` <Bar dataKey="packets" Source code <Bar dataKey="packets" name="Packets"
name="Packets" radius={[2, 2, 0, 0]}>` line. radius={[2, 2, 0, 0]}>
250 ` {[Link]((_, i) => (` Source code {[Link]((_, i) => (
line.
251 ` <Cell key={i} Source code <Cell key={i} fill={PROTO_COLORS[i %
fill={PROTO_COLORS[i % line. PROTO_COLORS.length]} />
PROTO_COLORS.length]} />`
252 ` ))}` Source code ))}
line.
253 ` </Bar>` Source code </Bar>
line.
254 ` </BarChart>` Source code </BarChart>
line.
255 ` </ResponsiveContainer>` Source code </ResponsiveContainer>
line.
256 ` )}` Source code )}
line.
257 ` </div>` Source code </div>
line.
258 ` </div>` Source code </div>
line.

Page 593 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
259 ` </div>` Source code </div>
line.
260 `` Blank line for Separator between code blocks.
readability.
261 ` <div className="grid grid-cols-1 Source code <div className="grid grid-cols-1 lg:grid-
lg:grid-cols-2 gap-6 pb-6">` line. cols-2 gap-6 pb-6">
262 ` {/* Top Endpoints */}` Source code {/* Top Endpoints */}
line.
263 ` <div className="bg-[var(--bg-base)] Source code <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] line. border border-[var(--border-default)]
rounded flex flex-col">` rounded flex flex-col">
264 ` <div className="px-4 py-3 border-b Source code <div className="px-4 py-3 border-b
border-[var(--border-subtle)] font-mono text- line. border-[var(--border-subtle)] font-mono
sm font-bold text-[var(--te...` text-sm font-bold text-[v
265 ` Top Endpoints` Source code Top Endpoints
line.
266 ` {flowsLoading && <Loader2 Source code {flowsLoading && <Loader2
className="w-3.5 h-3.5 animate-spin text- line. className="w-3.5 h-3.5 animate-spin
[var(--text-muted)]" />}` text-[var(--text-muted)]" />}
267 ` </div>` Source code </div>
line.
268 ` {[Link] === 0 ? (` Source code {[Link] === 0 ? (
line.
269 ` <EmptyState label="No endpoint Source code <EmptyState label="No endpoint data yet"
data yet" />` line. />
270 ` ) : (` Source code ):(
line.
271 ` <table className="w-full text-sm Source code <table className="w-full text-sm font-
font-sans text-left">` line. sans text-left">
272 ` <thead className="bg-[var(--bg- Source code <thead className="bg-[var(--bg-overlay)]
overlay)] border-b border-[var(--border- line. border-b border-[var(--border-subtle)] text-
subtle)] text-xs text-[var(--tex...` xs text-[var(--
273 ` <tr>` Source code <tr>
line.
274 ` <th className="px-4 py- Source code <th className="px-4 py-2">Address</th>
2">Address</th>` line.
275 ` <th className="px-4 py- Source code <th className="px-4 py-2">Country</th>
2">Country</th>` line.
276 ` <th className="px-4 py-2 text- Source code <th className="px-4 py-2 text-
right">Packets</th>` line. right">Packets</th>
277 ` <th className="px-4 py-2 text- Source code <th className="px-4 py-2 text-
right">Bytes</th>` line. right">Bytes</th>
278 ` </tr>` Source code </tr>
line.
279 ` </thead>` Source code </thead>
line.
280 ` <tbody>` Source code <tbody>
line.

Page 594 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
281 ` {[Link]((ep, i) => (` Source code {[Link]((ep, i) => (
line.
282 ` <tr key={i} className="border- Source code <tr key={i} className="border-b border-
b border-[var(--border-subtle)] hover:bg- line. [var(--border-subtle)] hover:bg-[var(--bg-
[var(--bg-hover)]">` hover)]">
283 ` <td className="px-4 py-2 Source code <td className="px-4 py-2 font-mono font-
font-mono font-bold text-[var(-- line. bold text-[var(--accent)]">{[Link]}</td>
accent)]">{[Link]}</td>`
284 ` <td className="px-4 py-2 Source code <td className="px-4 py-2 text-xs text-
text-xs text-[var(--text- line. [var(--text-secondary)]">{[Link]}</td>
secondary)]">{[Link]}</td>`
285 ` <td className="px-4 py-2 Source code <td className="px-4 py-2 text-right font-
text-right font- line. mono">{[Link]()}</td>
mono">{[Link]()}</td>`
286 ` <td className="px-4 py-2 Source code <td className="px-4 py-2 text-right font-
text-right font-mono text-[var(--text- line. mono text-[var(--text-secondary)]">
secondary)]">`
287 ` {[Link] > 1024 * 1024 ? Source code {[Link] > 1024 * 1024 ? `${([Link] /
`${([Link] / 1024 / 1024).toFixed(1)} MB` : line. 1024 / 1024).toFixed(1)} MB` :
`${([Link] / 1024).to...` `${([Link] / 1024).toFixed
288 ` </td>` Source code </td>
line.
289 ` </tr>` Source code </tr>
line.
290 ` ))}` Source code ))}
line.
291 ` </tbody>` Source code </tbody>
line.
292 ` </table>` Source code </table>
line.
293 ` )}` Source code )}
line.
294 ` </div>` Source code </div>
line.
295 `` Blank line for Separator between code blocks.
readability.
296 ` {/* Conversations */}` Source code {/* Conversations */}
line.
297 ` <div className="bg-[var(--bg-base)] Source code <div className="bg-[var(--bg-base)]
border border-[var(--border-default)] line. border border-[var(--border-default)]
rounded flex flex-col">` rounded flex flex-col">
298 ` <div className="px-4 py-3 border-b Source code <div className="px-4 py-3 border-b
border-[var(--border-subtle)] font-mono text- line. border-[var(--border-subtle)] font-mono
sm font-bold text-[var(--te...` text-sm font-bold text-[v
299 ` Active Conversations` Source code Active Conversations
line.
300 ` </div>` Source code </div>
line.
301 ` {[Link] === 0 ? (` Source code {[Link] === 0 ? (
line.

Page 595 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
302 ` <EmptyState label="No Source code <EmptyState label="No conversation data
conversation data yet" />` line. yet" />
303 ` ) : (` Source code ):(
line.
304 ` <table className="w-full text-xs Source code <table className="w-full text-xs font-sans
font-sans text-left">` line. text-left">
305 ` <thead className="bg-[var(--bg- Source code <thead className="bg-[var(--bg-overlay)]
overlay)] border-b border-[var(--border- line. border-b border-[var(--border-subtle)] text-
subtle)] text-[9px] text-[var(--...` [9px] text-[var
306 ` <tr>` Source code <tr>
line.
307 ` <th className="px-4 py- Source code <th className="px-4 py-2">Source</th>
2">Source</th>` line.
308 ` <th className="px-4 py- Source code <th className="px-4 py-
2">Destination</th>` line. 2">Destination</th>
309 ` <th className="px-4 py- Source code <th className="px-4 py-2">Proto</th>
2">Proto</th>` line.
310 ` <th className="px-4 py-2 text- Source code <th className="px-4 py-2 text-
right">Pkts</th>` line. right">Pkts</th>
311 ` <th className="px-4 py-2 text- Source code <th className="px-4 py-2 text-
right">Bytes</th>` line. right">Bytes</th>
312 ` </tr>` Source code </tr>
line.
313 ` </thead>` Source code </thead>
line.
314 ` <tbody>` Source code <tbody>
line.
315 ` {[Link]((c, i) => (` Source code {[Link]((c, i) => (
line.
316 ` <tr key={i} className="border- Source code <tr key={i} className="border-b border-
b border-[var(--border-subtle)] hover:bg- line. [var(--border-subtle)] hover:bg-[var(--bg-
[var(--bg-hover)]">` hover)]">
317 ` <td className="px-4 py-1.5 Source code <td className="px-4 py-1.5 font-mono
font-mono text-[var(--text- line. text-[var(--text-primary)]">{[Link]}</td>
primary)]">{[Link]}</td>`
318 ` <td className="px-4 py-1.5 Source code <td className="px-4 py-1.5 font-mono
font-mono text-[var(--accent)]">{[Link]}</td>` line. text-[var(--accent)]">{[Link]}</td>
319 ` <td className="px-4 py-1.5 Source code <td className="px-4 py-1.5 font-mono
font-mono text-[var(--text-muted)] line. text-[var(--text-muted)]
uppercase">{[Link]}</td>` uppercase">{[Link]}</td>
320 ` <td className="px-4 py-1.5 Source code <td className="px-4 py-1.5 text-right
text-right font- line. font-mono">{[Link]()}</td>
mono">{[Link]()}</td>`

Line Source Easy Explanation Technical Explanation


321 ` <td className="px-4 py- Source code line. <td className="px-4 py-1.5 text-right
1.5 text-right font-mono text-[var(--text- font-mono text-[var(--text-
secondary)]">` secondary)]">

Page 596 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


322 ` {[Link] > 1024 * 1024 ? Source code line. {[Link] > 1024 * 1024 ? `${([Link] /
`${([Link] / 1024 / 1024).toFixed(1)} 1024 / 1024).toFixed(1)} MB` :
MB` : `${([Link] / 1024).toFix...` `${([Link] / 1024).toFixed(1)
323 ` </td>` Source code line. </td>
324 ` </tr>` Source code line. </tr>
325 ` ))}` Source code line. ))}
326 ` </tbody>` Source code line. </tbody>
327 ` </table>` Source code line. </table>
328 ` )}` Source code line. )}
329 ` </div>` Source code line. </div>
330 ` </div>` Source code line. </div>
331 ` </div>` Source code line. </div>
332 ` );` Executable statement. );
333 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

File: webwireshark/src/pages/[Link]
Total lines: 348

Line Source Easy Explanation Technical Explanation


1 `import { useState, useEffect, useRef, Executable statement. import { useState, useEffect, useRef,
useMemo } from 'react';` useMemo } from 'react';
2 `import { Globe, X } from 'lucide-react';` Executable statement. import { Globe, X } from 'lucide-react';
3 `import { useGetNadsFlows, Executable statement. import { useGetNadsFlows,
useGetThreatIps } from useGetThreatIps } from
'@workspace/api-client-react';` '@workspace/api-client-react';
4 `` Blank line for Separator between code blocks.
readability.
5 `// Simplified world map country shapes Comment Simplified world map country shapes
using approximate lat/lon → SVG documenting intent. using approximate lat/lon → SVG
projection` projection
6 `// Using Mercator-like projection: x = (lon Comment Using Mercator-like projection: x =
+ 180) / 360 * W, y = (90 - lat) / 180 * H` documenting intent. (lon + 180) / 360 * W, y = (90 - lat) /
180 * H
7 `` Blank line for Separator between code blocks.
readability.
8 `const W = 1000;` Named constant — const W = 1000;
value should not
change.
9 `const H = 500;` Named constant — const H = 500;
value should not
change.

Page 597 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


10 `` Blank line for Separator between code blocks.
readability.
11 `function project(lon: number, lat: Source code line. function project(lon: number, lat:
number): [number, number] {` number): [number, number] {
12 ` const x = ((lon + 180) / 360) * W;` Named constant — const x = ((lon + 180) / 360) * W;
value should not
change.
13 ` const y = ((90 - lat) / 180) * H;` Named constant — const y = ((90 - lat) / 180) * H;
value should not
change.
14 ` return [x, y];` Exit function and give return [x, y];
back a value.
15 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
16 `` Blank line for Separator between code blocks.
readability.
17 `// Simplified continent paths Comment Simplified continent paths
(approximate bezier outlines)` documenting intent. (approximate bezier outlines)
18 `const CONTINENT_PATHS = [` Named constant — const CONTINENT_PATHS = [
value should not
change.
19 ` // North America` Comment North America
documenting intent.
20 ` 'M 120,80 C 130,60 200,60 240,80 L Source code line. 'M 120,80 C 130,60 200,60 240,80 L
260,120 C 250,160 230,200 200,220 C 260,120 C 250,160 230,200 200,220
180,240 150,250 130,240 C 110,230 C 180,240 150,250 130,240 C 110
100,200 10...`
21 ` // South America` Comment South America
documenting intent.
22 ` 'M 200,240 C 210,250 220,280 Source code line. 'M 200,240 C 210,250 220,280
215,320 C 210,360 200,390 185,400 C 215,320 C 210,360 200,390 185,400
170,410 155,400 150,380 C 145,360 C 170,410 155,400 150,380 C
150,330 160,300 ...` 145,360 1
23 ` // Europe` Comment Europe
documenting intent.
24 ` 'M 450,60 C 480,50 520,55 540,70 C Source code line. 'M 450,60 C 480,50 520,55 540,70 C
550,85 545,110 530,120 C 510,130 550,85 545,110 530,120 C 510,130
480,125 460,115 C 440,105 440,80 480,125 460,115 C 440,105 440,80
450,60 Z',`
25 ` // Africa` Comment Africa
documenting intent.
26 ` 'M 470,140 C 500,130 540,135 Source code line. 'M 470,140 C 500,130 540,135
560,155 C 575,175 575,220 565,260 C 560,155 C 575,175 575,220 565,260
555,300 535,340 510,360 C 490,375 C 555,300 535,340 510,360 C
465,375 450,360 ...` 490,375 4
27 ` // Asia` Comment Asia
documenting intent.
28 ` 'M 540,50 C 600,40 700,45 770,65 C Source code line. 'M 540,50 C 600,40 700,45 770,65 C
820,80 850,110 850,140 C 850,170 820,80 850,110 850,140 C 850,170
820,195 770,210 C 720,225 650,225 820,195 770,210 C 720,225 650,22
600,210 C 550...`

Page 598 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


29 ` // Oceania` Comment Oceania
documenting intent.
30 ` 'M 760,300 C 790,295 830,300 Source code line. 'M 760,300 C 790,295 830,300
850,315 C 860,330 855,355 840,365 C 850,315 C 860,330 855,355 840,365
820,375 790,370 770,355 C 750,340 C 820,375 790,370 770,355 C
745,315 760,300 Z',` 750,340 7
31 `];` Executable statement. ];
32 `` Blank line for Separator between code blocks.
readability.
33 `interface GeoPoint {` Source code line. interface GeoPoint {
34 ` lat: number;` Executable statement. lat: number;
35 ` lon: number;` Executable statement. lon: number;
36 ` label: string;` Executable statement. label: string;
37 ` country: string;` Executable statement. country: string;
38 ` threatScore: number;` Executable statement. threatScore: number;
39 ` alerts: number;` Executable statement. alerts: number;
40 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
41 `` Blank line for Separator between code blocks.
readability.
42 `interface CountrySidebarData {` Source code line. interface CountrySidebarData {
43 ` country: string;` Executable statement. country: string;
44 ` threatScore: number;` Executable statement. threatScore: number;
45 ` alerts: number;` Executable statement. alerts: number;
46 ` flows: GeoPoint[];` Executable statement. flows: GeoPoint[];
47 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
48 `` Blank line for Separator between code blocks.
readability.
49 `const HOME = project(0, 51); // London Named constant — const HOME = project(0, 51); //
as "home" reference point` value should not London as "home" reference point
change.
50 `` Blank line for Separator between code blocks.
readability.
51 `const KNOWN_COUNTRIES: Named constant — const KNOWN_COUNTRIES:
Record<string, { lat: number; lon: value should not Record<string, { lat: number; lon:
number; flag: string }> = {` change. number; flag: string }
52 ` CN: { lat: 35.9, lon: 104.2, flag: '🌍🌍' },` Source code line. CN: { lat: 35.9, lon: 104.2, flag: '🌍🌍' },
53 ` RU: { lat: 61.5, lon: 105.3, flag: '🌍🌍' },` Source code line. RU: { lat: 61.5, lon: 105.3, flag: '🌍🌍' },
54 ` US: { lat: 37.1, lon: -95.7, flag: '🌍🌍' },` Source code line. US: { lat: 37.1, lon: -95.7, flag: '🌍🌍' },
55 ` NL: { lat: 52.1, lon: 5.3, flag: '🌍🌍' },` Source code line. NL: { lat: 52.1, lon: 5.3, flag: '🌍🌍' },
56 ` DE: { lat: 51.2, lon: 10.5, flag: '🌍🌍' },` Source code line. DE: { lat: 51.2, lon: 10.5, flag: '🌍🌍' },
57 ` BR: { lat: -14.2, lon: -51.9, flag: '🌍🌍' },` Source code line. BR: { lat: -14.2, lon: -51.9, flag: '🌍🌍' },
58 ` UA: { lat: 48.4, lon: 31.2, flag: '🌍🌍' },` Source code line. UA: { lat: 48.4, lon: 31.2, flag: '🌍🌍' },

Page 599 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


59 ` IR: { lat: 32.4, lon: 53.7, flag: '🌍🌍' },` Source code line. IR: { lat: 32.4, lon: 53.7, flag: '🌍🌍' },
60 ` KP: { lat: 40.3, lon: 127.5, flag: '🌍🌍' },` Source code line. KP: { lat: 40.3, lon: 127.5, flag: '🌍🌍' },
61 ` RO: { lat: 45.9, lon: 24.9, flag: '🌍🌍' },` Source code line. RO: { lat: 45.9, lon: 24.9, flag: '🌍🌍' },
62 ` TR: { lat: 38.9, lon: 35.2, flag: '🌍🌍' },` Source code line. TR: { lat: 38.9, lon: 35.2, flag: '🌍🌍' },
63 ` PK: { lat: 30.4, lon: 69.3, flag: '🌍🌍' },` Source code line. PK: { lat: 30.4, lon: 69.3, flag: '🌍🌍' },
64 ` GB: { lat: 55.4, lon: -3.4, flag: '🌍🌍' },` Source code line. GB: { lat: 55.4, lon: -3.4, flag: '🌍🌍' },
65 ` AU: { lat: -25.3, lon: 133.8, flag: '🌍🌍' },` Source code line. AU: { lat: -25.3, lon: 133.8, flag: '🌍🌍'
},
66 `};` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
67 `` Blank line for Separator between code blocks.
readability.
68 `function scoreColor(score: number): Source code line. function scoreColor(score: number):
string {` string {
69 ` if (score >= 0.8) return 'var(--critical)';` Conditional branch — if (score >= 0.8) return 'var(--critical)';
run code only when
condition true.
70 ` if (score >= 0.6) return 'var(--high)';` Conditional branch — if (score >= 0.6) return 'var(--high)';
run code only when
condition true.
71 ` if (score >= 0.4) return 'var(--medium)';` Conditional branch — if (score >= 0.4) return 'var(--
run code only when medium)';
condition true.
72 ` return 'var(--low)';` Exit function and give return 'var(--low)';
back a value.
73 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.
74 `` Blank line for Separator between code blocks.
readability.
75 `function ArcPath({ from, to, color, score Source code line. function ArcPath({ from, to, color,
}: {` score }: {
76 ` from: [number, number]; to: [number, Executable statement. from: [number, number]; to: [number,
number]; color: string; score: number;` number]; color: string; score: number;
77 `}) {` Source code line. }) {
78 ` const [x1, y1] = from;` Named constant — const [x1, y1] = from;
value should not
change.
79 ` const [x2, y2] = to;` Named constant — const [x2, y2] = to;
value should not
change.
80 ` const mx = (x1 + x2) / 2;` Named constant — const mx = (x1 + x2) / 2;
value should not
change.

Page 600 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
81 ` const my = [Link](y1, y2) - Named constant const my = [Link](y1, y2) -
[Link](x2 - x1) * 0.2 - 30;` — value should [Link](x2 - x1) * 0.2 - 30;
not change.
82 ` const d = `M ${x1} ${y1} Q ${mx} ${my} Named constant const d = `M ${x1} ${y1} Q ${mx} ${my}
${x2} ${y2}`;` — value should ${x2} ${y2}`;
not change.
83 ` const strokeW = [Link](0.8, Named constant const strokeW = [Link](0.8,
[Link](2.5, score * 3));` — value should [Link](2.5, score * 3));
not change.
84 ` const len = [Link]((x2 - x1) ** 2 + (y2 Named constant const len = [Link]((x2 - x1) ** 2 + (y2 -
- y1) ** 2) + [Link](y1 - my);` — value should y1) ** 2) + [Link](y1 - my);
not change.
85 `` Blank line for Separator between code blocks.
readability.
86 ` return (` Exit function and return (
give back a
value.
87 ` <path` Source code <path
line.
88 ` d={d}` Source code d={d}
line.
89 ` fill="none"` Source code fill="none"
line.
90 ` stroke={color}` Source code stroke={color}
line.
91 ` strokeWidth={strokeW}` Source code strokeWidth={strokeW}
line.
92 ` strokeOpacity={0.7}` Source code strokeOpacity={0.7}
line.
93 ` strokeDasharray={`${len * 0.15} ${len Source code strokeDasharray={`${len * 0.15} ${len *
* 0.85}`}` line. 0.85}`}
94 ` style={{ animation: `arc-travel ${1.2 + Source code style={{ animation: `arc-travel ${1.2 + (1 -
(1 - score)}s linear infinite` }}` line. score)}s linear infinite` }}
95 ` />` Source code />
line.
96 ` );` Executable );
statement.
97 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.
98 `` Blank line for Separator between code blocks.
readability.
99 `export default function ThreatMap() {` Source code export default function ThreatMap() {
line.
100 ` const [filter, setFilter] = useState<'all' \ 'critical' \ 'high' \
101 ` const [selectedCountry, null>(null);` Named constant — value should not
setSelectedCountry] = change.
useState<CountrySidebarData \

Page 601 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
102 ` const [hoveredPoint, setHoveredPoint] = null>(null);` Named constant — value should not
useState<{ x: number; y: number; label: change.
string } \
103 ` const svgRef = Named constant const svgRef =
useRef<SVGSVGElement>(null);` — value should useRef<SVGSVGElement>(null);
not change.
104 `` Blank line for Separator between code blocks.
readability.
105 ` const { data: flows } = Named constant const { data: flows } =
useGetNadsFlows(undefined, { query: { — value should useGetNadsFlows(undefined, { query: {
queryKey: ['threatmap-flows'] } });` not change. queryKey: ['threat
106 ` const { data: threatIps } = Named constant const { data: threatIps } =
useGetThreatIps(undefined, { query: { — value should useGetThreatIps(undefined, { query: {
queryKey: ['threatmap-ips'] } });` not change. queryKey: ['th
107 `` Blank line for Separator between code blocks.
readability.
108 ` const geoPoints = Named constant const geoPoints =
useMemo<GeoPoint[]>(() => {` — value should useMemo<GeoPoint[]>(() => {
not change.
109 ` const points: GeoPoint[] = [];` Named constant const points: GeoPoint[] = [];
— value should
not change.
110 ` const seen = new Set<string>();` Named constant const seen = new Set<string>();
— value should
not change.
111 `` Blank line for Separator between code blocks.
readability.
112 ` const rawIps = threatIps && Named constant const rawIps = threatIps &&
[Link] > 0 ? threatIps : [` — value should [Link] > 0 ? threatIps : [
not change.
113 ` { ip: '[Link]', country: 'China', Source code { ip: '[Link]', country: 'China',
countryCode: 'CN', alertCount: 14, line. countryCode: 'CN', alertCount: 14,
threatScore: 0.97, lat: 35.9, lon: 1...` threatScore: 0.97, lat: 3
114 ` { ip: '[Link]', country: 'Russia', Source code { ip: '[Link]', country: 'Russia',
countryCode: 'RU', alertCount: 9, line. countryCode: 'RU', alertCount: 9,
threatScore: 0.89, lat: 61.5, lon: ...` threatScore: 0.89, lat:
115 ` { ip: '[Link]', country: Source code { ip: '[Link]', country:
'Netherlands', countryCode: 'NL', line. 'Netherlands', countryCode: 'NL',
alertCount: 6, threatScore: 0.74, lat: 52.1, alertCount: 6, threatScore: 0.74, l
l...`
116 ` { ip: '[Link]', country: 'Brazil', Source code { ip: '[Link]', country: 'Brazil',
countryCode: 'BR', alertCount: 4, line. countryCode: 'BR', alertCount: 4,
threatScore: 0.61, lat: -14.2, lon: -...` threatScore: 0.61, lat: -1
117 ` { ip: '[Link]', country: Source code { ip: '[Link]', country: 'Ukraine',
'Ukraine', countryCode: 'UA', alertCount: 3, line. countryCode: 'UA', alertCount: 3,
threatScore: 0.55, lat: 48.4, lon...` threatScore: 0.55, lat
118 ` { ip: '[Link]', country: 'Iran', Source code { ip: '[Link]', country: 'Iran',
countryCode: 'IR', alertCount: 3, line. countryCode: 'IR', alertCount: 3,
threatScore: 0.52, lat: 32.4, lon: 53...` threatScore: 0.52, lat: 32
119 ` { ip: '[Link]', country: 'North Source code { ip: '[Link]', country: 'North
Korea', countryCode: 'KP', alertCount: 2, line. Korea', countryCode: 'KP', alertCount: 2,
threatScore: 0.48, lat: 40.3, ...` threatScore: 0.48,

Page 602 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
120 ` { ip: '[Link]', country: Source code { ip: '[Link]', country: 'Romania',
'Romania', countryCode: 'RO', alertCount: line. countryCode: 'RO', alertCount: 2,
2, threatScore: 0.43, lat: 45.9, lon:...` threatScore: 0.43, lat:
121 ` ];` Executable ];
statement.
122 `` Blank line for Separator between code blocks.
readability.
123 ` for (const ip of rawIps) {` Loop over items for (const ip of rawIps) {
or until condition
changes.
124 ` const code = [Link] ?? '';` Named constant const code = [Link] ?? '';
— value should
not change.
125 ` const geo = Named constant const geo =
KNOWN_COUNTRIES[code];` — value should KNOWN_COUNTRIES[code];
not change.
126 ` const lat = (ip as any).lat ?? geo?.lat;` Named constant const lat = (ip as any).lat ?? geo?.lat;
— value should
not change.
127 ` const lon = (ip as any).lon ?? Named constant const lon = (ip as any).lon ?? geo?.lon;
geo?.lon;` — value should
not change.
128 ` if (lat == null \ \ lon == null) continue;`
129 ` const key = Named constant const key =
`${[Link](lat)},${[Link](lon)}`;` — value should `${[Link](lat)},${[Link](lon)}`;
not change.
130 ` if ([Link](key)) continue;` Conditional if ([Link](key)) continue;
branch — run
code only when
condition true.
131 ` [Link](key);` Executable [Link](key);
statement.
132 ` [Link]({` Source code [Link]({
line.
133 ` lat, lon,` Source code lat, lon,
line.
134 ` label: `${[Link]} (${[Link]})`,` Source code label: `${[Link]} (${[Link]})`,
line.
135 ` country: [Link],` Source code country: [Link],
line.
136 ` threatScore: [Link],` Source code threatScore: [Link],
line.
137 ` alerts: [Link],` Source code alerts: [Link],
line.
138 ` });` Executable });
statement.
139 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/opening
a block.

Page 603 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
140 ` return points;` Exit function and return points;
give back a
value.
141 ` }, [threatIps]);` Executable }, [threatIps]);
statement.
142 `` Blank line for Separator between code blocks.
readability.
143 ` const visiblePoints = useMemo(() => {` Named constant const visiblePoints = useMemo(() => {
— value should
not change.
144 ` if (filter === 'all') return geoPoints;` Conditional if (filter === 'all') return geoPoints;
branch — run
code only when
condition true.
145 ` return [Link](p => {` Exit function and return [Link](p => {
give back a
value.
146 ` if (filter === 'critical') return Conditional if (filter === 'critical') return [Link]
[Link] >= 0.8;` branch — run >= 0.8;
code only when
condition true.
147 ` if (filter === 'high') return [Link] Conditional if (filter === 'high') return [Link]
>= 0.6 && [Link] < 0.8;` branch — run >= 0.6 && [Link] < 0.8;
code only when
condition true.
148 ` if (filter === 'medium') return Conditional if (filter === 'medium') return
[Link] >= 0.4 && [Link] < branch — run [Link] >= 0.4 && [Link] <
0.6;` code only when 0.6;
condition true.
149 ` return [Link] < 0.4;` Exit function and return [Link] < 0.4;
give back a
value.
150 ` });` Executable });
statement.
151 ` }, [geoPoints, filter]);` Executable }, [geoPoints, filter]);
statement.
152 `` Blank line for Separator between code blocks.
readability.
153 ` function handlePointClick(point: Source code function handlePointClick(point:
GeoPoint) {` line. GeoPoint) {
154 ` const related = [Link](p => Named constant const related = [Link](p =>
[Link] === [Link]);` — value should [Link] === [Link]);
not change.
155 ` setSelectedCountry({` Source code setSelectedCountry({
line.
156 ` country: [Link],` Source code country: [Link],
line.
157 ` threatScore: Source code threatScore: [Link](...[Link](p
[Link](...[Link](p => line. => [Link])),
[Link])),`
158 ` alerts: [Link]((s, p) => s + Source code alerts: [Link]((s, p) => s +
[Link], 0),` line. [Link], 0),

Page 604 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
159 ` flows: related,` Source code flows: related,
line.
160 ` });` Executable });
statement.

Lin Source Easy Technical Explanation


e Explanatio
n
161 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openi
ng a block.
162 `` Blank line for Separator between code blocks.
readability.
163 ` const FILTERS: Array<typeof filter> = ['all', Named const FILTERS: Array<typeof filter> = ['all',
'critical', 'high', 'medium', 'low'];` constant — 'critical', 'high', 'medium', 'low
value should
not change.
164 `` Blank line for Separator between code blocks.
readability.
165 ` return (` Exit function return (
and give
back a
value.
166 ` <div className="h-full flex bg-[var(--bg-void)] Source code <div className="h-full flex bg-[var(--bg-void)]
text-[var(--text-primary)] overflow-hidden line. text-[var(--text-primary)] overflow-hidden
relative">` relative"
167 ` {/* Map Area */}` Source code {/* Map Area */}
line.
168 ` <div className="flex-1 relative overflow- Source code <div className="flex-1 relative overflow-hidden
hidden bg-[#0C1018]">` line. bg-[#0C1018]">
169 ` {/* Grid */}` Source code {/* Grid */}
line.
170 ` <div className="absolute inset-0 bg- Source code <div className="absolute inset-0 bg-[linear-
[linear- line. gradient(rgba(255,89,73,0.03)_1px,transparent_
gradient(rgba(255,89,73,0.03)_1px,transparent_1 1px),linea
px),linear-gradien...`
171 `` Blank line for Separator between code blocks.
readability.
172 ` {/* Toolbar */}` Source code {/* Toolbar */}
line.
173 ` <div className="absolute top-4 left-4 z-20 Source code <div className="absolute top-4 left-4 z-20 flex
flex items-center gap-2 bg-[var(--bg-base)]/90 line. items-center gap-2 bg-[var(--bg-base)]/90
backdrop-blur borde...` backdrop-b
174 ` <Globe className="w-4 h-4 text-[var(-- Source code <Globe className="w-4 h-4 text-[var(--accent)]"
accent)]" />` line. />
175 ` <span className="font-mono font-bold Source code <span className="font-mono font-bold text-xs
text-xs text-[var(--text-primary)] mr-2">Global line. text-[var(--text-primary)] mr-2">Global Threat
Threat Map</span>` Map</spa
176 ` <div className="h-4 w-px bg-[var(-- Source code <div className="h-4 w-px bg-[var(--border-
border-strong)]" />` line. strong)]" />

Page 605 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
177 ` {[Link](f => (` Source code {[Link](f => (
line.
178 ` <button` Source code <button
line.
179 ` key={f}` Source code key={f}
line.
180 ` onClick={() => setFilter(f)}` Source code onClick={() => setFilter(f)}
line.
181 ` className={`px-2.5 py-1 rounded text- Source code className={`px-2.5 py-1 rounded text-[9px]
[9px] font-mono uppercase tracking-wider border line. font-mono uppercase tracking-wider border
transition-colors` transition-colo
182 ` ${filter === f` Source code ${filter === f
line.
183 ` ? 'border-[var(--accent)] text-[var(-- Source code ? 'border-[var(--accent)] text-[var(--accent)] bg-
accent)] bg-[var(--accent-dim)]'` line. [var(--accent-dim)]'
184 ` : 'border-transparent text-[var(--text- Source code : 'border-transparent text-[var(--text-secondary)]
secondary)] hover:border-[var(--border-strong)] line. hover:border-[var(--border-strong)] hover:text-[v
hover:text-[...`
185 ` >` Source code >
line.
186 ` {f}` Source code {f}
line.
187 ` </button>` Source code </button>
line.
188 ` ))}` Source code ))}
line.
189 ` </div>` Source code </div>
line.
190 `` Blank line for Separator between code blocks.
readability.
191 ` {/* SVG Map */}` Source code {/* SVG Map */}
line.
192 ` <svg` Source code <svg
line.
193 ` ref={svgRef}` Source code ref={svgRef}
line.
194 ` viewBox={`0 0 ${W} ${H}`}` Source code viewBox={`0 0 ${W} ${H}`}
line.
195 ` className="absolute inset-0 w-full h-full"` Source code className="absolute inset-0 w-full h-full"
line.
196 ` preserveAspectRatio="xMidYMid meet"` Source code preserveAspectRatio="xMidYMid meet"
line.
197 ` >` Source code >
line.
198 ` {/* Ocean background */}` Source code {/* Ocean background */}
line.
199 ` <rect width={W} height={H} fill="#0C1018" Source code <rect width={W} height={H} fill="#0C1018" />
/>` line.

Page 606 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
200 `` Blank line for Separator between code blocks.
readability.
201 ` {/* Latitude / longitude grid lines */}` Source code {/* Latitude / longitude grid lines */}
line.
202 ` {[-60, -30, 0, 30, 60].map(lat => {` Source code {[-60, -30, 0, 30, 60].map(lat => {
line.
203 ` const [, y] = project(0, lat);` Named const [, y] = project(0, lat);
constant —
value should
not change.
204 ` return <line key={lat} x1={0} y1={y} Exit function return <line key={lat} x1={0} y1={y} x2={W}
x2={W} y2={y} stroke="rgba(255,89,73,0.06)" and give y2={y} stroke="rgba(255,89,73,0.06)"
strokeWidth={0.5} />;` back a
value.
205 ` })}` Source code })}
line.
206 ` {[-150, -120, -90, -60, -30, 0, 30, 60, 90, Source code {[-150, -120, -90, -60, -30, 0, 30, 60, 90, 120,
120, 150].map(lon => {` line. 150].map(lon => {
207 ` const [x] = project(lon, 0);` Named const [x] = project(lon, 0);
constant —
value should
not change.
208 ` return <line key={lon} x1={x} y1={0} Exit function return <line key={lon} x1={x} y1={0} x2={x}
x2={x} y2={H} stroke="rgba(255,89,73,0.06)" and give y2={H} stroke="rgba(255,89,73,0.06)"
strokeWidth={0.5} />;` back a
value.
209 ` })}` Source code })}
line.
210 `` Blank line for Separator between code blocks.
readability.
211 ` {/* Continent fills */}` Source code {/* Continent fills */}
line.
212 ` {CONTINENT_PATHS.map((d, i) => (` Source code {CONTINENT_PATHS.map((d, i) => (
line.
213 ` <path key={i} d={d} fill="#0D1820" Source code <path key={i} d={d} fill="#0D1820"
stroke="rgba(255,89,73,0.12)" strokeWidth={0.8} line. stroke="rgba(255,89,73,0.12)" strokeWidth={0.8}
/>` />
214 ` ))}` Source code ))}
line.
215 `` Blank line for Separator between code blocks.
readability.
216 ` {/* Home node */}` Source code {/* Home node */}
line.
217 ` <circle cx={HOME[0]} cy={HOME[1]} r={6} Source code <circle cx={HOME[0]} cy={HOME[1]} r={6}
fill="var(--normal)" opacity={0.9} />` line. fill="var(--normal)" opacity={0.9} />
218 ` <circle cx={HOME[0]} cy={HOME[1]} Source code <circle cx={HOME[0]} cy={HOME[1]} r={12}
r={12} fill="none" stroke="var(--normal)" line. fill="none" stroke="var(--normal)"
strokeWidth={1} opacity={0.4} c...` strokeWidth={1} opacity=

Page 607 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
219 ` <text x={HOME[0] + 10} y={HOME[1] + 4} Source code <text x={HOME[0] + 10} y={HOME[1] + 4}
fontSize={8} fill="var(--normal)" line. fontSize={8} fill="var(--normal)"
fontFamily="monospace">HOME</text>` fontFamily="monospace">HOME
220 `` Blank line for Separator between code blocks.
readability.
221 ` {/* Arcs + threat points */}` Source code {/* Arcs + threat points */}
line.
222 ` {[Link]((point, i) => {` Source code {[Link]((point, i) => {
line.
223 ` const [px, py] = project([Link], Named const [px, py] = project([Link], [Link]);
[Link]);` constant —
value should
not change.
224 ` const color = Named const color = scoreColor([Link]);
scoreColor([Link]);` constant —
value should
not change.
225 ` return (` Exit function return (
and give
back a
value.
226 ` <g key={i}>` Source code <g key={i}>
line.
227 ` <ArcPath from={[px, py]} to={HOME} Source code <ArcPath from={[px, py]} to={HOME}
color={color} score={[Link]} />` line. color={color} score={[Link]} />
228 ` {/* Pulse ring for critical */}` Source code {/* Pulse ring for critical */}
line.
229 ` {[Link] >= 0.8 && (` Source code {[Link] >= 0.8 && (
line.
230 ` <circle cx={px} cy={py} r={10} Source code <circle cx={px} cy={py} r={10} fill="none"
fill="none" stroke={color} strokeWidth={1} line. stroke={color} strokeWidth={1} opacity={0.4}
opacity={0.4}`
231 ` style={{ animation: 'ping 1.5s ease- Source code style={{ animation: 'ping 1.5s ease-out infinite' }}
out infinite' }} />` line. />
232 ` )}` Source code )}
line.
233 ` {/* Main dot */}` Source code {/* Main dot */}
line.
234 ` <circle` Source code <circle
line.
235 ` cx={px} cy={py}` Source code cx={px} cy={py}
line.
236 ` r={[Link](3, [Link](8, Source code r={[Link](3, [Link](8, [Link] *
[Link] * 10))}` line. 10))}
237 ` fill={color}` Source code fill={color}
line.
238 ` opacity={0.85}` Source code opacity={0.85}
line.

Page 608 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanatio
n
239 ` style={{ cursor: 'pointer' }}` Source code style={{ cursor: 'pointer' }}
line.
240 ` onClick={() => Source code onClick={() => handlePointClick(point)}
handlePointClick(point)}` line.

Line Source Easy Technical Explanation


Explanation
241 ` onMouseEnter={(e) => {` Source code onMouseEnter={(e) => {
line.
242 ` const rect = Named const rect =
[Link]?.getBoundingClientRect();` constant — [Link]?.getBoundingClientRect();
value should
not change.
243 ` if (rect) setHoveredPoint({` Conditional if (rect) setHoveredPoint({
branch — run
code only
when
condition true.
244 ` x: [Link] - [Link],` Source code x: [Link] - [Link],
line.
245 ` y: [Link] - [Link],` Source code y: [Link] - [Link],
line.
246 ` label: `${[Link]} • Score: Source code label: `${[Link]} • Score:
${[Link]([Link] * 100)} • line. ${[Link]([Link] * 100)} •
Alerts: ${[Link]}`,` Alerts: ${[Link]}`,
247 ` });` Executable });
statement.
248 ` }}` Source code }}
line.
249 ` onMouseLeave={() => Source code onMouseLeave={() =>
setHoveredPoint(null)}` line. setHoveredPoint(null)}
250 ` />` Source code />
line.
251 ` </g>` Source code </g>
line.
252 ` );` Executable );
statement.
253 ` })}` Source code })}
line.
254 ` </svg>` Source code </svg>
line.
255 `` Blank line for Separator between code blocks.
readability.
256 ` {/* Hover tooltip */}` Source code {/* Hover tooltip */}
line.
257 ` {hoveredPoint && (` Source code {hoveredPoint && (
line.
258 ` <div` Source code <div
line.

Page 609 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
259 ` className="absolute pointer- Source code className="absolute pointer-events-none
events-none z-30 bg-[var(--bg-overlay)] line. z-30 bg-[var(--bg-overlay)] border border-
border border-[var(--border-strong)] ...` [var(--border-stro
260 ` style={{ left: hoveredPoint.x + 12, Source code style={{ left: hoveredPoint.x + 12, top:
top: hoveredPoint.y - 20 }}` line. hoveredPoint.y - 20 }}
261 ` >` Source code >
line.
262 ` {[Link]}` Source code {[Link]}
line.
263 ` </div>` Source code </div>
line.
264 ` )}` Source code )}
line.
265 `` Blank line for Separator between code blocks.
readability.
266 ` {/* Legend */}` Source code {/* Legend */}
line.
267 ` <div className="absolute bottom-4 Source code <div className="absolute bottom-4 left-4
left-4 z-20 bg-[var(--bg-base)]/80 backdrop- line. z-20 bg-[var(--bg-base)]/80 backdrop-blur
blur border border-[var(--borde...` border border-[va
268 ` <div className="text-[var(--text- Source code <div className="text-[var(--text-muted)]
muted)] uppercase tracking-wider mb- line. uppercase tracking-wider mb-2">Threat
2">Threat Score</div>` Score</div>
269 ` <div className="flex flex-col gap- Source code <div className="flex flex-col gap-1">
1">` line.
270 ` {[` Source code {[
line.
271 ` { label: '≥ 80 Critical', color: 'var(-- Source code { label: '≥ 80 Critical', color: 'var(--critical)' },
critical)' },` line.
272 ` { label: '60–79 High', color: 'var(-- Source code { label: '60–79 High', color: 'var(--high)' },
high)' },` line.
273 ` { label: '40–59 Medium', color: Source code { label: '40–59 Medium', color: 'var(--
'var(--medium)' },` line. medium)' },
274 ` { label: '< 40 Low', color: 'var(-- Source code { label: '< 40 Low', color: 'var(--low)' },
low)' },` line.
275 ` ].map(l => (` Source code ].map(l => (
line.
276 ` <div key={[Link]} Source code <div key={[Link]} className="flex items-
className="flex items-center gap-2">` line. center gap-2">
277 ` <div className="w-3 h-1.5 Source code <div className="w-3 h-1.5 rounded-full"
rounded-full" style={{ backgroundColor: line. style={{ backgroundColor: [Link] }} />
[Link] }} />`
278 ` <span className="text-[var(-- Source code <span className="text-[var(--text-
text-secondary)]">{[Link]}</span>` line. secondary)]">{[Link]}</span>
279 ` </div>` Source code </div>
line.
280 ` ))}` Source code ))}
line.

Page 610 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
281 ` </div>` Source code </div>
line.
282 ` <div className="mt-2 border-t Source code <div className="mt-2 border-t border-
border-[var(--border-subtle)] pt-2 text-[var(-- line. [var(--border-subtle)] pt-2 text-[var(--text-
text-muted)]">` muted)]">
283 ` Arc width = packet volume` Source code Arc width = packet volume
line.
284 ` </div>` Source code </div>
line.
285 ` </div>` Source code </div>
line.
286 ` </div>` Source code </div>
line.
287 `` Blank line for Separator between code blocks.
readability.
288 ` {/* Country Sidebar */}` Source code {/* Country Sidebar */}
line.
289 ` {selectedCountry && (` Source code {selectedCountry && (
line.
290 ` <div className="w-72 border-l Source code <div className="w-72 border-l border-
border-[var(--border-strong)] bg-[var(--bg- line. [var(--border-strong)] bg-[var(--bg-base)]
base)] flex flex-col shrink-0 z-10">` flex flex-col shrink
291 ` <div className="h-11 border-b Source code <div className="h-11 border-b border-
border-[var(--border-strong)] flex items- line. [var(--border-strong)] flex items-center
center justify-between px-4 shrink-0">` justify-between px-4 s
292 ` <span className="font-mono font- Source code <span className="font-mono font-bold
bold text-xs text-[var(--text-primary)] line. text-xs text-[var(--text-primary)]
truncate">{[Link]...` truncate">{selectedCountry.c
293 ` <button onClick={() => Source code <button onClick={() =>
setSelectedCountry(null)}` line. setSelectedCountry(null)}
294 ` className="w-6 h-6 flex items- Source code className="w-6 h-6 flex items-center
center justify-center rounded hover:bg- line. justify-center rounded hover:bg-[var(--bg-
[var(--bg-hover)] text-[var(--text...` hover)] text-[var(--t
295 ` <X className="w-3.5 h-3.5" />` Source code <X className="w-3.5 h-3.5" />
line.
296 ` </button>` Source code </button>
line.
297 ` </div>` Source code </div>
line.
298 ` <div className="flex-1 overflow- Source code <div className="flex-1 overflow-auto p-4
auto p-4 flex flex-col gap-4">` line. flex flex-col gap-4">
299 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)]
overlay)] rounded p-3 border border-[var(-- line. rounded p-3 border border-[var(--border-
border-subtle)]">` subtle)]">
300 ` <div className="font-mono text- Source code <div className="font-mono text-[9px] text-
[9px] text-[var(--text-muted)] uppercase line. [var(--text-muted)] uppercase tracking-
tracking-wider mb-1.5">Threat S...` wider mb-1.5">Threa
301 ` <div className="h-2 w-full bg- Source code <div className="h-2 w-full bg-[var(--bg-
[var(--bg-base)] rounded-full overflow- line. base)] rounded-full overflow-hidden">
hidden">`

Page 611 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
302 ` <div className="h-full rounded- Source code <div className="h-full rounded-full
full transition-all"` line. transition-all"
303 ` style={{ width: Source code style={{ width:
`${[Link]([Link] line. `${[Link]([Link]
* 100)}%`, backgroundColor: * 100)}%`, backgroundColor: scoreColor(sel
scoreColor(se...`
304 ` </div>` Source code </div>
line.
305 ` <div className="flex justify- Source code <div className="flex justify-between mt-
between mt-1.5 text-[10px] font-mono">` line. 1.5 text-[10px] font-mono">
306 ` <span className="text-[var(-- Source code <span className="text-[var(--text-
text-muted)]">Score</span>` line. muted)]">Score</span>
307 ` <span className="font-bold" Source code <span className="font-bold" style={{
style={{ color: line. color:
scoreColor([Link]) scoreColor([Link])
}}>` }}>
308 ` Source code {[Link]([Link] *
{[Link]([Link] * line. 100)}
100)}`
309 ` </span>` Source code </span>
line.
310 ` </div>` Source code </div>
line.
311 ` </div>` Source code </div>
line.
312 `` Blank line for Separator between code blocks.
readability.
313 ` <div className="grid grid-cols-2 Source code <div className="grid grid-cols-2 gap-2">
gap-2">` line.
314 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)]
overlay)] rounded p-3 border border-[var(-- line. rounded p-3 border border-[var(--border-
border-subtle)] text-center">` subtle)] text-center"
315 ` <div className="font-mono Source code <div className="font-mono text-[9px] text-
text-[9px] text-[var(--text-muted)] uppercase line. [var(--text-muted)] uppercase tracking-
tracking-wider mb-1">Alerts</...` wider mb-1">Alerts<
316 ` <div className="font-space Source code <div className="font-space font-bold text-
font-bold text-lg text-[var(-- line. lg text-[var(--
critical)]">{[Link]}</div>` critical)]">{[Link]}</div>
317 ` </div>` Source code </div>
line.
318 ` <div className="bg-[var(--bg- Source code <div className="bg-[var(--bg-overlay)]
overlay)] rounded p-3 border border-[var(-- line. rounded p-3 border border-[var(--border-
border-subtle)] text-center">` subtle)] text-center"
319 ` <div className="font-mono Source code <div className="font-mono text-[9px] text-
text-[9px] text-[var(--text-muted)] uppercase line. [var(--text-muted)] uppercase tracking-
tracking-wider mb-1">IPs</div>` wider mb-1">IPs</di
320 ` <div className="font-space Source code <div className="font-space font-bold text-
font-bold text-lg text-[var(--text- line. lg text-[var(--text-
primary)]">{[Link]...` primary)]">{[Link]

Page 612 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
321 ` </div>` Source code line. </div>
322 ` </div>` Source code line. </div>
323 `` Blank line for Separator between code blocks.
readability.
324 ` <div>` Source code line. <div>
325 ` <div className="font-mono Source code line. <div className="font-mono text-[9px]
text-[9px] text-[var(--text-muted)] text-[var(--text-muted)] uppercase
uppercase tracking-wider mb-2">Active tracking-wider mb-2">Active
Thr...`
326 ` <div className="flex flex-col Source code line. <div className="flex flex-col gap-1.5">
gap-1.5">`
327 ` {[Link]((f, Source code line. {[Link]((f, i) => (
i) => (`
328 ` <div key={i} className="bg- Source code line. <div key={i} className="bg-[var(--bg-
[var(--bg-overlay)] rounded p-2.5 border overlay)] rounded p-2.5 border border-
border-[var(--border-subtle)] h...` [var(--border-subtle)] ho
329 ` <div className="flex justify- Source code line. <div className="flex justify-between
between items-center">` items-center">
330 ` <span className="font- Source code line. <span className="font-mono text-
mono text-[10px] font-bold text-[var(-- [10px] font-bold text-[var(--accent)]">
accent)]">`
331 ` {[Link](' ')[0]}` Source code line. {[Link](' ')[0]}
332 ` </span>` Source code line. </span>
333 ` <span className="text- Source code line. <span className="text-[9px] px-1.5 py-
[9px] px-1.5 py-0.5 rounded font-bold text- 0.5 rounded font-bold text-white font-
white font-mono"` mono"
334 ` style={{ backgroundColor: Source code line. style={{ backgroundColor:
scoreColor([Link]) }}>` scoreColor([Link]) }}>
335 ` {[Link]([Link] Source code line. {[Link]([Link] * 100)}
* 100)}`
336 ` </span>` Source code line. </span>
337 ` </div>` Source code line. </div>
338 ` <div className="text-[9px] Source code line. <div className="text-[9px] text-[var(--
text-[var(--text-muted)] mt-0.5">{[Link]} text-muted)] mt-0.5">{[Link]}
alerts</div>` alerts</div>
339 ` </div>` Source code line. </div>
340 ` ))}` Source code line. ))}
341 ` </div>` Source code line. </div>
342 ` </div>` Source code line. </div>
343 ` </div>` Source code line. </div>
344 ` </div>` Source code line. </div>
345 ` )}` Source code line. )}
346 ` </div>` Source code line. </div>
347 ` );` Executable );
statement.

Page 613 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
348 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

File: webwireshark/src/pages/[Link]
Total lines: 21

Line Source Easy Explanation Technical Explanation


1 `import { Card, CardContent } from Executable statement. import { Card, CardContent } from
"@/components/ui/card";` "@/components/ui/card";
2 `import { AlertCircle } from "lucide- Executable statement. import { AlertCircle } from "lucide-
react";` react";
3 `` Blank line for Separator between code blocks.
readability.
4 `export default function NotFound() {` Source code line. export default function NotFound() {
5 ` return (` Exit function and give return (
back a value.
6 ` <div className="min-h-screen w-full Source code line. <div className="min-h-screen w-full
flex items-center justify-center bg-gray- flex items-center justify-center bg-
50">` gray-50">
7 ` <Card className="w-full max-w- Source code line. <Card className="w-full max-w-md
md mx-4">` mx-4">
8 ` <CardContent className="pt- Source code line. <CardContent className="pt-6">
6">`
9 ` <div className="flex mb-4 gap- Source code line. <div className="flex mb-4 gap-2">
2">`
10 ` <AlertCircle className="h-8 w- Source code line. <AlertCircle className="h-8 w-8 text-
8 text-red-500" />` red-500" />
11 ` <h1 className="text-2xl font- Source code line. <h1 className="text-2xl font-bold
bold text-gray-900">404 Page Not text-gray-900">404 Page Not
Found</h1>` Found</h1>
12 ` </div>` Source code line. </div>
13 `` Blank line for Separator between code blocks.
readability.
14 ` <p className="mt-4 text-sm Source code line. <p className="mt-4 text-sm text-
text-gray-600">` gray-600">
15 ` Did you forget to add the page Source code line. Did you forget to add the page to the
to the router?` router?
16 ` </p>` Source code line. </p>
17 ` </CardContent>` Source code line. </CardContent>
18 ` </Card>` Source code line. </Card>
19 ` </div>` Source code line. </div>
20 ` );` Executable statement. );

Page 614 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


21 `}` Brace or parenthesis C/C++ syntax structure.
closing/opening a
block.

File: webwireshark/src/components/layout/[Link]
Total lines: 29

Lin Source Easy Technical Explanation


e Explanation
1 `import React, { useEffect } from 'react';` Executable import React, { useEffect } from 'react';
statement.
2 `import { TitleBar } from './TitleBar';` Executable import { TitleBar } from './TitleBar';
statement.
3 `import { StatusBar } from './StatusBar';` Executable import { StatusBar } from './StatusBar';
statement.
4 `import { Sidebar } from './Sidebar';` Executable import { Sidebar } from './Sidebar';
statement.
5 `import { wsClient } from '@/lib/wsClient';` Executable import { wsClient } from '@/lib/wsClient';
statement.
6 `` Blank line for Separator between code blocks.
readability.
7 `export function MainLayout({ children }: { Source code export function MainLayout({ children }: {
children: [Link] }) {` line. children: [Link] }) {
8 ` useEffect(() => {` Source code useEffect(() => {
line.
9 ` // Add dark mode by default` Comment Add dark mode by default
documenting
intent.
10 ` Executable [Link]('dar
[Link]('dark' statement. k');
);`
11 ` [Link]();` Executable [Link]();
statement.
12 ` return () => {` Exit function return () => {
and give back
a value.
13 ` [Link]();` Executable [Link]();
statement.
14 ` };` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
15 ` }, []);` Executable }, []);
statement.
16 `` Blank line for Separator between code blocks.
readability.

Page 615 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
17 ` return (` Exit function return (
and give back
a value.
18 ` <div className="flex flex-col h-screen w-full Source code <div className="flex flex-col h-screen w-full
bg-[var(--bg-void)] overflow-hidden">` line. bg-[var(--bg-void)] overflow-hidden">
19 ` <TitleBar />` Source code <TitleBar />
line.
20 ` <div className="flex flex-1 overflow- Source code <div className="flex flex-1 overflow-hidden">
hidden">` line.
21 ` <Sidebar />` Source code <Sidebar />
line.
22 ` <main className="flex-1 overflow-hidden Source code <main className="flex-1 overflow-hidden
relative">` line. relative">
23 ` {children}` Source code {children}
line.
24 ` </main>` Source code </main>
line.
25 ` </div>` Source code </div>
line.
26 ` <StatusBar />` Source code <StatusBar />
line.
27 ` </div>` Source code </div>
line.
28 ` );` Executable );
statement.
29 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

File: webwireshark/src/components/layout/[Link]
Total lines: 53

Line Source Easy Explanation Technical Explanation


1 `import React from 'react';` Executable import React from 'react';
statement.
2 `import { Link, useLocation } from Executable import { Link, useLocation } from
'wouter';` statement. 'wouter';
3 `import { Radio, BarChart2, AlertTriangle, Executable import { Radio, BarChart2,
Activity, Globe, GitMerge, Settings } from statement. AlertTriangle, Activity, Globe,
'lucide-react';` GitMerge, Settings } from 'lucide-react';
4 `import { cn } from '@/lib/utils';` Executable import { cn } from '@/lib/utils';
statement.

Page 616 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


5 `import { Tooltip, TooltipContent, Executable import { Tooltip, TooltipContent,
TooltipTrigger } from statement. TooltipTrigger } from
'@/components/ui/tooltip';` '@/components/ui/tooltip';
6 `` Blank line for Separator between code blocks.
readability.
7 `const navItems = [` Named constant — const navItems = [
value should not
change.
8 ` { path: '/', icon: Radio, label: 'Capture' },` Source code line. { path: '/', icon: Radio, label: 'Capture'
},
9 ` { path: '/stats', icon: BarChart2, label: Source code line. { path: '/stats', icon: BarChart2, label:
'Statistics' },` 'Statistics' },
10 ` { path: '/alerts', icon: AlertTriangle, label: Source code line. { path: '/alerts', icon: AlertTriangle,
'Alerts' },` label: 'Alerts' },
11 ` { path: '/anomaly', icon: Activity, label: Source code line. { path: '/anomaly', icon: Activity, label:
'Anomaly' },` 'Anomaly' },
12 ` { path: '/threatmap', icon: Globe, label: Source code line. { path: '/threatmap', icon: Globe, label:
'Threat Map' },` 'Threat Map' },
13 ` { path: '/flows', icon: GitMerge, label: Source code line. { path: '/flows', icon: GitMerge, label:
'Flow Inspector' },` 'Flow Inspector' },
14 ` { path: '/settings', icon: Settings, label: Source code line. { path: '/settings', icon: Settings, label:
'Settings' },` 'Settings' },
15 `];` Executable ];
statement.
16 `` Blank line for Separator between code blocks.
readability.
17 `export function Sidebar() {` Source code line. export function Sidebar() {
18 ` const [location] = useLocation();` Named constant — const [location] = useLocation();
value should not
change.
19 `` Blank line for Separator between code blocks.
readability.
20 ` return (` Exit function and return (
give back a value.
21 ` <div className="w-[48px] hover:w- Source code line. <div className="w-[48px] hover:w-
[200px] transition-all duration-200 group [200px] transition-all duration-200
flex flex-col border-r border-[var(--b...` group flex flex-col border-r bo
22 ` <div className="flex-1 py-4 flex flex- Source code line. <div className="flex-1 py-4 flex flex-
col gap-2">` col gap-2">
23 ` {[Link]((item) => {` Source code line. {[Link]((item) => {
24 ` const isActive = location === Named constant — const isActive = location ===
[Link];` value should not [Link];
change.
25 ` return (` Exit function and return (
give back a value.
26 ` <Tooltip key={[Link]} Source code line. <Tooltip key={[Link]}
delayDuration={0}>` delayDuration={0}>
27 ` <TooltipTrigger asChild>` Source code line. <TooltipTrigger asChild>
28 ` <Link` Source code line. <Link

Page 617 of 629


NADS Complete Technical Reference

Line Source Easy Explanation Technical Explanation


29 ` href={[Link]}` Source code line. href={[Link]}
30 ` className={cn(` Source code line. className={cn(
31 ` "flex items-center h-10 px-3 Source code line. "flex items-center h-10 px-3 relative
relative text-[var(--text-secondary)] text-[var(--text-secondary)] hover:bg-
hover:bg-[var(--bg-hover)] hov...` [var(--bg-hover)] hover:
32 ` isActive && "text-[var(-- Source code line. isActive && "text-[var(--accent)] bg-
accent)] bg-[var(--bg-overlay)]"` [var(--bg-overlay)]"
33 ` )}` Source code line. )}
34 ` >` Source code line. >
35 ` {isActive && (` Source code line. {isActive && (
36 ` <div className="absolute Source code line. <div className="absolute left-0 top-0
left-0 top-0 bottom-0 w-0.5 bg-[var(-- bottom-0 w-0.5 bg-[var(--accent)]" />
accent)]" />`
37 ` )}` Source code line. )}
38 ` <[Link] className="w-5 Source code line. <[Link] className="w-5 h-5
h-5 shrink-0" />` shrink-0" />
39 ` <span className="ml-4 Source code line. <span className="ml-4 opacity-0
opacity-0 group-hover:opacity-100 group-hover:opacity-100 transition-
transition-opacity duration-200 font- opacity duration-200 font-medium"
medium">`
40 ` {[Link]}` Source code line. {[Link]}
41 ` </span>` Source code line. </span>
42 ` </Link>` Source code line. </Link>
43 ` </TooltipTrigger>` Source code line. </TooltipTrigger>
44 ` <TooltipContent side="right" Source code line. <TooltipContent side="right"
className="group-hover:hidden border- className="group-hover:hidden
[var(--border-default)] bg-[var(--bg-...` border-[var(--border-default)] bg-[var(--
45 ` {[Link]}` Source code line. {[Link]}
46 ` </TooltipContent>` Source code line. </TooltipContent>
47 ` </Tooltip>` Source code line. </Tooltip>
48 ` );` Executable );
statement.
49 ` })}` Source code line. })}
50 ` </div>` Source code line. </div>
51 ` </div>` Source code line. </div>
52 ` );` Executable );
statement.
53 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

File: webwireshark/src/components/layout/[Link]
Total lines: 100
Page 618 of 629
NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
1 `import React from 'react';` Executable import React from 'react';
statement.
2 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
3 `import { useGetCaptureStatus } from Executable import { useGetCaptureStatus } from
'@workspace/api-client-react';` statement. '@workspace/api-client-react';
4 `import { cn } from '@/lib/utils';` Executable import { cn } from '@/lib/utils';
statement.
5 `import { Wifi, WifiOff, Activity } from 'lucide- Executable import { Wifi, WifiOff, Activity } from 'lucide-
react';` statement. react';
6 `` Blank line for Separator between code blocks.
readability.
7 `export function StatusBar() {` Source code export function StatusBar() {
line.
8 ` const { captureState, stats, activeFlows, Named const { captureState, stats, activeFlows,
alertBadgeCount, wsConnected, packets, constant — alertBadgeCount, wsConnected, packets,
setCaptureState, setStats, setActi...` value should
not change.
9 `` Blank line for Separator between code blocks.
readability.
10 ` // Poll real capture status from backend` Comment Poll real capture status from backend
documenting
intent.
11 ` const { data: backendStatus, isError: Named const { data: backendStatus, isError:
statusError } = useGetCaptureStatus();` constant — statusError } = useGetCaptureStatus();
value should
not change.
12 `` Blank line for Separator between code blocks.
readability.
13 ` // Sync backend state → store` Comment Sync backend state → store
documenting
intent.
14 ` [Link](() => {` Source code [Link](() => {
line.
15 ` if (backendStatus) {` Conditional if (backendStatus) {
branch — run
code only
when
condition true.
16 ` if ([Link] && Conditional if ([Link] && [Link]
[Link] !== captureState) {` branch — run !== captureState) {
code only
when
condition true.
17 ` setCaptureState([Link]);` Executable setCaptureState([Link]);
statement.
18 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.

Page 619 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
19 ` if ([Link] != null \ \ [Link] != null) {`
20 ` setStats({` Source code setStats({
line.
21 ` pps: [Link] ?? [Link],` Source code pps: [Link] ?? [Link],
line.
22 ` bps: [Link] ?? [Link],` Source code bps: [Link] ?? [Link],
line.
23 ` totalPackets: [Link] ?? Source code totalPackets: [Link] ??
[Link],` line. [Link],
24 ` });` Executable });
statement.
25 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
26 ` }` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
27 ` }, [backendStatus]);` Executable }, [backendStatus]);
statement.
28 `` Blank line for Separator between code blocks.
readability.
29 ` const displayedPackets = [Link] \ \ [Link];`
30 `` Blank line for Separator between code blocks.
readability.
31 ` return (` Exit function return (
and give back
a value.
32 ` <div className="h-6 border-t border-[var(-- Source code <div className="h-6 border-t border-[var(--
border-default)] flex items-center justify-between line. border-default)] flex items-center justify-
px-4 bg-[var(--bg-b...` between px-4 b
33 ` {/* Left: capture state + WS */}` Source code {/* Left: capture state + WS */}
line.
34 ` <div className="flex items-center gap-3">` Source code <div className="flex items-center gap-3">
line.
35 ` <span` Source code <span
line.
36 ` className={cn(` Source code className={cn(
line.
37 ` "px-1.5 py-0.5 rounded text-[10px] font- Source code "px-1.5 py-0.5 rounded text-[10px] font-bold
bold tracking-wider",` line. tracking-wider",
38 ` captureState === 'capturing' && "bg- Source code captureState === 'capturing' && "bg-[var(--
[var(--normal)]/20 text-[var(--normal)]",` line. normal)]/20 text-[var(--normal)]",
39 ` captureState === 'idle' && "bg-[var(--bg- Source code captureState === 'idle' && "bg-[var(--bg-hover)]
hover)] text-[var(--text-muted)]",` line. text-[var(--text-muted)]",
40 ` captureState === 'paused' && "bg-[var(- Source code captureState === 'paused' && "bg-[var(--
-medium)]/20 text-[var(--medium)]",` line. medium)]/20 text-[var(--medium)]",

Page 620 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
41 ` captureState === 'stopped' && "bg- Source code captureState === 'stopped' && "bg-[var(--
[var(--critical)]/20 text-[var(--critical)]"` line. critical)]/20 text-[var(--critical)]"
42 ` )}` Source code )}
line.
43 ` >` Source code >
line.
44 ` {[Link]()}` Source code {[Link]()}
line.
45 ` {captureState === 'capturing' && (` Source code {captureState === 'capturing' && (
line.
46 ` <span className="inline-block w-1.5 h- Source code <span className="inline-block w-1.5 h-1.5
1.5 rounded-full bg-[var(--normal)] ml-1 animate- line. rounded-full bg-[var(--normal)] ml-1 animate-
pulse align-middle...` pulse align-m
47 ` )}` Source code )}
line.
48 ` </span>` Source code </span>
line.
49 `` Blank line for Separator between code blocks.
readability.
50 ` {/* WS connection indicator */}` Source code {/* WS connection indicator */}
line.
51 ` <span className={`flex items-center gap- Source code <span className={`flex items-center gap-1
1 text-[10px] ${wsConnected ? 'text-[var(-- line. text-[10px] ${wsConnected ? 'text-[var(--
normal)]' : 'text-[var(--t...` normal)]' : 'text
52 ` {wsConnected` Source code {wsConnected
line.
53 ` ? <Wifi className="w-3 h-3" />` Source code ? <Wifi className="w-3 h-3" />
line.
54 ` : <WifiOff className="w-3 h-3" />}` Source code : <WifiOff className="w-3 h-3" />}
line.
55 ` {wsConnected ? 'WS connected' : 'WS Source code {wsConnected ? 'WS connected' : 'WS offline'}
offline'}` line.
56 ` </span>` Source code </span>
line.
57 `` Blank line for Separator between code blocks.
readability.
58 ` {statusError && (` Source code {statusError && (
line.
59 ` <span className="text-[10px] text-[var(- Source code <span className="text-[10px] text-[var(--
-medium)]">· backend unreachable</span>` line. medium)]">· backend unreachable</span>
60 ` )}` Source code )}
line.
61 ` </div>` Source code </div>
line.
62 `` Blank line for Separator between code blocks.
readability.
63 ` {/* Center: packet counts */}` Source code {/* Center: packet counts */}
line.

Page 621 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
64 ` <div className="flex items-center text- Source code <div className="flex items-center text-[var(--
[var(--text-secondary)]">` line. text-secondary)]">
65 ` {displayedPackets > 0 ? (` Source code {displayedPackets > 0 ? (
line.
66 ` <>` Source code <>
line.
67 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-primary)]
primary)] font- line. font-
bold">{[Link]()}</spa bold">{[Link]()}</spa
n>` n>
68 ` <span className="mx- Source code <span className="mx-1">packets</span>
1">packets</span>` line.
69 ` {[Link] > 0 && Source code {[Link] > 0 && [Link] > 0
[Link] > 0 && [Link] !== line. && [Link] !== [Link] && (
[Link] && (`
70 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-muted)]">·
muted)]">· {[Link]()} in line. {[Link]()} in
buffer</span>` buffer</span>
71 ` )}` Source code )}
line.
72 ` </>` Source code </>
line.
73 ` ) : (` Source code ):(
line.
74 ` <span className="text-[var(--text- Source code <span className="text-[var(--text-muted)]">No
muted)]">No packets</span>` line. packets</span>
75 ` )}` Source code )}
line.
76 ` </div>` Source code </div>
line.
77 `` Blank line for Separator between code blocks.
readability.
78 ` {/* Right: rates + flows + alerts */}` Source code {/* Right: rates + flows + alerts */}
line.
79 ` <div className="flex items-center gap-4 Source code <div className="flex items-center gap-4 text-
text-[var(--text-secondary)]">` line. [var(--text-secondary)]">
80 ` {[Link] > 0 && (` Source code {[Link] > 0 && (
line.

Line Source Easy Technical Explanation


Explanation
81 ` <span className="flex items- Source code line. <span className="flex items-center
center gap-1">` gap-1">
82 ` <Activity className="w-3 h-3 Source code line. <Activity className="w-3 h-3 text-[var(--
text-[var(--accent)]" />` accent)]" />
83 ` {[Link]()} pps` Source code line. {[Link]()} pps
84 ` </span>` Source code line. </span>
85 ` )}` Source code line. )}

Page 622 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
86 ` {[Link] > 0 && (` Source code line. {[Link] > 0 && (
87 ` <span>{([Link] / Source code line. <span>{([Link] / 1000000).toFixed(1)}
1000000).toFixed(1)} Mbps</span>` Mbps</span>
88 ` )}` Source code line. )}
89 ` {activeFlows > 0 && (` Source code line. {activeFlows > 0 && (
90 ` Source code line. <span>{[Link]()}
<span>{[Link]()} flows</span>
flows</span>`
91 ` )}` Source code line. )}
92 ` {alertBadgeCount > 0 && (` Source code line. {alertBadgeCount > 0 && (
93 ` <span className="text-[var(-- Source code line. <span className="text-[var(--critical)]
critical)] flex items-center gap-1 font-bold flex items-center gap-1 font-bold
animate-pulse">` animate-pulse">
94 ` ⚠ {alertBadgeCount} alerts` Source code line. ⚠ {alertBadgeCount} alerts
95 ` </span>` Source code line. </span>
96 ` )}` Source code line. )}
97 ` </div>` Source code line. </div>
98 ` </div>` Source code line. </div>
99 ` );` Executable );
statement.
100 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

File: webwireshark/src/components/layout/[Link]
Total lines: 30

Line Source Easy Technical Explanation


Explanation
1 `import React from 'react';` Executable import React from 'react';
statement.
2 `import { useAppStore } from Executable import { useAppStore } from
'@/store/useAppStore';` statement. '@/store/useAppStore';
3 `import { cn } from '@/lib/utils';` Executable import { cn } from '@/lib/utils';
statement.
4 `` Blank line for Separator between code blocks.
readability.
5 `export function TitleBar() {` Source code line. export function TitleBar() {
6 ` const wsConnected = Named constant — const wsConnected =
useAppStore((state) => value should not useAppStore((state) =>
[Link]);` change. [Link]);

Page 623 of 629


NADS Complete Technical Reference

Line Source Easy Technical Explanation


Explanation
7 `` Blank line for Separator between code blocks.
readability.
8 ` return (` Exit function and return (
give back a value.
9 ` <div className="h-8 border-b border- Source code line. <div className="h-8 border-b border-
[var(--border-default)] flex items-center [var(--border-default)] flex items-center
justify-between px-4 bg-[var(--bg-b...` justify-between px-4 b
10 ` <div className="flex items-center Source code line. <div className="flex items-center
gap-4">` gap-4">
11 ` <span className="font-space font- Source code line. <span className="font-space font-
bold text-[var(--accent)] text-sm tracking- bold text-[var(--accent)] text-sm
wider">WebWireshark</span>` tracking-wider">WebWireshark</spa
12 ` <div className="flex items-center Source code line. <div className="flex items-center
gap-2">` gap-2">
13 ` <div` Source code line. <div
14 ` className={cn(` Source code line. className={cn(
15 ` "w-2 h-2 rounded-full",` Source code line. "w-2 h-2 rounded-full",
16 ` wsConnected ? "bg-[var(-- Source code line. wsConnected ? "bg-[var(--normal)]" :
normal)]" : "bg-[var(--critical)]"` "bg-[var(--critical)]"
17 ` )}` Source code line. )}
18 ` />` Source code line. />
19 ` <span className="text-xs text- Source code line. <span className="text-xs text-[var(--
[var(--text-muted)] font-mono">` text-muted)] font-mono">
20 ` {wsConnected ? 'Connected' : Source code line. {wsConnected ? 'Connected' :
'Disconnected'}` 'Disconnected'}
21 ` </span>` Source code line. </span>
22 ` </div>` Source code line. </div>
23 ` </div>` Source code line. </div>
24 ` <div className="flex items-center Source code line. <div className="flex items-center
gap-4 text-xs font-mono text-[var(--text- gap-4 text-xs font-mono text-[var(--
muted)]">` text-muted)]">
25 ` <span>Mem: 128.4 MB</span>` Source code line. <span>Mem: 128.4 MB</span>
26 ` <span>v2.1.0</span>` Source code line. <span>v2.1.0</span>
27 ` </div>` Source code line. </div>
28 ` </div>` Source code line. </div>
29 ` );` Executable );
statement.
30 `}` Brace or C/C++ syntax structure.
parenthesis
closing/opening a
block.

File: webwireshark/src/[Link]

Page 624 of 629


NADS Complete Technical Reference

Total lines: 49

Lin Source Easy Technical Explanation


e Explanation
1 `import React from 'react';` Executable import React from 'react';
statement.
2 `import { Switch, Route, Router as Executable import { Switch, Route, Router as WouterRouter
WouterRouter } from "wouter";` statement. } from "wouter";
3 `import { QueryClient, QueryClientProvider } Executable import { QueryClient, QueryClientProvider }
from "@tanstack/react-query";` statement. from "@tanstack/react-query";
4 `import { Toaster } from Executable import { Toaster } from
"@/components/ui/toaster";` statement. "@/components/ui/toaster";
5 `import { TooltipProvider } from Executable import { TooltipProvider } from
"@/components/ui/tooltip";` statement. "@/components/ui/tooltip";
6 `import NotFound from "@/pages/not-found";` Executable import NotFound from "@/pages/not-found";
statement.
7 `` Blank line for Separator between code blocks.
readability.
8 `import { MainLayout } from Executable import { MainLayout } from
"@/components/layout/MainLayout";` statement. "@/components/layout/MainLayout";
9 `import Capture from "@/pages/Capture";` Executable import Capture from "@/pages/Capture";
statement.
10 `import Stats from "@/pages/Stats";` Executable import Stats from "@/pages/Stats";
statement.
11 `import Alerts from "@/pages/Alerts";` Executable import Alerts from "@/pages/Alerts";
statement.
12 `import Anomaly from "@/pages/Anomaly";` Executable import Anomaly from "@/pages/Anomaly";
statement.
13 `import ThreatMap from "@/pages/ThreatMap";` Executable import ThreatMap from "@/pages/ThreatMap";
statement.
14 `import Flows from "@/pages/Flows";` Executable import Flows from "@/pages/Flows";
statement.
15 `import Settings from "@/pages/Settings";` Executable import Settings from "@/pages/Settings";
statement.
16 `` Blank line for Separator between code blocks.
readability.
17 `const queryClient = new QueryClient();` Named const queryClient = new QueryClient();
constant —
value should
not change.
18 `` Blank line for Separator between code blocks.
readability.
19 `function Router() {` Source code function Router() {
line.
20 ` return (` Exit function return (
and give back
a value.
21 ` <MainLayout>` Source code <MainLayout>
line.
22 ` <Switch>` Source code <Switch>
line.

Page 625 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
23 ` <Route path="/" component={Capture} />` Source code <Route path="/" component={Capture} />
line.
24 ` <Route path="/stats" component={Stats} Source code <Route path="/stats" component={Stats} />
/>` line.
25 ` <Route path="/alerts" component={Alerts} Source code <Route path="/alerts" component={Alerts} />
/>` line.
26 ` <Route path="/anomaly" Source code <Route path="/anomaly" component={Anomaly}
component={Anomaly} />` line. />
27 ` <Route path="/threatmap" Source code <Route path="/threatmap"
component={ThreatMap} />` line. component={ThreatMap} />
28 ` <Route path="/flows" component={Flows} Source code <Route path="/flows" component={Flows} />
/>` line.
29 ` <Route path="/settings" Source code <Route path="/settings" component={Settings}
component={Settings} />` line. />
30 ` <Route component={NotFound} />` Source code <Route component={NotFound} />
line.
31 ` </Switch>` Source code </Switch>
line.
32 ` </MainLayout>` Source code </MainLayout>
line.
33 ` );` Executable );
statement.
34 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
35 `` Blank line for Separator between code blocks.
readability.
36 `function App() {` Source code function App() {
line.
37 ` return (` Exit function return (
and give back
a value.
38 ` <QueryClientProvider client={queryClient}>` Source code <QueryClientProvider client={queryClient}>
line.
39 ` <TooltipProvider>` Source code <TooltipProvider>
line.
40 ` <WouterRouter Source code <WouterRouter
base={[Link].BASE_URL.replace(/\/$ line. base={[Link].BASE_URL.replace(/\/$
/, "")}>` /, "")}>
41 ` <Router />` Source code <Router />
line.
42 ` </WouterRouter>` Source code </WouterRouter>
line.
43 ` <Toaster />` Source code <Toaster />
line.
44 ` </TooltipProvider>` Source code </TooltipProvider>
line.

Page 626 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanation
45 ` </QueryClientProvider>` Source code </QueryClientProvider>
line.
46 ` );` Executable );
statement.
47 `}` Brace or C/C++ syntax structure.
parenthesis
closing/openin
g a block.
48 `` Blank line for Separator between code blocks.
readability.
49 `export default App;` Executable export default App;
statement.

File: webwireshark/src/[Link]
Total lines: 14

Lin Source Easy Technical Explanation


e Explanat
ion
1 `import React from 'react';` Executabl import React from 'react';
e
statement.
2 `import ReactDOM from 'react-dom/client';` Executabl import ReactDOM from 'react-dom/client';
e
statement.
3 `import App from './App';` Executabl import App from './App';
e
statement.
4 `import './[Link]';` Executabl import './[Link]';
e
statement.
5 `import { wsClient } from './lib/wsClient';` Executabl import { wsClient } from './lib/wsClient';
e
statement.
6 `` Blank line Separator between code blocks.
for
readability
.
7 `// Start WebSocket connection to NADS backend` Comment Start WebSocket connection to NADS backend
documenti
ng intent.
8 `[Link]();` Executabl [Link]();
e
statement.
9 `` Blank line Separator between code blocks.
for

Page 627 of 629


NADS Complete Technical Reference

Lin Source Easy Technical Explanation


e Explanat
ion
readability
.
10 `[Link]([Link] Source [Link]([Link]
('root')!).render(` code line. ('root')!).render(
11 ` <[Link]>` Source <[Link]>
code line.
12 ` <App />` Source <App />
code line.
13 ` </[Link]>` Source </[Link]>
code line.
14 `);` Executabl );
e
statement.

Page 628 of 629


NADS Complete Technical Reference

End of Document
NADS Complete Technical Reference — NADS_CODEBASE_GUIDE.md merged with
NADS_LINE_BY_LINE_COMPLETE.md

Page 629 of 629

You might also like