remoteid 0.2.2

Drone Remote ID (ASTM F3411-22a, EN 4709-002) in pure no_std Rust: decode, encode, track, and judge trust (spoof and plausibility verdicts, DRIP RFC 9575 Ed25519 verification)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
//! Trust decisions: is this Remote ID broadcast plausible, authenticated,
//! or spoofed?
//!
//! Remote ID frames are unauthenticated in almost every aircraft flying
//! today, and public tools broadcast fake drones from a laptop or a five
//! dollar microcontroller. A receiver that only decodes fields trusts all of
//! them. This module keeps per-transmitter evidence and grades it:
//!
//! | Verdict | Meaning |
//! |---|---|
//! | [`Verdict::Authenticated`] | DRIP signatures verify under a trusted key, the signed content matches what was received, and nothing contradicts it |
//! | [`Verdict::Plausible`] | Nothing contradicts the broadcast (the default for honest, unauthenticated aircraft) |
//! | [`Verdict::Suspicious`] | Physical or protocol inconsistencies a real transmitter rarely shows |
//! | [`Verdict::Spoofed`] | Strong evidence: a failed signature, a teleport, two transmitters sharing one identity, or the fingerprint of a known spoofing tool |
//!
//! The verdict is advice. Nothing is dropped, and every verdict comes with
//! the [`Reason`]s behind it and a score between 0 and 1.
//!
//! # What is checked
//!
//! * **Kinematics**: position jumps faster than [`TrustConfig::max_speed_mps`],
//!   sustained impossible speed, reported speed, course and vertical rate
//!   against the track actually flown (all with the transmitted accuracy as
//!   slack).
//! * **Time**: Location timestamps that freeze, run at the wrong rate, or
//!   disagree with the receiver's UTC clock; System and Auth timestamps far
//!   from the receiver's clock or zero in an F3411-22a message.
//! * **Counters**: one counter value reused for different content (two
//!   radios behind one address), repeated counter restarts.
//! * **Wi-Fi**: a TSF that is a Unix wall clock (software injectors write
//!   `time.time()`; real transmitters count microseconds since boot), a TSF
//!   that jumps against the receiver's clock.
//! * **Signal**: repeated large jumps in signal strength between frames.
//! * **Fingerprints** of two public spoofers, read from their source code:
//!   [cyber-defence-campus/droneRemoteIDSpoofer](https://github.com/cyber-defence-campus/droneRemoteIDSpoofer)
//!   and [jjshoots/RemoteIDSpoofer](https://github.com/jjshoots/RemoteIDSpoofer).
//! * **Identity**: serial numbers that break ANSI/CTA-2063-A, no Basic ID at
//!   all.
//! * **DRIP** (RFC 9575): signatures, through [`crate::auth`] with the
//!   `verify` feature; the authentication state follows RFC 9575 Appendix A.
//!
//! The std [`crate::Tracker`] adds checks across transmitters: one UAS ID
//! seen from two places at once, and several addresses sharing one radio
//! clock.
//!
//! # `no_std`
//!
//! [`TrustState`] needs no allocation. Feed it with
//! [`TrustState::observe`]; with the `verify` feature, completed
//! authentication messages are checked by [`TrustState::verify_pending`].

use core::fmt;

use crate::drip::{AssembledAuth, AuthAssembler, Det};
use crate::geo::FloatExt;
use crate::wifi::BeaconInfo;
use crate::{
    geo, Auth, Frame, IdType, Location, Message, SerialNumber, Transport, UasData, MESSAGE_SIZE,
};

/// Overall judgement of one transmitter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Verdict {
    /// Strong evidence the broadcast is fake or hijacked.
    Spoofed,
    /// Inconsistencies a real transmitter rarely shows.
    Suspicious,
    /// Nothing contradicts the broadcast.
    Plausible,
    /// Cryptographically authenticated and consistent.
    Authenticated,
}

impl Verdict {
    /// Lower case name.
    pub fn name(self) -> &'static str {
        match self {
            Verdict::Spoofed => "spoofed",
            Verdict::Suspicious => "suspicious",
            Verdict::Plausible => "plausible",
            Verdict::Authenticated => "authenticated",
        }
    }
}

impl fmt::Display for Verdict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// Public spoofing tools with a known fingerprint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Spoofer {
    /// cyber-defence-campus/droneRemoteIDSpoofer (Python, scapy, HCI).
    DroneRemoteIdSpoofer,
    /// jjshoots/RemoteIDSpoofer (ESP8266 / ESP32 Arduino).
    RemoteIdSpoofer,
}

impl Spoofer {
    /// Repository name.
    pub fn name(self) -> &'static str {
        match self {
            Spoofer::DroneRemoteIdSpoofer => "cyber-defence-campus/droneRemoteIDSpoofer",
            Spoofer::RemoteIdSpoofer => "jjshoots/RemoteIDSpoofer",
        }
    }
}

/// How much a reason weighs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Severity {
    /// Hint; two of them make a broadcast suspicious.
    Weak,
    /// Makes a broadcast suspicious; three different ones make it spoofed.
    Moderate,
    /// Makes a broadcast spoofed on its own.
    Strong,
}

macro_rules! reasons {
    ($( $(#[$m:meta])* $name:ident = $code:literal, $sev:ident, $label:literal; )*) => {
        /// Evidence behind a verdict.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
        #[repr(u8)]
        #[non_exhaustive]
        pub enum Reason { $( $(#[$m])* $name = $code, )* }

        impl Reason {
            /// Every reason, in code order.
            pub const ALL: &'static [Reason] = &[ $( Reason::$name, )* ];
            const COUNT: usize = [ $( $code, )* ].len();

            /// How much the reason weighs.
            pub fn severity(self) -> Severity {
                match self { $( Reason::$name => Severity::$sev, )* }
            }

            /// Stable snake case name (used by the JSON writer and Python).
            pub fn name(self) -> &'static str {
                match self { $( Reason::$name => $label, )* }
            }
        }
    };
}

reasons! {
    /// The fingerprint of a public spoofing tool ([`Assessment::spoofer`] says which).
    KnownSpoofer = 0, Strong, "known_spoofer";
    /// A DRIP signature or DET binding failed for this aircraft.
    AuthFailed = 1, Strong, "auth_failed";
    /// The position jumped further than the speed limit allows.
    Teleport = 2, Strong, "teleport";
    /// One counter value carried different content: two radios share an address.
    CounterConflict = 3, Strong, "counter_conflict";
    /// The same UAS ID is broadcast from another transmitter at an incompatible position.
    IdentityClone = 4, Strong, "identity_clone";
    /// The same UAS ID disagrees across transports (Bluetooth 4/5, Beacon, NAN).
    TransportDisagreement = 5, Strong, "transport_disagreement";
    /// The track flown is faster than any drone, over several windows.
    SpeedImplausible = 6, Moderate, "speed_implausible";
    /// Reported horizontal speed disagrees with the track flown.
    ReportedSpeedMismatch = 7, Moderate, "reported_speed_mismatch";
    /// Reported direction disagrees with the track flown.
    ReportedCourseMismatch = 8, Moderate, "reported_course_mismatch";
    /// Climb or descent rate is impossible or disagrees with the reported vertical speed.
    VerticalRateImplausible = 9, Moderate, "vertical_rate_implausible";
    /// Location timestamps stopped while the receiver clock ran.
    TimestampFrozen = 10, Moderate, "timestamp_frozen";
    /// Location timestamps run at the wrong rate or far from the receiver's UTC clock.
    LocationClockDrift = 11, Moderate, "location_clock_drift";
    /// System or Auth timestamps are zero (F3411-22a) or far from the receiver's UTC clock.
    SystemClockDrift = 12, Moderate, "system_clock_drift";
    /// The Wi-Fi TSF is a Unix wall clock, as software frame injectors write it.
    TsfWallClock = 13, Moderate, "tsf_wall_clock";
    /// The Wi-Fi TSF jumps against the receiver's clock.
    TsfDiscontinuity = 14, Moderate, "tsf_discontinuity";
    /// The message counter keeps restarting.
    CounterInterleave = 15, Moderate, "counter_interleave";
    /// Signal strength keeps jumping between consecutive frames.
    SignalJump = 16, Moderate, "signal_jump";
    /// Several transmitter addresses share one radio clock.
    SharedRadio = 17, Moderate, "shared_radio";
    /// Location fields outside their ranges or reserved codes.
    InvalidFields = 18, Moderate, "invalid_fields";
    /// A serial number Basic ID that breaks ANSI/CTA-2063-A.
    SerialFormat = 19, Weak, "serial_format";
    /// Locations for a while but never a Basic ID.
    NoBasicId = 20, Weak, "no_basic_id";
    /// A valid DRIP signature outside its VNB / VNA window (possible replay).
    AuthExpired = 21, Weak, "auth_expired";
}

impl fmt::Display for Reason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// A set of [`Reason`]s.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ReasonSet(u32);

impl ReasonSet {
    /// Adds a reason.
    pub fn insert(&mut self, r: Reason) {
        self.0 |= 1 << r as u8;
    }

    /// `true` if `r` is in the set.
    pub fn contains(&self, r: Reason) -> bool {
        self.0 & (1 << r as u8) != 0
    }

    /// `true` if empty.
    pub fn is_empty(&self) -> bool {
        self.0 == 0
    }

    /// Number of reasons.
    pub fn len(&self) -> usize {
        self.0.count_ones() as usize
    }

    /// The reasons in code order.
    pub fn iter(&self) -> impl Iterator<Item = Reason> + '_ {
        Reason::ALL
            .iter()
            .copied()
            .filter(move |r| self.contains(*r))
    }

    /// Number of reasons of a severity.
    pub fn count(&self, s: Severity) -> usize {
        self.iter().filter(|r| r.severity() == s).count()
    }
}

impl fmt::Debug for ReasonSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

/// DRIP authentication state, following RFC 9575 Appendix A.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AuthState {
    /// No authentication received.
    #[default]
    None,
    /// Pages received, no complete message yet.
    Partial,
    /// Complete messages of a type or scheme this receiver cannot check.
    Unsupported,
    /// Complete messages, but the key or data needed to verify is missing.
    Unverifiable,
    /// Signatures verify and signed content matches what was received.
    Verified,
    /// Verified, and the key chains to a trusted key.
    Trusted,
    /// Every checked message failed.
    Unverified,
    /// Both verified and failed messages.
    Questionable,
    /// Both trusted and failed messages.
    Conflicting,
}

impl AuthState {
    /// Lower case name.
    pub fn name(self) -> &'static str {
        match self {
            AuthState::None => "none",
            AuthState::Partial => "partial",
            AuthState::Unsupported => "unsupported",
            AuthState::Unverifiable => "unverifiable",
            AuthState::Verified => "verified",
            AuthState::Trusted => "trusted",
            AuthState::Unverified => "unverified",
            AuthState::Questionable => "questionable",
            AuthState::Conflicting => "conflicting",
        }
    }
}

/// A verdict with its evidence.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Assessment {
    /// The graded judgement.
    pub verdict: Verdict,
    /// 0 (certainly fake) to 1 (authenticated and consistent); 0.5 means no
    /// evidence either way.
    pub score: f32,
    /// Why.
    pub reasons: ReasonSet,
    /// Which tool, when [`Reason::KnownSpoofer`] is set.
    pub spoofer: Option<Spoofer>,
    /// DRIP authentication state.
    pub auth: AuthState,
}

impl Default for Assessment {
    fn default() -> Self {
        Assessment {
            verdict: Verdict::Plausible,
            score: 0.5,
            reasons: ReasonSet::default(),
            spoofer: None,
            auth: AuthState::None,
        }
    }
}

/// Settings for the trust checks. Times are milliseconds of the caller's
/// monotonic clock.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TrustConfig {
    /// Fastest believable ground speed, m/s (default 100, about 360 km/h:
    /// above racing drones, far below what spoofers produce by accident).
    pub max_speed_mps: f64,
    /// Fastest believable climb or descent, m/s (default 40).
    pub max_vertical_mps: f64,
    /// Position accuracy assumed when the transmitter says "unknown", m.
    pub default_accuracy_m: f64,
    /// Largest allowed gap between a Location timestamp and the receiver's
    /// UTC clock, seconds (default 30).
    pub max_location_drift_s: f64,
    /// Largest allowed gap between a System or Auth timestamp and the
    /// receiver's UTC clock, seconds (default 900).
    pub max_system_drift_s: f64,
    /// How long a reason stays active after its last supporting event
    /// (default 300 000 ms). Fingerprints never expire.
    pub memory_ms: u64,
    /// Count DRIP signatures under keys that are only self certified (no
    /// trusted parent) as authenticated. Default `false`: anyone can make a
    /// DET, only a registry endorsement says who owns it.
    pub accept_self_certified: bool,
    /// How recent the last content-validated signature must be for
    /// [`Verdict::Authenticated`] (default 30 000 ms; RFC 9575 asks for one
    /// every 5 s).
    pub auth_fresh_ms: u64,
    /// Clock skew allowed around DRIP VNB / VNA, seconds (default 120).
    pub auth_skew_s: u32,
    /// Grant [`Verdict::Authenticated`] only for signatures checked against
    /// their VNB / VNA window with a receiver UTC clock
    /// ([`Observation::unix_ms`]). Default `true`: without a clock a valid
    /// signature recorded earlier and replayed elsewhere cannot be told from
    /// a live one. The auth state still says `verified` or `trusted`.
    pub auth_requires_clock: bool,
    /// Number of different moderate reasons that make a transmitter
    /// [`Verdict::Spoofed`] with no strong reason. Default `None`: moderate
    /// evidence alone caps at [`Verdict::Suspicious`], because the
    /// kinematic and clock checks have not been measured on enough real
    /// flights to call an aircraft fake on them alone. `Some(3)` was the
    /// 0.2.0 behaviour.
    pub moderate_spoofed: Option<u8>,
    /// Evaluations needed before a ratio-based reason can fire (default 3).
    pub min_evaluations: u16,
    /// Match fingerprints of known spoofing tools (default `true`). Turn
    /// off to see what the generic checks find on their own.
    pub fingerprints: bool,
}

impl Default for TrustConfig {
    fn default() -> Self {
        TrustConfig {
            max_speed_mps: 100.0,
            max_vertical_mps: 40.0,
            default_accuracy_m: 30.0,
            max_location_drift_s: 30.0,
            max_system_drift_s: 900.0,
            memory_ms: 300_000,
            accept_self_certified: false,
            auth_fresh_ms: 30_000,
            auth_skew_s: 120,
            auth_requires_clock: true,
            moderate_spoofed: None,
            min_evaluations: 3,
            fingerprints: true,
        }
    }
}

/// One received Remote ID frame with what the receiver knows about it.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct Observation<'a> {
    /// Link it came on.
    pub transport: Transport,
    /// Message counter from the frame, if the transport has one.
    pub counter: Option<u8>,
    /// The message or message pack, header byte first, counter removed.
    pub payload: &'a [u8],
    /// Receiver monotonic clock, milliseconds.
    pub now_ms: u64,
    /// Receiver UTC clock, Unix milliseconds, if it is trustworthy (NTP or
    /// GNSS). Enables the absolute timestamp checks.
    pub unix_ms: Option<u64>,
    /// Signal strength, dBm.
    pub rssi_dbm: Option<i8>,
    /// Wi-Fi Beacon header fields (from [`crate::wifi::beacon_info`]).
    pub beacon: Option<BeaconInfo>,
    /// Which receiver heard the frame (RIDF `receiver_id`; 0 for a single
    /// receiver). Signal strength and Wi-Fi TSF continuity are tracked per
    /// receiver, since a near and a far receiver hear the same frame at
    /// very different levels.
    pub receiver_id: u16,
}

impl<'a> Observation<'a> {
    /// An observation with only the required fields.
    pub fn new(transport: Transport, counter: Option<u8>, payload: &'a [u8], now_ms: u64) -> Self {
        Observation {
            transport,
            counter,
            payload,
            now_ms,
            unix_ms: None,
            rssi_dbm: None,
            beacon: None,
            receiver_id: 0,
        }
    }

    /// Sets the receiver UTC clock.
    pub fn with_unix_ms(mut self, unix_ms: u64) -> Self {
        self.unix_ms = Some(unix_ms);
        self
    }

    /// Sets the signal strength.
    pub fn with_rssi(mut self, rssi_dbm: i8) -> Self {
        self.rssi_dbm = Some(rssi_dbm);
        self
    }

    /// Sets the Wi-Fi Beacon header fields.
    pub fn with_beacon(mut self, beacon: BeaconInfo) -> Self {
        self.beacon = Some(beacon);
        self
    }

    /// Sets the receiver that heard the frame.
    pub fn with_receiver(mut self, receiver_id: u16) -> Self {
        self.receiver_id = receiver_id;
        self
    }
}

/// Number of time buckets per [`TrustConfig::memory_ms`] window.
const BUCKETS: usize = 4;

/// Hits and evaluations of one rule, counted over a sliding window of
/// `memory_ms` (four buckets of a quarter each) and over the lifetime.
#[derive(Debug, Clone, Copy, Default)]
struct Tally {
    total: u16,
    last_hit_ms: u64,
    /// (bucket number, hits, evaluations).
    buckets: [(u32, u16, u16); BUCKETS],
}

impl Tally {
    fn record(&mut self, hit: bool, now: u64, bucket_ms: u64) {
        let epoch = (now / bucket_ms) as u32;
        let b = &mut self.buckets[epoch as usize % BUCKETS];
        if b.0 != epoch {
            *b = (epoch, 0, 0);
        }
        b.2 = b.2.saturating_add(1);
        if hit {
            b.1 = b.1.saturating_add(1);
            self.total = self.total.saturating_add(1);
            self.last_hit_ms = now;
        }
    }

    /// (hits, evaluations) in the window ending at `now`.
    fn window(&self, now: u64, bucket_ms: u64) -> (u32, u32) {
        let epoch = (now / bucket_ms) as u32;
        self.buckets
            .iter()
            .filter(|b| (b.1 > 0 || b.2 > 0) && epoch.wrapping_sub(b.0) < BUCKETS as u32)
            .fold((0, 0), |(h, e), b| (h + b.1 as u32, e + b.2 as u32))
    }
}

/// Tally slot (after the reasons) for single position outliers: one fix
/// far off the track that the next fix returns from.
const OUTLIER: usize = Reason::COUNT;

#[derive(Debug, Clone, Copy, Default)]
struct Fix {
    t: u64,
    lat: f64,
    lon: f64,
    alt: Option<f32>,
    speed: Option<f32>,
    dir: Option<f32>,
    vspeed: Option<f32>,
    hacc: f64,
    vacc: f64,
    ts: Option<f32>,
}

const FIXES: usize = 16;
const RECENT: usize = 16;
#[cfg(feature = "verify")]
const HASHES: usize = 48;
const COUNTER_SLOTS: usize = 8;
/// Receivers with their own signal and TSF continuity per transmitter.
const RECEIVERS: usize = 4;

/// The slot for `id` in a per-receiver table: its own, else a free one,
/// else the stalest.
fn receiver_slot<T: Copy>(table: &[Option<(u16, T, u64)>; RECEIVERS], id: u16) -> usize {
    if let Some(i) = table.iter().position(|e| e.is_some_and(|e| e.0 == id)) {
        return i;
    }
    if let Some(i) = table.iter().position(Option::is_none) {
        return i;
    }
    (0..RECEIVERS)
        .min_by_key(|&i| table[i].map_or(0, |e| e.2))
        .unwrap_or(0)
}

#[derive(Debug, Clone, Copy, Default)]
struct AuthTally {
    pages: u32,
    complete: u32,
    unsupported: u32,
    unverifiable: u32,
    valid: u32,
    invalid: u32,
    verified_ms: Option<u64>,
    trusted_ms: Option<u64>,
    /// As above, for signatures checked inside VNB / VNA against a receiver
    /// UTC clock.
    verified_clocked_ms: Option<u64>,
    trusted_clocked_ms: Option<u64>,
    any_verified: bool,
    any_trusted: bool,
    /// Signer of the latest verified signature (always one of the DETs the
    /// aircraft broadcasts).
    det: Option<Det>,
}

/// Per-transmitter trust evidence. No allocation. Measured with
/// `size_of` on x86_64: 7256 bytes with the `verify` feature, 6768 without.
#[derive(Debug, Clone)]
pub struct TrustState {
    data: UasData,
    frames: u64,
    decode_errors: u64,
    first_ms: Option<u64>,
    last_ms: u64,
    tallies: [Tally; Reason::COUNT + 1],
    bucket_ms: u64,
    spoofer: Option<Spoofer>,
    fixes: [Fix; FIXES],
    nfix: usize,
    /// The fix before a jump, while the fix after it is on probation.
    jump_from: Option<Fix>,
    /// A non zero Location timestamp has been seen.
    ts_nonzero: bool,
    last_window_ms: Option<u64>,
    locations: u32,
    counters: [[Option<(u8, u32, u64)>; COUNTER_SLOTS]; 6],
    /// (receiver, TSF, receiver time) per receiver.
    tsf: [Option<(u16, u64, u64)>; RECEIVERS],
    beacon: Option<BeaconInfo>,
    /// (receiver, RSSI, receiver time) per receiver.
    last_rssi: [Option<(u16, i8, u64)>; RECEIVERS],
    system_ts_zero: bool,
    transports: u8,
    recent: [[u8; MESSAGE_SIZE]; RECENT],
    nrecent: usize,
    #[cfg(feature = "verify")]
    hashes: [([u8; 8], u8, bool); HASHES],
    #[cfg(feature = "verify")]
    nhash: usize,
    assembler: AuthAssembler,
    pending: Option<AssembledAuth>,
    pack_msgs: [[u8; MESSAGE_SIZE]; 9],
    npack: usize,
    auth: AuthTally,
}

impl Default for TrustState {
    fn default() -> Self {
        TrustState {
            data: UasData::default(),
            frames: 0,
            decode_errors: 0,
            first_ms: None,
            last_ms: 0,
            tallies: [Tally::default(); Reason::COUNT + 1],
            bucket_ms: TrustConfig::default().memory_ms / BUCKETS as u64,
            spoofer: None,
            fixes: [Fix::default(); FIXES],
            nfix: 0,
            jump_from: None,
            ts_nonzero: false,
            last_window_ms: None,
            locations: 0,
            counters: [[None; COUNTER_SLOTS]; 6],
            tsf: [None; RECEIVERS],
            beacon: None,
            last_rssi: [None; RECEIVERS],
            system_ts_zero: false,
            transports: 0,
            recent: [[0; MESSAGE_SIZE]; RECENT],
            nrecent: 0,
            #[cfg(feature = "verify")]
            hashes: [([0; 8], 0, false); HASHES],
            #[cfg(feature = "verify")]
            nhash: 0,
            assembler: AuthAssembler::new(),
            pending: None,
            pack_msgs: [[0; MESSAGE_SIZE]; 9],
            npack: 0,
            auth: AuthTally::default(),
        }
    }
}

fn fnv1a(data: &[u8]) -> u32 {
    let mut h: u32 = 0x811C_9DC5;
    for b in data {
        h ^= *b as u32;
        h = h.wrapping_mul(0x0100_0193);
    }
    h
}

fn wrap_hour(mut x: f64) -> f64 {
    // Into [-1800, 1800).
    while x >= 1800.0 {
        x -= 3600.0;
    }
    while x < -1800.0 {
        x += 3600.0;
    }
    x
}

fn circular_mean_deg(sum_sin: f64, sum_cos: f64) -> f64 {
    let m = geo::atan2(sum_sin, sum_cos).to_degrees();
    if m < 0.0 {
        m + 360.0
    } else {
        m
    }
}

fn is_alnum16(s: &str) -> bool {
    s.len() == 16 && s.bytes().all(|c| c.is_ascii_alphanumeric())
}

impl TrustState {
    /// An empty state.
    pub fn new() -> Self {
        Self::default()
    }

    /// Everything decoded so far from this transmitter.
    pub fn data(&self) -> &UasData {
        &self.data
    }

    /// Frames seen.
    pub fn frames(&self) -> u64 {
        self.frames
    }

    /// Frames that failed to decode.
    pub fn decode_errors(&self) -> u64 {
        self.decode_errors
    }

    /// Transports this transmitter was heard on.
    pub fn transports(&self) -> impl Iterator<Item = Transport> + '_ {
        Transport::ALL
            .iter()
            .copied()
            .filter(move |t| self.transports & (1 << t.code()) != 0)
    }

    /// DETs broadcast in Basic ID messages.
    pub fn dets(&self) -> impl Iterator<Item = Det> + '_ {
        self.data
            .basic_id
            .iter()
            .flatten()
            .filter_map(Det::from_basic_id)
    }

    /// Records evidence from outside this transmitter (the std tracker uses
    /// it for [`Reason::IdentityClone`], [`Reason::TransportDisagreement`]
    /// and [`Reason::SharedRadio`]).
    pub fn note(&mut self, reason: Reason, now_ms: u64) {
        self.hit(reason, now_ms);
    }

    fn hit(&mut self, r: Reason, now: u64) {
        self.eval(r, true, now);
    }

    fn eval(&mut self, r: Reason, hit: bool, now: u64) {
        let bucket_ms = self.bucket_ms;
        self.tallies[r as usize].record(hit, now, bucket_ms);
    }

    fn active(&self, r: Reason, cfg: &TrustConfig, now: u64) -> bool {
        let t = &self.tallies[r as usize];
        if r == Reason::Teleport {
            // A jump that persisted counts 2, a single fix off the track
            // that the next fix came back from counts 1, over the last
            // `memory_ms`. One GPS glitch (1) or one jump (2) is not enough.
            let (jumps, _) = t.window(now, self.bucket_ms);
            let (outliers, _) = self.tallies[OUTLIER].window(now, self.bucket_ms);
            return 2 * jumps + outliers >= 3;
        }
        if t.total == 0 {
            return false;
        }
        if r == Reason::KnownSpoofer {
            // Fingerprints never expire.
            return true;
        }
        if now.saturating_sub(t.last_hit_ms) > cfg.memory_ms {
            return false;
        }
        // Counts and ratios over the last `memory_ms`, not the lifetime:
        // isolated events far apart never add up.
        let (hits, evals) = t.window(now, self.bucket_ms);
        let ratio = hits >= cfg.min_evaluations as u32 && hits * 2 >= evals;
        match r {
            Reason::KnownSpoofer | Reason::AuthFailed | Reason::TsfWallClock => true,
            Reason::SerialFormat | Reason::NoBasicId | Reason::AuthExpired => true,
            Reason::Teleport => unreachable!("handled above"),
            Reason::IdentityClone | Reason::TransportDisagreement => hits >= 2,
            Reason::SystemClockDrift | Reason::SharedRadio => hits >= 2,
            Reason::CounterConflict
            | Reason::TsfDiscontinuity
            | Reason::CounterInterleave
            | Reason::SignalJump
            | Reason::InvalidFields
            | Reason::TimestampFrozen => hits >= 3,
            Reason::SpeedImplausible
            | Reason::ReportedSpeedMismatch
            | Reason::ReportedCourseMismatch
            | Reason::VerticalRateImplausible
            | Reason::LocationClockDrift => ratio,
        }
    }

    /// Processes one frame and returns the updated assessment.
    pub fn observe(&mut self, cfg: &TrustConfig, obs: &Observation<'_>) -> Assessment {
        let now = obs.now_ms;
        self.bucket_ms = (cfg.memory_ms / BUCKETS as u64).max(1);
        self.frames += 1;
        self.first_ms.get_or_insert(now);
        self.last_ms = self.last_ms.max(now);
        self.transports |= 1 << obs.transport.code();

        if let Some(rssi) = obs.rssi_dbm {
            let i = receiver_slot(&self.last_rssi, obs.receiver_id);
            if let Some((id, prev, t)) = self.last_rssi[i] {
                if id == obs.receiver_id && now.saturating_sub(t) <= 500 {
                    let jump = (rssi as i16 - prev as i16).abs() >= 25;
                    self.eval(Reason::SignalJump, jump, now);
                }
            }
            self.last_rssi[i] = Some((obs.receiver_id, rssi, now));
        }

        if let Some(b) = obs.beacon {
            self.check_beacon(&b, obs.unix_ms, obs.receiver_id, now);
            self.beacon = Some(b);
        }

        let frame = match Frame::decode(obs.payload) {
            Ok(f) => f,
            Err(_) => {
                self.decode_errors += 1;
                return self.assessment(cfg, now);
            }
        };

        if let Some(c) = obs.counter {
            self.check_counter(obs.transport, &frame, c, obs.payload, now);
        }

        let mut auth_pages: [Option<Auth>; 9] = Default::default();
        let mut nauth = 0;
        self.npack = 0;
        let is_pack = matches!(frame, Frame::Pack(_));
        #[cfg(feature = "verify")]
        if is_pack {
            let has_loc =
                matches!(&frame, Frame::Pack(p) if p.raw_messages().any(|m| m[0] >> 4 == 1));
            self.push_hash(crate::auth::auth_hash(obs.payload), 15, has_loc);
        }
        let mut raws: [Option<[u8; MESSAGE_SIZE]>; 9] = [None; 9];
        match &frame {
            Frame::Message(_) => raws[0] = obs.payload[..MESSAGE_SIZE].try_into().ok(),
            Frame::Pack(p) => {
                for (slot, raw) in raws.iter_mut().zip(p.raw_messages()) {
                    *slot = Some(*raw);
                }
            }
        }
        for raw in raws.iter().flatten() {
            let Ok(msg) = Message::decode(raw) else {
                continue;
            };
            if raw[0] >> 4 != 2 {
                self.push_recent(raw);
                if is_pack && self.npack < 9 {
                    self.pack_msgs[self.npack] = *raw;
                    self.npack += 1;
                }
                #[cfg(feature = "verify")]
                if !is_pack {
                    self.push_hash(crate::auth::auth_hash(raw), raw[0] >> 4, false);
                }
            }
            self.data.update(&msg);
            match &msg {
                Message::Location(l) => self.on_location(cfg, l, obs.unix_ms, now),
                Message::System(s) => {
                    if s.protocol_version >= 1 && s.timestamp == 0 {
                        self.system_ts_zero = true;
                        self.hit(Reason::SystemClockDrift, now);
                    } else if let (Some(ts), Some(unix_ms)) = (s.unix_timestamp(), obs.unix_ms) {
                        let drift = (ts as f64 - unix_ms as f64 / 1000.0).fabs();
                        self.eval(
                            Reason::SystemClockDrift,
                            drift > cfg.max_system_drift_s,
                            now,
                        );
                    }
                }
                Message::Auth(a) => {
                    self.auth.pages += 1;
                    if is_pack {
                        if nauth < auth_pages.len() {
                            auth_pages[nauth] = Some(a.clone());
                            nauth += 1;
                        }
                    } else {
                        let mut out = AssembledAuth::default();
                        let counter = obs.counter.unwrap_or(0);
                        if self.assembler.push_legacy(a, counter, &mut out) {
                            self.complete_auth(out, obs.unix_ms, cfg, now);
                        }
                    }
                }
                _ => {}
            }
        }
        if nauth > 0 {
            let mut out = AssembledAuth::default();
            if AuthAssembler::push_pack(auth_pages.iter().flatten(), &mut out) {
                self.complete_auth(out, obs.unix_ms, cfg, now);
            }
        }
        self.check_identity(cfg, now);
        self.assessment(cfg, now)
    }

    fn complete_auth(
        &mut self,
        out: AssembledAuth,
        unix_ms: Option<u64>,
        cfg: &TrustConfig,
        now: u64,
    ) {
        self.auth.complete += 1;
        if let Some(unix_ms) = unix_ms {
            if out.timestamp == 0 && out.protocol_version >= 1 {
                self.hit(Reason::SystemClockDrift, now);
            } else if out.timestamp != 0 {
                let drift = (out.unix_timestamp() as f64 - unix_ms as f64 / 1000.0).fabs();
                self.eval(
                    Reason::SystemClockDrift,
                    drift > cfg.max_system_drift_s,
                    now,
                );
            }
        }
        self.pending = Some(out);
    }

    fn push_recent(&mut self, raw: &[u8; MESSAGE_SIZE]) {
        if self.recent[..self.nrecent.min(RECENT)].contains(raw) {
            return;
        }
        self.recent[self.nrecent % RECENT] = *raw;
        self.nrecent += 1;
    }

    #[cfg(feature = "verify")]
    fn push_hash(&mut self, h: [u8; 8], t: u8, has_loc: bool) {
        if self.hashes[..self.nhash.min(HASHES)]
            .iter()
            .any(|e| e.0 == h)
        {
            return;
        }
        self.hashes[self.nhash % HASHES] = (h, t, has_loc);
        self.nhash += 1;
    }

    fn check_counter(
        &mut self,
        transport: Transport,
        frame: &Frame<'_>,
        counter: u8,
        payload: &[u8],
        now: u64,
    ) {
        let slot = match frame {
            Frame::Pack(_) => 7,
            Frame::Message(m) => (u8::from(m.message_type()) as usize).min(6),
        };
        let hash = fnv1a(payload);
        let entry = &mut self.counters[transport.code() as usize % 6][slot];
        let mut conflict = false;
        let mut restart = false;
        if let Some((prev, prev_hash, t)) = *entry {
            if prev == counter && prev_hash != hash && now.saturating_sub(t) < 3_000 {
                conflict = true;
            }
            let step = counter.wrapping_sub(prev);
            if step > 128 && 256 - step as u16 > 8 {
                restart = true;
            }
        }
        *entry = Some((counter, hash, now));
        if conflict {
            self.hit(Reason::CounterConflict, now);
        }
        if restart {
            self.hit(Reason::CounterInterleave, now);
        }
    }

    fn check_beacon(&mut self, b: &BeaconInfo, unix_ms: Option<u64>, receiver: u16, now: u64) {
        // 1e15 us is 31.7 years of uptime: only a wall clock gets there.
        let wall = match unix_ms {
            Some(u) => {
                b.tsf >= 1_000_000_000_000_000 || (b.tsf / 1000).abs_diff(u) < 400 * 86_400_000
            }
            None => b.tsf >= 1_000_000_000_000_000,
        };
        if wall {
            self.hit(Reason::TsfWallClock, now);
        }
        let i = receiver_slot(&self.tsf, receiver);
        if let Some((id, prev_tsf, prev_now)) = self.tsf[i] {
            if id == receiver && b.tsf != 0 && prev_tsf != 0 {
                let drx = now.saturating_sub(prev_now) as f64;
                let dtsf = (b.tsf as f64 - prev_tsf as f64) / 1000.0;
                let jump = dtsf < 0.0 || (dtsf - drx).fabs() > 500.0 + 0.05 * drx;
                self.eval(Reason::TsfDiscontinuity, jump, now);
            }
        }
        self.tsf[i] = Some((receiver, b.tsf, now));
    }

    fn on_location(&mut self, cfg: &TrustConfig, l: &Location, unix_ms: Option<u64>, now: u64) {
        let issues = l.check().count();
        if issues > 0 {
            self.hit(Reason::InvalidFields, now);
        }
        let Some((lat, lon)) = l.position() else {
            return;
        };
        if issues > 0 {
            return;
        }
        self.locations += 1;
        let acc = |m: Option<f32>| m.map_or(cfg.default_accuracy_m, |v| v as f64);
        let fix = Fix {
            t: now,
            lat,
            lon,
            alt: l.altitude_geo.or(l.altitude_baro),
            speed: l.speed_horizontal,
            dir: l.direction,
            vspeed: l.speed_vertical,
            hacc: acc(l.horizontal_accuracy.meters()),
            vacc: acc(l.vertical_accuracy.meters()),
            // Raw 0 (0.0 s past the hour) is what transmitters that never fill
            // the field send, the Open Drone ID sample units included, so it
            // counts as "not provided" rather than as a frozen clock, until
            // the transmitter has sent a non zero one.
            ts: l.timestamp.filter(|t| *t != 0.0 || self.ts_nonzero),
        };
        if fix.ts.is_some_and(|t| t != 0.0) {
            self.ts_nonzero = true;
        }

        if let (Some(ts), Some(unix_ms)) = (fix.ts, unix_ms) {
            let rx = (unix_ms % 3_600_000) as f64 / 1000.0;
            let drift = wrap_hour(ts as f64 - rx).fabs();
            self.eval(
                Reason::LocationClockDrift,
                drift > cfg.max_location_drift_s,
                now,
            );
        }

        let reachable = |from: &Fix| {
            let dt = now.saturating_sub(from.t) as f64 / 1000.0;
            let d = geo::distance_m(from.lat, from.lon, lat, lon);
            d <= 50.0 || d <= from.hacc + fix.hacc + cfg.max_speed_mps * dt
        };
        // The previous fix jumped away from `jump_from`: if this one is back
        // near the track, the jump was one bad fix (a GNSS outlier); drop it.
        // If not, the jump stuck.
        let mut stuck = false;
        if let Some(before) = self.jump_from.take() {
            if reachable(&before) {
                self.nfix -= 1;
                let bucket_ms = self.bucket_ms;
                self.tallies[OUTLIER].record(true, now, bucket_ms);
            } else {
                self.hit(Reason::Teleport, now);
                stuck = true;
            }
        }
        let mut jumped = false;
        if self.nfix > 0 {
            let prev = self.fixes[(self.nfix - 1) % FIXES];
            if now.saturating_sub(prev.t) >= 50 && !reachable(&prev) {
                // Judged when the next fix arrives.
                self.jump_from = Some(prev);
                jumped = true;
            }
        }
        self.fixes[self.nfix % FIXES] = fix;
        self.nfix += 1;
        if jumped && !stuck {
            // No window statistics across a fix that may be a single outlier
            // on an otherwise steady track.
            return;
        }

        if self
            .last_window_ms
            .is_some_and(|t| now.saturating_sub(t) < 1000)
        {
            return;
        }
        // Anchor: the newest fix at least 2 s old (and at most 15 s).
        let held = self.nfix.min(FIXES);
        let mut anchor = None;
        for k in 1..held {
            let f = self.fixes[(self.nfix - 1 - k) % FIXES];
            let age = now.saturating_sub(f.t);
            if age > 15_000 {
                break;
            }
            if age >= 2_000 {
                anchor = Some((k, f));
                break;
            }
        }
        let Some((k, a)) = anchor else { return };
        self.last_window_ms = Some(now);
        let dt = now.saturating_sub(a.t) as f64 / 1000.0;
        let d = geo::distance_m(a.lat, a.lon, lat, lon);
        let slack_v = (a.hacc + fix.hacc) / dt;
        let v_obs = d / dt;
        self.eval(
            Reason::SpeedImplausible,
            v_obs - slack_v > cfg.max_speed_mps,
            now,
        );

        // Reported values over the window (fixes newer than the anchor).
        let (mut sp, mut nsp, mut ss, mut sc, mut ndir, mut vs, mut nvs) =
            (0.0, 0, 0.0, 0.0, 0, 0.0, 0);
        for j in 0..k {
            let f = self.fixes[(self.nfix - 1 - j) % FIXES];
            if let Some(s) = f.speed {
                sp += s as f64;
                nsp += 1;
            }
            if let Some(dir) = f.dir {
                ss += geo::sin((dir as f64).to_radians());
                sc += geo::cos((dir as f64).to_radians());
                ndir += 1;
            }
            if let Some(v) = f.vspeed {
                vs += v as f64;
                nvs += 1;
            }
        }
        if nsp > 0 {
            let v_rep = sp / nsp as f64;
            let tol = 3.0 + 0.3 * v_obs.max(v_rep) + slack_v;
            self.eval(
                Reason::ReportedSpeedMismatch,
                (v_obs - v_rep).fabs() > tol,
                now,
            );
            if ndir > 0 && v_rep >= 3.0 && v_obs - slack_v >= 3.0 {
                let course = geo::bearing_deg(a.lat, a.lon, lat, lon);
                let dir = circular_mean_deg(ss, sc);
                self.eval(
                    Reason::ReportedCourseMismatch,
                    geo::angle_diff_deg(course, dir) > 45.0,
                    now,
                );
            }
        }
        if let (Some(h0), Some(h1)) = (a.alt, fix.alt) {
            let rate = (h1 - h0) as f64 / dt;
            let vslack = (a.vacc + fix.vacc) / dt;
            let mut bad = rate.fabs() - vslack > cfg.max_vertical_mps;
            if nvs > 0 {
                let v_rep = vs / nvs as f64;
                bad |= (rate - v_rep).fabs() > 3.0 + 0.5 * rate.fabs().max(v_rep.fabs()) + vslack;
            }
            self.eval(Reason::VerticalRateImplausible, bad, now);
        }
        if let (Some(t0), Some(t1)) = (a.ts, fix.ts) {
            let dts = wrap_hour(t1 as f64 - t0 as f64);
            if dts == 0.0 {
                // Frozen while the aircraft moves or several fixes went by.
                self.eval(Reason::TimestampFrozen, d > 5.0 || k >= 3, now);
            } else if unix_ms.is_none() {
                self.eval(Reason::LocationClockDrift, (dts - dt).fabs() > 5.0, now);
            }
        }
    }

    fn check_identity(&mut self, cfg: &TrustConfig, now: u64) {
        let mut cdc = false;
        let mut jj = false;
        let mut serial_bad = false;
        let mut has_basic = false;
        let mut serial_text: Option<[u8; 20]> = None;
        for b in self.data.basic_id.iter().flatten() {
            if b.id_type == IdType::None {
                continue;
            }
            has_basic = true;
            let id = b.uas_id_str().unwrap_or("");
            if id.starts_with("Spoofed_Serial_") {
                cdc = true;
            }
            if b.id_type == IdType::SerialNumber {
                serial_bad |= SerialNumber::parse(id).is_none();
                serial_text = Some(b.uas_id);
            }
        }
        let self_id = self
            .data
            .self_id
            .as_ref()
            .and_then(|s| s.description_str())
            .unwrap_or("");
        if self_id == "Spoofing test" {
            cdc = true;
        }
        let operator = self
            .data
            .operator_id
            .as_ref()
            .and_then(|o| o.operator_id_str())
            .unwrap_or("");
        if let Some(b) = self.beacon {
            let ssid = b.ssid();
            // cyber-defence-campus: SSID "RID-" + serial, capability 0 (neither ESS nor IBSS).
            if let Some(serial) = serial_text {
                let n = serial.iter().position(|&c| c == 0).unwrap_or(20);
                if ssid.len() == 4 + n && ssid.starts_with(b"RID-") && ssid[4..] == serial[..n] {
                    cdc = true;
                }
            }
            if b.capability == 0 && self.system_ts_zero {
                cdc = true;
            }
            // jjshoots: SSID is the random 16 character operator ID; beacon
            // interval field 10 TU with Self ID "Recreational".
            if !operator.is_empty() && is_alnum16(operator) && ssid == operator.as_bytes() {
                jj = true;
            }
            if b.interval_tu == 10 && self_id == "Recreational" {
                jj = true;
            }
        }
        if !cfg.fingerprints {
            cdc = false;
            jj = false;
        }
        if cdc {
            self.spoofer = Some(Spoofer::DroneRemoteIdSpoofer);
            self.hit(Reason::KnownSpoofer, now);
        } else if jj {
            self.spoofer = Some(Spoofer::RemoteIdSpoofer);
            self.hit(Reason::KnownSpoofer, now);
        }
        if serial_bad {
            self.hit(Reason::SerialFormat, now);
        }
        if !has_basic
            && self.locations >= 5
            && self
                .first_ms
                .is_some_and(|f| now.saturating_sub(f) >= 15_000)
        {
            self.hit(Reason::NoBasicId, now);
        }
    }

    /// The completed authentication message waiting for verification, if
    /// any (taking it clears it).
    pub fn take_pending_auth(&mut self) -> Option<AssembledAuth> {
        self.pending.take()
    }

    /// Records the outcome of verifying a message from
    /// [`TrustState::take_pending_auth`].
    #[cfg(feature = "verify")]
    pub fn record_auth(
        &mut self,
        msg: &AssembledAuth,
        result: crate::auth::AuthResult,
        now_ms: u64,
    ) {
        use crate::auth::{AuthKind, AuthResult};
        match result {
            AuthResult::NotHandled | AuthResult::Unsupported => self.auth.unsupported += 1,
            AuthResult::Unverifiable => self.auth.unverifiable += 1,
            AuthResult::Valid {
                kind,
                signer,
                trusted,
                content_validated,
                fresh,
            } => {
                // A DRIP signature only speaks for this aircraft when its
                // signer is a DET the aircraft itself broadcasts in a Basic
                // ID. Otherwise anyone could relay a nearby DRIP aircraft's
                // signed messages under their own identity.
                if kind != AuthKind::Link
                    && kind != AuthKind::Other
                    && !self.dets().any(|d| d == signer)
                {
                    self.auth.unverifiable += 1;
                    return;
                }
                self.auth.valid += 1;
                if fresh == Some(false) {
                    self.hit(Reason::AuthExpired, now_ms);
                    return;
                }
                // A Link proves the key, not this aircraft's live data.
                if kind != AuthKind::Link && content_validated {
                    self.auth.any_verified = true;
                    self.auth.verified_ms = Some(now_ms);
                    self.auth.det = Some(signer);
                    let clocked = fresh == Some(true);
                    if clocked {
                        self.auth.verified_clocked_ms = Some(now_ms);
                    }
                    if trusted {
                        self.auth.any_trusted = true;
                        self.auth.trusted_ms = Some(now_ms);
                        if clocked {
                            self.auth.trusted_clocked_ms = Some(now_ms);
                        }
                    }
                }
            }
            AuthResult::Invalid(_) => {
                // Pages gathered across seconds over Bluetooth 4 and rebuilt
                // by FEC may mix messages; only count clean failures.
                if msg.from_pack || msg.recovered_page.is_none() {
                    self.auth.invalid += 1;
                    self.hit(Reason::AuthFailed, now_ms);
                }
            }
        }
    }

    /// Verifies the pending authentication message, if any, with `scheme`
    /// and `keys`, and records the result.
    #[cfg(feature = "verify")]
    pub fn verify_pending(
        &mut self,
        cfg: &TrustConfig,
        scheme: &mut dyn crate::auth::AuthScheme,
        keys: &mut dyn crate::auth::KeyStore,
        now_ms: u64,
        unix_ms: Option<u64>,
    ) -> Option<crate::auth::AuthResult> {
        let msg = self.pending.take()?;
        let mut dets = [Det::default(); 2];
        let mut nd = 0;
        for d in self.dets() {
            if nd < 2 {
                dets[nd] = d;
                nd += 1;
            }
        }
        let ctx = crate::auth::AuthContext {
            uas_dets: &dets[..nd],
            recent_messages: &self.recent[..self.nrecent.min(RECENT)],
            recent_hashes: &self.hashes[..self.nhash.min(HASHES)],
            pack_messages: if msg.from_pack {
                &self.pack_msgs[..self.npack]
            } else {
                &[]
            },
            now_unix: unix_ms.map(|u| u / 1000),
            skew_s: cfg.auth_skew_s,
        };
        let result = scheme.verify(&msg, &ctx, keys);
        self.record_auth(&msg, result, now_ms);
        Some(result)
    }

    /// The DET that signed this aircraft's latest verified DRIP message.
    /// It is always one of the DETs the aircraft broadcasts, so when the
    /// aircraft also broadcasts an unsigned serial number, this is the
    /// identity the signatures vouch for.
    pub fn authenticated_det(&self) -> Option<Det> {
        if matches!(self.auth_state(), AuthState::Verified | AuthState::Trusted) {
            self.auth.det
        } else {
            None
        }
    }

    /// The DRIP authentication state.
    pub fn auth_state(&self) -> AuthState {
        let a = &self.auth;
        if a.invalid > 0 {
            if a.any_trusted {
                AuthState::Conflicting
            } else if a.any_verified {
                AuthState::Questionable
            } else {
                AuthState::Unverified
            }
        } else if a.any_trusted {
            AuthState::Trusted
        } else if a.any_verified {
            AuthState::Verified
        } else if a.unverifiable > 0 || a.valid > 0 || (a.complete > 0 && a.unsupported == 0) {
            AuthState::Unverifiable
        } else if a.unsupported > 0 {
            AuthState::Unsupported
        } else if a.pages > 0 {
            AuthState::Partial
        } else {
            AuthState::None
        }
    }

    /// The current assessment at receiver time `now_ms`.
    pub fn assessment(&self, cfg: &TrustConfig, now_ms: u64) -> Assessment {
        let mut reasons = ReasonSet::default();
        for &r in Reason::ALL {
            if self.active(r, cfg, now_ms) {
                reasons.insert(r);
            }
        }
        let strong = reasons.count(Severity::Strong);
        let moderate = reasons.count(Severity::Moderate);
        let weak = reasons.count(Severity::Weak);
        let auth = self.auth_state();
        let fresh =
            |t: Option<u64>| t.is_some_and(|t| now_ms.saturating_sub(t) <= cfg.auth_fresh_ms);
        let (trusted_ms, verified_ms) = if cfg.auth_requires_clock {
            (self.auth.trusted_clocked_ms, self.auth.verified_clocked_ms)
        } else {
            (self.auth.trusted_ms, self.auth.verified_ms)
        };
        let authenticated = match auth {
            AuthState::Trusted => {
                fresh(trusted_ms) || (cfg.accept_self_certified && fresh(verified_ms))
            }
            AuthState::Verified => cfg.accept_self_certified && fresh(verified_ms),
            _ => false,
        };
        let mut score: f32 =
            0.5 - 0.4 * strong as f32 - 0.15 * moderate as f32 - 0.05 * weak as f32;
        if authenticated {
            score += 0.5;
        } else if matches!(auth, AuthState::Verified | AuthState::Trusted) {
            score += 0.2;
        }
        let moderate_spoofed = cfg
            .moderate_spoofed
            .is_some_and(|n| n > 0 && moderate >= n as usize);
        let verdict = if strong > 0 || moderate_spoofed {
            Verdict::Spoofed
        } else if moderate > 0 || weak >= 2 {
            Verdict::Suspicious
        } else if authenticated {
            Verdict::Authenticated
        } else {
            Verdict::Plausible
        };
        Assessment {
            verdict,
            score: score.clamp(0.0, 1.0),
            reasons,
            spoofer: if reasons.contains(Reason::KnownSpoofer) {
                self.spoofer
            } else {
                None
            },
            auth,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BasicId, Location, MessagePackBuilder, UaType};

    fn loc(lat: f64, lon: f64, speed: f32, dir: f32, ts: f32) -> [u8; 25] {
        Message::Location(Location {
            latitude: lat,
            longitude: lon,
            speed_horizontal: Some(speed),
            direction: Some(dir),
            altitude_geo: Some(100.0),
            timestamp: Some(ts),
            horizontal_accuracy: crate::HorizontalAccuracy(10),
            ..Location::default()
        })
        .encode()
        .unwrap()
    }

    #[test]
    fn steady_flight_is_plausible() {
        let cfg = TrustConfig::default();
        let mut st = TrustState::new();
        let id = Message::BasicId(
            BasicId::new(
                IdType::SerialNumber,
                UaType::HelicopterOrMultirotor,
                "1596F35074529ABCDEFG",
            )
            .unwrap(),
        )
        .encode()
        .unwrap();
        // 10 m/s due north, one fix per second.
        let mut a = Assessment::default();
        for i in 0..30u64 {
            let lat = 47.0 + (10.0 * i as f64) / 111_195.0;
            let mut b = MessagePackBuilder::new();
            b.push_raw(&id).unwrap();
            b.push_raw(&loc(lat, 8.0, 10.0, 0.0, 600.0 + i as f32))
                .unwrap();
            let obs = Observation::new(
                Transport::Bluetooth5,
                Some(i as u8),
                b.as_bytes(),
                1_000 * i,
            );
            a = st.observe(&cfg, &obs);
        }
        assert_eq!(a.verdict, Verdict::Plausible, "{:?}", a.reasons);
        assert!(a.reasons.is_empty(), "{:?}", a.reasons);
    }

    #[test]
    fn teleport_and_lies_are_caught() {
        let cfg = TrustConfig::default();
        let mut st = TrustState::new();
        let mut a = Assessment::default();
        for i in 0..20u64 {
            // Jumps 2 km east every second while claiming 5 m/s north.
            let lon = 8.0 + (2_000.0 * i as f64) / 75_800.0;
            let raw = loc(47.0, lon, 5.0, 0.0, 600.0 + i as f32);
            let obs = Observation::new(Transport::Bluetooth4, Some(i as u8), &raw, 1_000 * i);
            a = st.observe(&cfg, &obs);
        }
        assert_eq!(a.verdict, Verdict::Spoofed);
        assert!(a.reasons.contains(Reason::Teleport));
        assert!(a.reasons.contains(Reason::ReportedSpeedMismatch));
        assert!(a.reasons.contains(Reason::ReportedCourseMismatch));
    }

    #[test]
    fn counter_reuse_with_new_content_is_a_conflict() {
        let cfg = TrustConfig::default();
        let mut st = TrustState::new();
        let mut a = Assessment::default();
        for i in 0..10u64 {
            for (k, lon) in [(0u8, 8.0), (1, 8.001)] {
                let raw = loc(47.0, lon + i as f64 * 1e-5, 1.0, 90.0, 600.0 + i as f32);
                let obs = Observation::new(
                    Transport::Bluetooth4,
                    Some(i as u8),
                    &raw,
                    1_000 * i + k as u64,
                );
                a = st.observe(&cfg, &obs);
            }
        }
        assert!(
            a.reasons.contains(Reason::CounterConflict),
            "{:?}",
            a.reasons
        );
        assert_eq!(a.verdict, Verdict::Spoofed);
    }

    #[test]
    fn reasons_have_unique_names_and_codes() {
        for (i, r) in Reason::ALL.iter().enumerate() {
            assert_eq!(*r as usize, i);
            assert_eq!(
                Reason::ALL.iter().filter(|o| o.name() == r.name()).count(),
                1
            );
        }
    }
}