-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmulti_federation.py
More file actions
1381 lines (1175 loc) · 52 KB
/
multi_federation.py
File metadata and controls
1381 lines (1175 loc) · 52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
"""
Multi-Federation Witness Requirements
Extends the federation registry to support cross-federation governance:
1. Federation Identity: Each federation has its own unique ID and profile
2. Inter-Federation Trust: Federations can establish trust relationships
3. Cross-Federation Witnessing: Proposals affecting multiple federations
require witnesses from each affected federation
Use cases:
- Global proposals that span organizations
- Inter-company collaborations with shared governance
- Decentralized autonomous organizations (DAOs) with sub-DAOs
Track BF: Multi-federation witness requirements
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from typing import Dict, List, Optional, Set, Tuple
from pathlib import Path
from enum import Enum
class FederationRelationship(Enum):
"""Type of relationship between two federations."""
NONE = "none" # No established relationship
PEER = "peer" # Equal status, mutual recognition
PARENT = "parent" # This federation is parent of the other
CHILD = "child" # This federation is child of the other
TRUSTED = "trusted" # Unilateral trust (we trust them)
ALLIED = "allied" # Mutual alliance (we trust each other)
@dataclass
class FederationProfile:
"""Profile of a federation in the multi-federation registry."""
federation_id: str
name: str
created_at: str
status: str = "active" # active, suspended, dissolved
# Governance parameters
min_team_count: int = 3 # Minimum teams to be considered operational
requires_external_witness: bool = True # Require witness from outside federation
# Trust metrics
reputation_score: float = 0.5 # Overall federation reputation
active_team_count: int = 0
proposal_count: int = 0
success_rate: float = 0.5
@dataclass
class InterFederationTrust:
"""Trust relationship between two federations."""
source_federation_id: str
target_federation_id: str
relationship: FederationRelationship
established_at: str
trust_score: float = 0.5 # How much source trusts target (0-1)
witness_allowed: bool = True # Can target witness for source's proposals
last_interaction: str = ""
successful_interactions: int = 0 # Track BI: Count of successful interactions
failed_interactions: int = 0 # Track BI: Count of failed interactions
@dataclass
class CrossFederationProposal:
"""A proposal that spans multiple federations."""
proposal_id: str
proposing_federation_id: str
proposing_team_id: str
affected_federation_ids: List[str]
action_type: str
description: str
created_at: str
status: str = "pending" # pending, approved, rejected
# Approval tracking per federation
federation_approvals: Dict[str, Dict] = field(default_factory=dict)
# {federation_id: {"approved": bool, "timestamp": str, "approving_teams": [...]}}
# Witness requirements
requires_external_federation_witness: bool = True
external_witnesses: List[str] = field(default_factory=list)
class MultiFederationRegistry:
"""
Registry for managing multiple federations and their relationships.
This sits above individual FederationRegistry instances to coordinate
cross-federation governance.
"""
# Minimum trust score for cross-federation witnessing
MIN_CROSS_FED_TRUST = 0.4
# Trust Bootstrap Limits (Track BI)
# Maximum trust that can be claimed for a new relationship
MAX_INITIAL_TRUST = 0.5
# Maximum trust boost per successful interaction
TRUST_INCREMENT_PER_SUCCESS = 0.05
# Federation age requirements (days) for trust levels
TRUST_AGE_REQUIREMENTS = {
0.5: 0, # Immediate - up to 0.5
0.6: 7, # 1 week - up to 0.6
0.7: 30, # 1 month - up to 0.7
0.8: 90, # 3 months - up to 0.8
0.9: 180, # 6 months - up to 0.9
1.0: 365, # 1 year - up to 1.0
}
# Minimum successful interactions for trust levels
TRUST_INTERACTION_REQUIREMENTS = {
0.5: 0, # No interactions needed for baseline
0.6: 3, # 3 successful interactions
0.7: 10, # 10 successful interactions
0.8: 25, # 25 successful interactions
0.9: 50, # 50 successful interactions
1.0: 100, # 100 successful interactions
}
def __init__(self, db_path: Optional[str] = None):
"""
Initialize the multi-federation registry.
Args:
db_path: Path to SQLite database (default: in-memory)
"""
if db_path:
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
else:
self.db_path = ":memory:"
self._ensure_tables()
def _ensure_tables(self):
"""Create database tables if they don't exist."""
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS federations (
federation_id TEXT PRIMARY KEY,
name TEXT NOT NULL,
created_at TEXT NOT NULL,
status TEXT DEFAULT 'active',
min_team_count INTEGER DEFAULT 3,
requires_external_witness INTEGER DEFAULT 1,
reputation_score REAL DEFAULT 0.5,
active_team_count INTEGER DEFAULT 0,
proposal_count INTEGER DEFAULT 0,
success_rate REAL DEFAULT 0.5
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS inter_federation_trust (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_federation_id TEXT NOT NULL,
target_federation_id TEXT NOT NULL,
relationship TEXT NOT NULL,
established_at TEXT NOT NULL,
trust_score REAL DEFAULT 0.5,
witness_allowed INTEGER DEFAULT 1,
last_interaction TEXT DEFAULT '',
successful_interactions INTEGER DEFAULT 0,
failed_interactions INTEGER DEFAULT 0,
UNIQUE(source_federation_id, target_federation_id)
)
""")
# Migration: add columns if they don't exist
try:
conn.execute("ALTER TABLE inter_federation_trust ADD COLUMN successful_interactions INTEGER DEFAULT 0")
except sqlite3.OperationalError:
pass
try:
conn.execute("ALTER TABLE inter_federation_trust ADD COLUMN failed_interactions INTEGER DEFAULT 0")
except sqlite3.OperationalError:
pass
conn.execute("""
CREATE TABLE IF NOT EXISTS cross_federation_proposals (
proposal_id TEXT PRIMARY KEY,
proposing_federation_id TEXT NOT NULL,
proposing_team_id TEXT NOT NULL,
affected_federation_ids TEXT NOT NULL,
action_type TEXT NOT NULL,
description TEXT NOT NULL,
created_at TEXT NOT NULL,
status TEXT DEFAULT 'pending',
federation_approvals TEXT DEFAULT '{}',
requires_external_federation_witness INTEGER DEFAULT 1,
external_witnesses TEXT DEFAULT '[]'
)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_trust_source
ON inter_federation_trust(source_federation_id)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_proposals_status
ON cross_federation_proposals(status)
""")
def register_federation(
self,
federation_id: str,
name: str,
min_team_count: int = 3,
requires_external_witness: bool = True,
) -> FederationProfile:
"""
Register a new federation in the multi-federation registry.
Args:
federation_id: Unique identifier for the federation
name: Human-readable name
min_team_count: Minimum teams required
requires_external_witness: Whether external witnesses are required
Returns:
FederationProfile for the registered federation
"""
now = datetime.now(timezone.utc).isoformat()
profile = FederationProfile(
federation_id=federation_id,
name=name,
created_at=now,
min_team_count=min_team_count,
requires_external_witness=requires_external_witness,
)
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
INSERT INTO federations
(federation_id, name, created_at, min_team_count, requires_external_witness)
VALUES (?, ?, ?, ?, ?)
""", (
profile.federation_id,
profile.name,
profile.created_at,
profile.min_team_count,
1 if profile.requires_external_witness else 0,
))
return profile
def get_federation(self, federation_id: str) -> Optional[FederationProfile]:
"""Get a federation's profile."""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
row = conn.execute(
"SELECT * FROM federations WHERE federation_id = ?",
(federation_id,)
).fetchone()
if not row:
return None
return FederationProfile(
federation_id=row["federation_id"],
name=row["name"],
created_at=row["created_at"],
status=row["status"],
min_team_count=row["min_team_count"],
requires_external_witness=bool(row["requires_external_witness"]),
reputation_score=row["reputation_score"],
active_team_count=row["active_team_count"],
proposal_count=row["proposal_count"],
success_rate=row["success_rate"],
)
def establish_trust(
self,
source_federation_id: str,
target_federation_id: str,
relationship: FederationRelationship = FederationRelationship.PEER,
initial_trust: float = 0.5,
witness_allowed: bool = True,
) -> InterFederationTrust:
"""
Establish a trust relationship between two federations.
Track BI: Applies trust bootstrap limits to prevent gaming.
Args:
source_federation_id: Federation establishing the trust
target_federation_id: Federation being trusted
relationship: Type of relationship
initial_trust: Requested initial trust score (0-1), will be capped
witness_allowed: Whether target can witness for source
Returns:
InterFederationTrust record with capped trust score
"""
now = datetime.now(timezone.utc).isoformat()
# Track BI: Apply bootstrap limits
# 1. Cap initial trust at MAX_INITIAL_TRUST
effective_trust = min(initial_trust, self.MAX_INITIAL_TRUST)
# 2. Further cap based on target federation age
target_fed = self.get_federation(target_federation_id)
if target_fed:
max_by_age = self._get_max_trust_by_age(target_fed.created_at)
effective_trust = min(effective_trust, max_by_age)
trust = InterFederationTrust(
source_federation_id=source_federation_id,
target_federation_id=target_federation_id,
relationship=relationship,
established_at=now,
trust_score=effective_trust,
witness_allowed=witness_allowed,
)
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
INSERT OR REPLACE INTO inter_federation_trust
(source_federation_id, target_federation_id, relationship,
established_at, trust_score, witness_allowed,
successful_interactions, failed_interactions)
VALUES (?, ?, ?, ?, ?, ?, 0, 0)
""", (
trust.source_federation_id,
trust.target_federation_id,
trust.relationship.value,
trust.established_at,
trust.trust_score,
1 if trust.witness_allowed else 0,
))
return trust
def _get_max_trust_by_age(self, created_at: str) -> float:
"""
Calculate maximum trust allowed based on federation age.
Track BI: Newer federations have lower trust ceilings.
"""
try:
created = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
age_days = (datetime.now(timezone.utc) - created).days
max_trust = 0.5 # Default
for trust_level, required_days in sorted(self.TRUST_AGE_REQUIREMENTS.items()):
if age_days >= required_days:
max_trust = trust_level
return max_trust
except (ValueError, TypeError):
return 0.5 # Default if parsing fails
def _get_max_trust_by_interactions(
self,
source_federation_id: str,
target_federation_id: str,
) -> float:
"""
Calculate maximum trust allowed based on successful interactions.
Track BI: Trust must be earned through successful collaborations.
"""
with sqlite3.connect(self.db_path) as conn:
row = conn.execute("""
SELECT successful_interactions
FROM inter_federation_trust
WHERE source_federation_id = ? AND target_federation_id = ?
""", (source_federation_id, target_federation_id)).fetchone()
if not row:
return 0.5
interactions = row[0] or 0
max_trust = 0.5
for trust_level, required_interactions in sorted(self.TRUST_INTERACTION_REQUIREMENTS.items()):
if interactions >= required_interactions:
max_trust = trust_level
return max_trust
def record_interaction(
self,
source_federation_id: str,
target_federation_id: str,
success: bool,
auto_adjust_trust: bool = True,
) -> Dict:
"""
Record an interaction between federations and optionally adjust trust.
Track BI: Trust is earned through successful interactions.
Args:
source_federation_id: Federation that initiated
target_federation_id: Federation that participated
success: Whether the interaction was successful
auto_adjust_trust: Whether to automatically adjust trust scores
Returns:
Updated trust status
"""
now = datetime.now(timezone.utc).isoformat()
with sqlite3.connect(self.db_path) as conn:
# Update interaction counts
if success:
conn.execute("""
UPDATE inter_federation_trust
SET successful_interactions = successful_interactions + 1,
last_interaction = ?
WHERE source_federation_id = ? AND target_federation_id = ?
""", (now, source_federation_id, target_federation_id))
else:
conn.execute("""
UPDATE inter_federation_trust
SET failed_interactions = failed_interactions + 1,
last_interaction = ?
WHERE source_federation_id = ? AND target_federation_id = ?
""", (now, source_federation_id, target_federation_id))
# Get current trust data
conn.row_factory = sqlite3.Row
row = conn.execute("""
SELECT trust_score, successful_interactions, failed_interactions
FROM inter_federation_trust
WHERE source_federation_id = ? AND target_federation_id = ?
""", (source_federation_id, target_federation_id)).fetchone()
if not row:
return {"error": "No trust relationship found"}
current_trust = row["trust_score"]
successful = row["successful_interactions"]
failed = row["failed_interactions"]
# Calculate new trust if auto-adjusting
new_trust = current_trust
if auto_adjust_trust:
# Get caps
max_by_age = self._get_max_trust_by_age(
self.get_federation(target_federation_id).created_at
if self.get_federation(target_federation_id) else now
)
max_by_interactions = self._get_max_trust_by_interactions(
source_federation_id, target_federation_id
)
max_trust = min(max_by_age, max_by_interactions)
if success:
# Increase trust up to cap
new_trust = min(
current_trust + self.TRUST_INCREMENT_PER_SUCCESS,
max_trust
)
else:
# Decrease trust on failure
new_trust = max(0.1, current_trust - 0.1)
conn.execute("""
UPDATE inter_federation_trust
SET trust_score = ?
WHERE source_federation_id = ? AND target_federation_id = ?
""", (new_trust, source_federation_id, target_federation_id))
return {
"source_federation": source_federation_id,
"target_federation": target_federation_id,
"success": success,
"previous_trust": current_trust,
"new_trust": new_trust,
"successful_interactions": successful,
"failed_interactions": failed,
"trust_adjusted": auto_adjust_trust,
}
def get_trust_bootstrap_status(
self,
source_federation_id: str,
target_federation_id: str,
) -> Dict:
"""
Get detailed trust bootstrap status between two federations.
Track BI: Transparency into trust constraints.
Returns:
Dict with current trust, caps, and requirements for increase
"""
trust = self.get_trust_relationship(source_federation_id, target_federation_id)
target_fed = self.get_federation(target_federation_id)
if not trust:
return {"error": "No trust relationship exists"}
# Get interaction counts
with sqlite3.connect(self.db_path) as conn:
row = conn.execute("""
SELECT successful_interactions, failed_interactions
FROM inter_federation_trust
WHERE source_federation_id = ? AND target_federation_id = ?
""", (source_federation_id, target_federation_id)).fetchone()
successful = row[0] if row else 0
failed = row[1] if row else 0
# Calculate caps
max_by_age = self._get_max_trust_by_age(
target_fed.created_at if target_fed else datetime.now(timezone.utc).isoformat()
)
max_by_interactions = self._get_max_trust_by_interactions(
source_federation_id, target_federation_id
)
effective_cap = min(max_by_age, max_by_interactions)
# Calculate what's needed for next level
next_level = None
interactions_needed = None
days_needed = None
for trust_level in sorted(self.TRUST_AGE_REQUIREMENTS.keys()):
if trust_level > trust.trust_score:
next_level = trust_level
interactions_needed = max(
0,
self.TRUST_INTERACTION_REQUIREMENTS.get(trust_level, 0) - successful
)
if target_fed:
created = datetime.fromisoformat(target_fed.created_at.replace('Z', '+00:00'))
current_age = (datetime.now(timezone.utc) - created).days
days_needed = max(
0,
self.TRUST_AGE_REQUIREMENTS.get(trust_level, 0) - current_age
)
break
return {
"source_federation": source_federation_id,
"target_federation": target_federation_id,
"current_trust": trust.trust_score,
"max_initial_trust": self.MAX_INITIAL_TRUST,
"max_trust_by_age": max_by_age,
"max_trust_by_interactions": max_by_interactions,
"effective_trust_cap": effective_cap,
"successful_interactions": successful,
"failed_interactions": failed,
"next_trust_level": next_level,
"interactions_needed_for_next": interactions_needed,
"days_needed_for_next": days_needed,
"can_increase": trust.trust_score < effective_cap,
}
def get_trust_relationship(
self,
source_federation_id: str,
target_federation_id: str,
) -> Optional[InterFederationTrust]:
"""Get the trust relationship from source to target."""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
row = conn.execute("""
SELECT * FROM inter_federation_trust
WHERE source_federation_id = ? AND target_federation_id = ?
""", (source_federation_id, target_federation_id)).fetchone()
if not row:
return None
# Handle columns that may not exist in older schemas
try:
successful = row["successful_interactions"] or 0
except (KeyError, IndexError):
successful = 0
try:
failed = row["failed_interactions"] or 0
except (KeyError, IndexError):
failed = 0
return InterFederationTrust(
source_federation_id=row["source_federation_id"],
target_federation_id=row["target_federation_id"],
relationship=FederationRelationship(row["relationship"]),
established_at=row["established_at"],
trust_score=row["trust_score"],
witness_allowed=bool(row["witness_allowed"]),
last_interaction=row["last_interaction"] or "",
successful_interactions=successful,
failed_interactions=failed,
)
# Alias for economic_federation compatibility
def get_trust(
self,
source_federation_id: str,
target_federation_id: str,
) -> Optional[InterFederationTrust]:
"""Alias for get_trust_relationship."""
return self.get_trust_relationship(source_federation_id, target_federation_id)
def get_all_relationships(self) -> List[InterFederationTrust]:
"""
Get all trust relationships in the registry.
Track BV: Used for reputation aggregation.
Returns:
List of all InterFederationTrust relationships
"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
rows = conn.execute("""
SELECT source_federation_id, target_federation_id, relationship,
established_at, trust_score, witness_allowed,
last_interaction, successful_interactions, failed_interactions
FROM inter_federation_trust
""").fetchall()
relationships = []
for row in rows:
relationships.append(InterFederationTrust(
source_federation_id=row["source_federation_id"],
target_federation_id=row["target_federation_id"],
relationship=FederationRelationship(row["relationship"]),
established_at=row["established_at"],
trust_score=row["trust_score"],
witness_allowed=bool(row["witness_allowed"]),
last_interaction=row["last_interaction"] or "",
successful_interactions=row["successful_interactions"],
failed_interactions=row["failed_interactions"],
))
return relationships
def update_trust(
self,
source_federation_id: str,
target_federation_id: str,
new_trust_score: float,
) -> float:
"""
Update the trust score for an existing relationship.
Track BN: Used by EconomicFederationRegistry for trust increases.
Args:
source_federation_id: Federation updating trust
target_federation_id: Federation being trusted
new_trust_score: New trust score
Returns:
The actual trust score after update (may be capped)
"""
# Apply bootstrap limits
max_by_age = self._get_max_trust_by_age(
self.get_federation(target_federation_id).created_at
)
max_by_interactions = self._get_max_trust_by_interactions(
source_federation_id, target_federation_id
)
effective_trust = min(new_trust_score, max_by_age, max_by_interactions)
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
UPDATE inter_federation_trust
SET trust_score = ?
WHERE source_federation_id = ? AND target_federation_id = ?
""", (effective_trust, source_federation_id, target_federation_id))
return effective_trust
def find_eligible_witness_federations(
self,
requesting_federation_id: str,
exclude_federations: List[str] = None,
min_trust: float = None,
) -> List[Tuple[str, float]]:
"""
Find federations eligible to provide witnesses.
Args:
requesting_federation_id: Federation needing witnesses
exclude_federations: Federations to exclude
min_trust: Minimum trust score (default: MIN_CROSS_FED_TRUST)
Returns:
List of (federation_id, trust_score) tuples, sorted by trust
"""
min_trust = min_trust or self.MIN_CROSS_FED_TRUST
exclude = set(exclude_federations or [])
exclude.add(requesting_federation_id) # Can't witness for self
with sqlite3.connect(self.db_path) as conn:
rows = conn.execute("""
SELECT target_federation_id, trust_score
FROM inter_federation_trust
WHERE source_federation_id = ?
AND witness_allowed = 1
AND trust_score >= ?
ORDER BY trust_score DESC
""", (requesting_federation_id, min_trust)).fetchall()
return [
(row[0], row[1])
for row in rows
if row[0] not in exclude
]
# Track CO: Collusion detection thresholds
COLLUSION_RECIPROCITY_WINDOW_DAYS = 30 # Look back period for reciprocity
COLLUSION_PROPOSAL_THRESHOLD = 3 # Max mutual proposals before flagged
COLLUSION_RATIO_THRESHOLD = 0.7 # Max proportion of mutual proposals
def detect_collusion_pattern(
self,
federation_a: str,
federation_b: str,
) -> Tuple[bool, str]:
"""
Track CO: Detect potential collusion between two federations.
Checks for reciprocal proposal patterns that suggest collusion:
- High proportion of proposals only affecting each other
- Lack of external federation involvement
- Rapid mutual approval patterns
Args:
federation_a: First federation to check
federation_b: Second federation to check
Returns:
(is_suspicious, reason) - True if collusion pattern detected
"""
cutoff = (datetime.now(timezone.utc) -
timedelta(days=self.COLLUSION_RECIPROCITY_WINDOW_DAYS)).isoformat()
with sqlite3.connect(self.db_path) as conn:
# Count proposals from A affecting B
a_to_b = conn.execute("""
SELECT COUNT(*) FROM cross_federation_proposals
WHERE proposing_federation_id = ?
AND affected_federation_ids LIKE ?
AND created_at >= ?
""", (federation_a, f'%{federation_b}%', cutoff)).fetchone()[0]
# Count proposals from B affecting A
b_to_a = conn.execute("""
SELECT COUNT(*) FROM cross_federation_proposals
WHERE proposing_federation_id = ?
AND affected_federation_ids LIKE ?
AND created_at >= ?
""", (federation_b, f'%{federation_a}%', cutoff)).fetchone()[0]
# Count all proposals from A
all_from_a = conn.execute("""
SELECT COUNT(*) FROM cross_federation_proposals
WHERE proposing_federation_id = ?
AND created_at >= ?
""", (federation_a, cutoff)).fetchone()[0]
# Count all proposals from B
all_from_b = conn.execute("""
SELECT COUNT(*) FROM cross_federation_proposals
WHERE proposing_federation_id = ?
AND created_at >= ?
""", (federation_b, cutoff)).fetchone()[0]
mutual_count = a_to_b + b_to_a
total_count = max(all_from_a + all_from_b, 1)
# Check 1: Absolute threshold
if mutual_count >= self.COLLUSION_PROPOSAL_THRESHOLD:
return (True, f"Exceeded mutual proposal threshold: {mutual_count} >= {self.COLLUSION_PROPOSAL_THRESHOLD}")
# Check 2: Ratio threshold
if total_count >= 2: # Need minimum data
ratio = mutual_count / total_count
if ratio >= self.COLLUSION_RATIO_THRESHOLD:
return (True, f"High mutual proposal ratio: {ratio:.1%} >= {self.COLLUSION_RATIO_THRESHOLD:.0%}")
return (False, f"No collusion pattern detected (mutual={mutual_count}, total={total_count})")
def create_cross_federation_proposal(
self,
proposing_federation_id: str,
proposing_team_id: str,
affected_federation_ids: List[str],
action_type: str,
description: str,
require_external_witness: bool = True,
) -> CrossFederationProposal:
"""
Create a proposal that spans multiple federations.
Args:
proposing_federation_id: Federation creating the proposal
proposing_team_id: Team within federation creating proposal
affected_federation_ids: All federations affected by this proposal
action_type: Type of action being proposed
description: Human-readable description
require_external_witness: Whether external federation witness needed
Returns:
CrossFederationProposal object
Raises:
ValueError: If collusion pattern detected between affected federations
"""
# Track CO: Check for collusion patterns
for other_fed in affected_federation_ids:
if other_fed != proposing_federation_id:
is_suspicious, reason = self.detect_collusion_pattern(
proposing_federation_id, other_fed
)
if is_suspicious:
raise ValueError(
f"Collusion pattern detected between {proposing_federation_id} "
f"and {other_fed}: {reason}"
)
# Track CP: Check federation status - no proposals involving quarantined/suspended
all_affected = affected_federation_ids + [proposing_federation_id]
with sqlite3.connect(self.db_path) as conn:
for fed_id in set(all_affected):
row = conn.execute(
"SELECT status FROM federations WHERE federation_id = ?",
(fed_id,)
).fetchone()
if row and row[0] != "active":
raise ValueError(
f"Federation {fed_id} is not active (status: {row[0]}). "
f"Cannot create proposals involving quarantined or suspended federations."
)
now = datetime.now(timezone.utc).isoformat()
proposal_id = f"xfed:{hashlib.sha256(f'{proposing_team_id}:{now}'.encode()).hexdigest()[:12]}"
# Ensure proposing federation is in affected list
if proposing_federation_id not in affected_federation_ids:
affected_federation_ids = [proposing_federation_id] + affected_federation_ids
proposal = CrossFederationProposal(
proposal_id=proposal_id,
proposing_federation_id=proposing_federation_id,
proposing_team_id=proposing_team_id,
affected_federation_ids=affected_federation_ids,
action_type=action_type,
description=description,
created_at=now,
requires_external_federation_witness=require_external_witness,
)
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
INSERT INTO cross_federation_proposals
(proposal_id, proposing_federation_id, proposing_team_id,
affected_federation_ids, action_type, description,
created_at, requires_external_federation_witness)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
proposal.proposal_id,
proposal.proposing_federation_id,
proposal.proposing_team_id,
json.dumps(proposal.affected_federation_ids),
proposal.action_type,
proposal.description,
proposal.created_at,
1 if proposal.requires_external_federation_witness else 0,
))
return proposal
def approve_from_federation(
self,
proposal_id: str,
approving_federation_id: str,
approving_teams: List[str],
) -> Dict:
"""
Record approval from a federation for a cross-federation proposal.
Args:
proposal_id: Proposal being approved
approving_federation_id: Federation providing approval
approving_teams: Teams within federation that approved
Returns:
Updated approval status
"""
now = datetime.now(timezone.utc).isoformat()
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
row = conn.execute(
"SELECT * FROM cross_federation_proposals WHERE proposal_id = ?",
(proposal_id,)
).fetchone()
if not row:
raise ValueError(f"Proposal not found: {proposal_id}")
affected = json.loads(row["affected_federation_ids"])
if approving_federation_id not in affected:
raise ValueError(
f"Federation {approving_federation_id} not affected by this proposal"
)
approvals = json.loads(row["federation_approvals"])
approvals[approving_federation_id] = {
"approved": True,
"timestamp": now,
"approving_teams": approving_teams,
}
# Check if all affected federations have approved
all_approved = all(
fed_id in approvals and approvals[fed_id].get("approved")
for fed_id in affected
)
new_status = "approved" if all_approved else "pending"
conn.execute("""
UPDATE cross_federation_proposals
SET federation_approvals = ?, status = ?
WHERE proposal_id = ?
""", (json.dumps(approvals), new_status, proposal_id))
return {
"proposal_id": proposal_id,
"approving_federation": approving_federation_id,
"approving_teams": approving_teams,
"all_approved": all_approved,
"new_status": new_status,
}
def add_external_witness(
self,
proposal_id: str,
witness_federation_id: str,
witness_team_id: str,
) -> Dict:
"""
Add an external federation witness to a proposal.
The witness must be from a federation not affected by the proposal
but trusted by the proposing federation.
Args:
proposal_id: Proposal being witnessed
witness_federation_id: Federation providing witness
witness_team_id: Specific team providing witness
Returns:
Status of witness addition
"""
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
row = conn.execute(
"SELECT * FROM cross_federation_proposals WHERE proposal_id = ?",
(proposal_id,)
).fetchone()
if not row:
raise ValueError(f"Proposal not found: {proposal_id}")
affected = json.loads(row["affected_federation_ids"])
proposing_fed = row["proposing_federation_id"]
# Witness federation must not be affected
if witness_federation_id in affected:
raise ValueError(
f"Witness federation {witness_federation_id} is affected by proposal"
)
# Check trust relationship
trust = self.get_trust_relationship(proposing_fed, witness_federation_id)
if not trust or not trust.witness_allowed:
raise ValueError(
f"No witness trust from {proposing_fed} to {witness_federation_id}"
)
if trust.trust_score < self.MIN_CROSS_FED_TRUST:
raise ValueError(
f"Trust score {trust.trust_score} below minimum {self.MIN_CROSS_FED_TRUST}"
)
witnesses = json.loads(row["external_witnesses"])
witness_entry = f"{witness_federation_id}:{witness_team_id}"
if witness_entry not in witnesses:
witnesses.append(witness_entry)