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
//! Federated Governance Model
//!
//! All structural changes to the federation (adding/removing members, rotating
//! policy authority, updating quorum policy) are represented as signed,
//! append-only [`GovernanceRecord`]s in a [`GovernanceLog`].
//!
//! # Security Properties
//!
//! - **Replay protection**: Each record carries a unique 32-byte `nonce`. The
//! log rejects any record whose nonce was already seen.
//! - **Chain integrity**: Each record may reference the hash of the preceding
//! record via `previous_action_hash`. A broken chain is rejected.
//! - **Signature requirement**: Records with an empty `signature` are rejected
//! at validation time (structural check; cryptographic verification is the
//! PKI layer's responsibility).
//! - **Append-only**: Records may not be removed or mutated after appending.
//! - **Bitcoin anchoring**: Governance records produce hashes that can be
//! included in a [`pqrascv_bitcoin_anchor::federation::FederationBatchAggregator`]
//! for audit finality. Bitcoin is not used for any decision-making.
use alloc::string::String;
use alloc::vec::Vec;
use crate::verifier_federation::QuorumPolicy;
use crate::verifier_identity::VerifierIdentity;
// ── GovernanceAction ──────────────────────────────────────────────────────
/// A structural change to the federated verifier network.
///
/// All actions must be authorized by the current policy authority and
/// recorded in the [`GovernanceLog`] before taking effect.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum GovernanceAction {
/// Admit a new verifier to the federation.
AddVerifier { verifier: VerifierIdentity },
/// Remove a verifier from the federation by ID.
RemoveVerifier { verifier_id: String },
/// Replace the policy authority verifier.
RotatePolicyAuthority {
old_authority: String,
new_authority: String,
},
/// Permanently revoke a verifier and record the reason.
RevokeVerifier { verifier_id: String, reason: String },
/// Change the federation's quorum policy.
UpdateQuorumPolicy { new_policy: QuorumPolicy },
}
// ── GovernanceRecord ──────────────────────────────────────────────────────
/// A single, signed, replay-protected governance action.
///
/// Records are append-only. Once accepted by [`GovernanceLog::append`], a
/// record cannot be removed or modified.
///
/// # Nonce
///
/// The `nonce` MUST be unique across all records in the log. A 32-byte
/// nonce provides sufficient collision resistance for normal federation
/// lifetimes. Zero nonces are explicitly rejected as likely-erroneous.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GovernanceRecord {
/// Application-defined unique action identifier (UUID or similar).
pub action_id: String,
/// The governance action being recorded.
pub action: GovernanceAction,
/// Verifier ID of the entity authorizing this action.
pub authorized_by: String,
/// Unix seconds when the action was authorized.
pub timestamp: u64,
/// 32-byte unique nonce for replay protection.
pub nonce: [u8; 32],
/// Opaque signature bytes over the record content (structural check only).
#[serde(with = "serde_bytes")]
pub signature: Vec<u8>,
/// SHA3-256 hash of the preceding governance record, if any.
///
/// Used to detect chain breaks. `None` is valid only for the first record.
pub previous_action_hash: Option<[u8; 32]>,
}
// ── GovernanceLog ─────────────────────────────────────────────────────────
/// An append-only, replay-protected log of governance records.
#[derive(Debug, Default)]
pub struct GovernanceLog {
records: Vec<GovernanceRecord>,
seen_nonces: Vec<[u8; 32]>,
}
impl GovernanceLog {
/// Creates an empty governance log.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Validates a record's structural integrity.
///
/// Does NOT perform cryptographic signature verification.
pub fn validate_structure(record: &GovernanceRecord) -> Result<(), GovernanceError> {
if record.signature.is_empty() {
return Err(GovernanceError::EmptySignature);
}
if record.nonce == [0u8; 32] {
return Err(GovernanceError::EmptyNonce);
}
if record.action_id.is_empty() {
return Err(GovernanceError::EmptyActionId);
}
if record.authorized_by.is_empty() {
return Err(GovernanceError::EmptyAuthorizedBy);
}
Ok(())
}
/// Appends a validated governance record to the log.
///
/// # Checks
///
/// 1. Structural validation (non-empty signature, non-zero nonce).
/// 2. Nonce uniqueness (replay protection).
/// 3. Chain integrity (`previous_action_hash` must match the last record's
/// `action_id` hash, if both are present).
pub fn append(&mut self, record: GovernanceRecord) -> Result<(), GovernanceError> {
Self::validate_structure(&record)?;
// Replay protection: reject duplicate nonces
if self.seen_nonces.contains(&record.nonce) {
return Err(GovernanceError::ReplayDetected {
nonce: record.nonce,
});
}
// Chain integrity: if the log is non-empty and the record declares a
// previous hash, it must match our expectation.
if let Some(last) = self.records.last() {
if let Some(prev_hash) = record.previous_action_hash {
// We use the action_id bytes as a stand-in for a full hash in
// this structural model (PKI layer provides full hash chaining).
let last_id_bytes = last.action_id.as_bytes();
let mut expected = [0u8; 32];
let copy_len = last_id_bytes.len().min(32);
expected[..copy_len].copy_from_slice(&last_id_bytes[..copy_len]);
if prev_hash != expected {
return Err(GovernanceError::ChainBroken {
expected,
got: prev_hash,
});
}
}
} else if record.previous_action_hash.is_some() {
// First record must not claim a predecessor
return Err(GovernanceError::ChainBroken {
expected: [0u8; 32],
got: record.previous_action_hash.unwrap_or([0u8; 32]),
});
}
self.seen_nonces.push(record.nonce);
self.records.push(record);
Ok(())
}
/// Returns all records in the log (read-only).
#[must_use]
pub fn records(&self) -> &[GovernanceRecord] {
&self.records
}
/// Returns the number of records in the log.
#[must_use]
pub fn record_count(&self) -> usize {
self.records.len()
}
/// Returns the most recent record, if any.
#[must_use]
pub fn latest(&self) -> Option<&GovernanceRecord> {
self.records.last()
}
}
// ── GovernanceError ───────────────────────────────────────────────────────
/// Errors from governance record validation or append operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GovernanceError {
/// The record's signature field is empty.
EmptySignature,
/// The record's nonce is all-zero (likely uninitialized).
EmptyNonce,
/// The record's `action_id` is empty.
EmptyActionId,
/// The record's `authorized_by` is empty.
EmptyAuthorizedBy,
/// A record with this nonce was already appended (replay attack).
ReplayDetected { nonce: [u8; 32] },
/// The `previous_action_hash` does not match the expected chain link.
ChainBroken { expected: [u8; 32], got: [u8; 32] },
}
impl core::fmt::Display for GovernanceError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::EmptySignature => f.write_str("governance record has empty signature"),
Self::EmptyNonce => f.write_str("governance record has zero nonce"),
Self::EmptyActionId => f.write_str("governance record has empty action_id"),
Self::EmptyAuthorizedBy => f.write_str("governance record has empty authorized_by"),
Self::ReplayDetected { nonce } => {
write!(f, "governance replay detected: nonce {nonce:x?}")
}
Self::ChainBroken { expected, got } => write!(
f,
"governance chain broken: expected {expected:x?}, got {got:x?}"
),
}
}
}
// ── Tests ─────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
fn make_record(action_id: &str, nonce: [u8; 32]) -> GovernanceRecord {
GovernanceRecord {
action_id: action_id.into(),
action: GovernanceAction::RemoveVerifier {
verifier_id: "old-v".into(),
},
authorized_by: "authority-v".into(),
timestamp: 1000,
nonce,
signature: vec![0xde, 0xad, 0xbe, 0xef],
previous_action_hash: None,
}
}
fn nonce(n: u8) -> [u8; 32] {
let mut arr = [0u8; 32];
arr[0] = n;
arr
}
#[test]
fn append_single_record() {
let mut log = GovernanceLog::new();
let r = make_record("action-1", nonce(1));
log.append(r).unwrap();
assert_eq!(log.record_count(), 1);
}
#[test]
fn replay_rejected() {
let mut log = GovernanceLog::new();
log.append(make_record("a1", nonce(1))).unwrap();
let r2 = make_record("a2", nonce(1)); // same nonce
let err = log.append(r2).unwrap_err();
assert!(matches!(err, GovernanceError::ReplayDetected { .. }));
}
#[test]
fn empty_signature_rejected() {
let mut record = make_record("a1", nonce(1));
record.signature = vec![];
assert!(matches!(
GovernanceLog::validate_structure(&record).unwrap_err(),
GovernanceError::EmptySignature
));
}
#[test]
fn zero_nonce_rejected() {
let record = make_record("a1", [0u8; 32]);
assert!(matches!(
GovernanceLog::validate_structure(&record).unwrap_err(),
GovernanceError::EmptyNonce
));
}
#[test]
fn two_unique_nonces_accepted() {
let mut log = GovernanceLog::new();
log.append(make_record("a1", nonce(1))).unwrap();
log.append(make_record("a2", nonce(2))).unwrap();
assert_eq!(log.record_count(), 2);
}
#[test]
fn first_record_with_previous_hash_rejected() {
let mut log = GovernanceLog::new();
let mut r = make_record("a1", nonce(1));
r.previous_action_hash = Some([0xABu8; 32]);
let err = log.append(r).unwrap_err();
assert!(matches!(err, GovernanceError::ChainBroken { .. }));
}
#[test]
fn add_verifier_action_roundtrip() {
let action = GovernanceAction::AddVerifier {
verifier: VerifierIdentity {
verifier_id: "new-v".into(),
organization: "NewOrg".into(),
public_key: vec![0xab],
ml_kem_public_key: None,
capabilities: vec![
crate::verifier_identity::VerifierCapability::HardwareVerification,
],
},
};
let record = GovernanceRecord {
action_id: "add-new-v".into(),
action,
authorized_by: "auth".into(),
timestamp: 2000,
nonce: nonce(42),
signature: vec![1, 2, 3, 4],
previous_action_hash: None,
};
let mut log = GovernanceLog::new();
log.append(record).unwrap();
assert!(matches!(
log.latest().unwrap().action,
GovernanceAction::AddVerifier { .. }
));
}
}