newton-aggregator 0.4.12

newton prover aggregator utils
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
//! Error type for the state-commit aggregation pipeline.
//!
//! [`StateCommitError`] mirrors the eight `IStateRootCommittable` typed
//! reverts plus the three transport-side failure modes the orchestrator
//! cares about (receipt timeout, on-chain revert, unknown selector). The
//! [`StateCommitError::is_poison`] predicate encodes the rule from
//! `.claude/rules/lessons.md` — *"State-commit registry reverts classify as
//! poison: rebuild against current view, never blind retry"* — so the
//! orchestrator can decide between (a) re-read view + rebuild proposal vs.
//! (b) backoff and retry with the same proposal.
//!
//! The 60s `STATE_COMMIT_RECEIPT_TIMEOUT` in [`newton_prover_chainio`] is
//! deliberately set to half the 120s commit cadence; that means a stuck
//! transaction always releases before the next prepare-tick fires, but only
//! if the orchestrator treats `ReceiptTimeout` as poison rather than retry —
//! otherwise prepare/commit drifts past the registry's view window.

use alloy::{primitives::B256, sol_types::SolError};
use newton_prover_chainio::error::ChainIoError;
use newton_prover_core::state_commit_registry::StateCommitRegistry::{
    CertificateMessageHashMismatch, InvalidNewStateRoot, InvalidPcr0Commitment, InvalidSealedSnapshot, SequenceGap,
    StateRootMismatch, TimestampRegression, UnsupportedStateCommitVersion,
};
use thiserror::Error;

/// Errors surfaced by the state-commit pipeline. Variants split into three
/// groups: misconfiguration ([`RegistryNotConfigured`](Self::RegistryNotConfigured)),
/// the eight typed `IStateRootCommittable` reverts, and the three
/// transport-side failures ([`ReceiptTimeout`](Self::ReceiptTimeout),
/// [`TransactionReverted`](Self::TransactionReverted),
/// [`UnknownRevert`](Self::UnknownRevert)). [`OnchainCallFailed`](Self::OnchainCallFailed)
/// wraps any underlying [`ChainIoError`] that isn't itself a registry revert
/// (RPC transport failure, signer error, config error).
#[derive(Debug, Error)]
pub enum StateCommitError {
    /// The orchestrator was started for a chain whose deployment JSON has no
    /// `stateCommitRegistry` entry. Caller should skip the chain rather than
    /// poison; not retried.
    #[error("StateCommitRegistry address not configured for this chain")]
    RegistryNotConfigured,

    // --- 8 typed `IStateRootCommittable` reverts -------------------------
    /// `0x104d0050` — `commit.sequenceNo != lastCommittedSequenceNo + 1`.
    /// Local view raced against a concurrent commit. Rebuild from current view.
    #[error("registry sequence gap: expected={expected}, got={got}")]
    SequenceGap {
        /// Sequence number the registry expected (`lastCommittedSequenceNo + 1`).
        expected: u64,
        /// Sequence number we submitted.
        got: u64,
    },

    /// `0x37f04d41` — `commit.prevStateRoot != lastCommittedStateRoot`.
    /// Off-chain replica state diverged or the local view is stale.
    #[error("state root mismatch: expected={expected}, got={got}")]
    StateRootMismatch {
        /// `lastCommittedStateRoot` per the registry.
        expected: B256,
        /// `prevStateRoot` we submitted.
        got: B256,
    },

    /// `0x5a612e4c` — `commit.timestamp <= lastCommittedTimestamp`. Defends
    /// against replay / reorg-driven out-of-order commits.
    #[error("timestamp regression: last={last}, got={got}")]
    TimestampRegression {
        /// `lastCommittedTimestamp` per the registry.
        last: u64,
        /// `commit.timestamp` we submitted.
        got: u64,
    },

    /// `0x6dfbfc74` — `pcr0Commitment == bytes32(0)`. The PCR0 source returned
    /// a zero hash; an off-chain bug in [`crate::state_commit::Pcr0Provider`].
    #[error("PCR0 commitment is bytes32(0)")]
    InvalidPcr0Commitment,

    /// `0x5bf0f768` — `newStateRoot == bytes32(0)`. The proposal builder must
    /// catch this off-chain (see [`crate::state_commit::proposal::build_state_commit`]).
    #[error("newStateRoot is bytes32(0)")]
    InvalidNewStateRoot,

    /// `0xb681668e` — `commit.version != STATE_COMMIT_V1`. Version bump
    /// without a coordinated migration; surfaces only on schema drift.
    #[error("unsupported StateCommit version: expected={expected}, got={got}")]
    UnsupportedStateCommitVersion {
        /// Version the registry will accept (`STATE_COMMIT_V1`).
        expected: u8,
        /// Version we submitted.
        got: u8,
    },

    /// `0xdc4e1d57` — sealed-snapshot payload malformed or signature empty.
    /// Surfaces only on the `injectSealedSnapshot` path; included here so the
    /// orchestrator can match a complete selector set.
    #[error("sealed snapshot payload malformed or signature empty")]
    InvalidSealedSnapshot,

    /// `0x822ef683` — `cert.messageHash != keccak256(abi.encode(StateCommit))`.
    /// Cert was signed against a different `StateCommit`; either the BLS
    /// aggregator and the writer disagree on the digest, or a stale cert is
    /// being reused.
    #[error("certificate messageHash mismatch: expected={expected}, actual={actual}")]
    CertificateMessageHashMismatch {
        /// Hash the cert binds to.
        expected: B256,
        /// Hash of the `StateCommit` we submitted.
        actual: B256,
    },

    // --- Transport / mining failures -------------------------------------
    /// `STATE_COMMIT_RECEIPT_TIMEOUT` (60s) elapsed before the receipt was
    /// observed. Treated as poison because a stuck tx may yet land and bind
    /// the registry to our proposal — re-reading the view is the only safe
    /// next step.
    #[error("transaction submission timed out after {timeout_secs}s")]
    ReceiptTimeout {
        /// Timeout duration in seconds.
        timeout_secs: u64,
    },

    /// Receipt observed with `status == false` — transaction mined but
    /// reverted on-chain. Revert data was either empty or unrecognized.
    #[error("transaction {tx_hash} reverted on-chain")]
    TransactionReverted {
        /// On-chain transaction hash.
        tx_hash: B256,
    },

    /// Reverted with revert data we couldn't decode: empty revert, or a
    /// selector outside the eight `IStateRootCommittable` codes. Conservative
    /// poison classification — never blind-retry an unknown failure.
    #[error("unknown revert: 0x{selector_hex}")]
    UnknownRevert {
        /// Hex-encoded 4-byte selector (or full data when shorter than 4 bytes).
        selector_hex: String,
    },

    /// Underlying [`ChainIoError`] that does not represent a typed registry
    /// revert (RPC transport failure, signer error, config error). Treated as
    /// transient — caller-level retry/backoff handles these without rebuilding
    /// the proposal.
    #[error("on-chain call failed: {0}")]
    OnchainCallFailed(#[source] ChainIoError),

    // --- Aggregator-layer failures (not on-chain reverts) -------------------
    /// Signed stake fell below the quorum threshold. Not poison — the tick
    /// failed before submission so no registry state changed. The orchestrator
    /// logs and waits for the next tick.
    #[error("quorum not reached: signed={signed_bps}bps required={required_bps}bps")]
    QuorumNotReached {
        /// Signed stake expressed in basis points (0–10_000).
        signed_bps: u16,
        /// Threshold in basis points configured on the aggregator.
        required_bps: u16,
    },

    /// Generic aggregation failure that is not a typed registry revert and is
    /// not retryable without external intervention (e.g. empty operator set,
    /// invalid key material). Not poison.
    #[error("BLS aggregation failed: {0}")]
    AggregationFailed(String),

    // --- Orchestrator tick-level failures -----------------------------------
    /// PCR0 provider returned an error for this tick. Not poison — skip the
    /// tick; the next tick re-reads the view and retries.
    #[error("PCR0 lookup failed: {0}")]
    Pcr0Lookup(String),

    /// Wall-clock is behind the registry's `lastCommitTimestamp`. Not poison —
    /// indicates NTP drift; the orchestrator skips the tick.
    #[error("clock skew detected: {0}")]
    ClockSkew(String),

    /// Operator prepare-phase proposals did not reach majority agreement.
    /// Not poison — the tick is aborted; next tick rebuilds from fresh view.
    #[error("operator proposal disagreement at sequence {sequence_no}")]
    OperatorDisagreement {
        /// Sequence number for which the majority proposal was sought.
        sequence_no: u64,
    },
}

impl StateCommitError {
    /// Returns `true` iff the local registry view is now stale and the
    /// orchestrator MUST re-read `(currentSequenceNo, currentStateRoot,
    /// lastCommitTimestamp)` before rebuilding the proposal.
    ///
    /// Encodes the rule from `.claude/rules/lessons.md` — *"State-commit
    /// registry reverts classify as poison"*. All eight typed reverts plus
    /// receipt timeout, on-chain revert, and unknown-selector revert return
    /// `true`. Transport failures ([`OnchainCallFailed`](Self::OnchainCallFailed))
    /// and missing-config errors ([`RegistryNotConfigured`](Self::RegistryNotConfigured))
    /// return `false` — those are retried or skipped without view rebuild.
    pub fn is_poison(&self) -> bool {
        matches!(
            self,
            Self::SequenceGap { .. }
                | Self::StateRootMismatch { .. }
                | Self::TimestampRegression { .. }
                | Self::InvalidPcr0Commitment
                | Self::InvalidNewStateRoot
                | Self::UnsupportedStateCommitVersion { .. }
                | Self::InvalidSealedSnapshot
                | Self::CertificateMessageHashMismatch { .. }
                | Self::ReceiptTimeout { .. }
                | Self::TransactionReverted { .. }
                | Self::UnknownRevert { .. }
        )
        // RegistryNotConfigured, OnchainCallFailed, QuorumNotReached,
        // AggregationFailed, Pcr0Lookup, ClockSkew, OperatorDisagreement
        // all return false — they are transient or pre-submission failures
        // that do not stale the registry view.
    }
}

/// Translate a [`ChainIoError`] surfaced from `commit_state_root` into a
/// typed [`StateCommitError`].
///
/// Walks the chainio error variant tree:
/// - [`ChainIoError::TransactionTimeout`] → [`StateCommitError::ReceiptTimeout`]
/// - [`ChainIoError::TransactionReverted`] → [`StateCommitError::TransactionReverted`]
/// - [`ChainIoError::ContractError`] / [`ChainIoError::ContractErrorWithTx`]
///   whose revert data starts with one of the eight known selectors → typed
///   PDS variant (with structured fields decoded where the selector carries args)
/// - any other revert data → [`StateCommitError::UnknownRevert`]
/// - non-revert errors (RPC, signer, config) → [`StateCommitError::OnchainCallFailed`]
pub fn from_chainio(err: ChainIoError) -> StateCommitError {
    match &err {
        ChainIoError::TransactionTimeout { timeout_secs } => {
            return StateCommitError::ReceiptTimeout {
                timeout_secs: *timeout_secs,
            };
        }
        ChainIoError::TransactionReverted(tx) => {
            return StateCommitError::TransactionReverted { tx_hash: *tx };
        }
        ChainIoError::ContractError(ce) | ChainIoError::ContractErrorWithTx { source: ce, .. } => {
            if let Some(data) = ce.as_revert_data() {
                return decode_revert_data(&data);
            }
        }
        _ => {}
    }
    StateCommitError::OnchainCallFailed(err)
}

/// Decode raw revert bytes into a typed [`StateCommitError`].
///
/// The first 4 bytes are matched against the eight `IStateRootCommittable`
/// selectors. Args are decoded via [`SolError::abi_decode`] when present;
/// decoding failure (truncated payload) falls through to
/// [`StateCommitError::UnknownRevert`].
pub(crate) fn decode_revert_data(data: &[u8]) -> StateCommitError {
    if data.len() < 4 {
        return StateCommitError::UnknownRevert {
            selector_hex: alloy::hex::encode(data),
        };
    }
    let selector: [u8; 4] = data[..4].try_into().expect("len >= 4 checked above");

    if selector == SequenceGap::SELECTOR {
        return SequenceGap::abi_decode(data)
            .map(|e| StateCommitError::SequenceGap {
                expected: e.expected,
                got: e.got,
            })
            .unwrap_or_else(|_| unknown(&selector));
    }
    if selector == StateRootMismatch::SELECTOR {
        return StateRootMismatch::abi_decode(data)
            .map(|e| StateCommitError::StateRootMismatch {
                expected: e.expected,
                got: e.got,
            })
            .unwrap_or_else(|_| unknown(&selector));
    }
    if selector == TimestampRegression::SELECTOR {
        return TimestampRegression::abi_decode(data)
            .map(|e| StateCommitError::TimestampRegression {
                last: e.last,
                got: e.got,
            })
            .unwrap_or_else(|_| unknown(&selector));
    }
    if selector == InvalidPcr0Commitment::SELECTOR {
        return StateCommitError::InvalidPcr0Commitment;
    }
    if selector == InvalidNewStateRoot::SELECTOR {
        return StateCommitError::InvalidNewStateRoot;
    }
    if selector == UnsupportedStateCommitVersion::SELECTOR {
        return UnsupportedStateCommitVersion::abi_decode(data)
            .map(|e| StateCommitError::UnsupportedStateCommitVersion {
                expected: e.expected,
                got: e.got,
            })
            .unwrap_or_else(|_| unknown(&selector));
    }
    if selector == InvalidSealedSnapshot::SELECTOR {
        return StateCommitError::InvalidSealedSnapshot;
    }
    if selector == CertificateMessageHashMismatch::SELECTOR {
        return CertificateMessageHashMismatch::abi_decode(data)
            .map(|e| StateCommitError::CertificateMessageHashMismatch {
                expected: e.expected,
                actual: e.actual,
            })
            .unwrap_or_else(|_| unknown(&selector));
    }
    unknown(&selector)
}

fn unknown(selector: &[u8; 4]) -> StateCommitError {
    StateCommitError::UnknownRevert {
        selector_hex: alloy::hex::encode(selector),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy::primitives::FixedBytes;

    fn b32(byte: u8) -> B256 {
        B256::repeat_byte(byte)
    }

    fn fb32(byte: u8) -> FixedBytes<32> {
        FixedBytes::repeat_byte(byte)
    }

    // ---- is_poison() exhaustive matrix ----

    #[test]
    fn is_poison_typed_reverts_all_true() {
        let cases: Vec<StateCommitError> = vec![
            StateCommitError::SequenceGap { expected: 5, got: 4 },
            StateCommitError::StateRootMismatch {
                expected: b32(0xaa),
                got: b32(0xbb),
            },
            StateCommitError::TimestampRegression { last: 100, got: 100 },
            StateCommitError::InvalidPcr0Commitment,
            StateCommitError::InvalidNewStateRoot,
            StateCommitError::UnsupportedStateCommitVersion { expected: 1, got: 2 },
            StateCommitError::InvalidSealedSnapshot,
            StateCommitError::CertificateMessageHashMismatch {
                expected: b32(0xaa),
                actual: b32(0xbb),
            },
        ];
        for case in cases {
            assert!(case.is_poison(), "typed revert variant must be poison: {case:?}");
        }
    }

    #[test]
    fn is_poison_transport_failures_all_true() {
        let cases: Vec<StateCommitError> = vec![
            StateCommitError::ReceiptTimeout { timeout_secs: 60 },
            StateCommitError::TransactionReverted { tx_hash: b32(0x11) },
            StateCommitError::UnknownRevert {
                selector_hex: "deadbeef".into(),
            },
        ];
        for case in cases {
            assert!(case.is_poison(), "transport failure must be poison: {case:?}");
        }
    }

    #[test]
    fn is_poison_config_and_transient_false() {
        assert!(!StateCommitError::RegistryNotConfigured.is_poison());
        // OnchainCallFailed wraps non-revert ChainIoError variants
        let inner = ChainIoError::SendAggregatedResponseError;
        assert!(!StateCommitError::OnchainCallFailed(inner).is_poison());
    }

    // ---- decode_revert_data: each selector + structured field round-trip ----

    #[test]
    fn decode_sequence_gap_extracts_fields() {
        let on_chain = SequenceGap { expected: 42, got: 41 };
        let data = on_chain.abi_encode();
        match decode_revert_data(&data) {
            StateCommitError::SequenceGap { expected, got } => {
                assert_eq!(expected, 42);
                assert_eq!(got, 41);
            }
            other => panic!("expected SequenceGap, got {other:?}"),
        }
    }

    #[test]
    fn decode_state_root_mismatch_extracts_fields() {
        let on_chain = StateRootMismatch {
            expected: fb32(0xaa),
            got: fb32(0xbb),
        };
        let data = on_chain.abi_encode();
        match decode_revert_data(&data) {
            StateCommitError::StateRootMismatch { expected, got } => {
                assert_eq!(expected, b32(0xaa));
                assert_eq!(got, b32(0xbb));
            }
            other => panic!("expected StateRootMismatch, got {other:?}"),
        }
    }

    #[test]
    fn decode_timestamp_regression_extracts_fields() {
        let on_chain = TimestampRegression { last: 100, got: 100 };
        let data = on_chain.abi_encode();
        match decode_revert_data(&data) {
            StateCommitError::TimestampRegression { last, got } => {
                assert_eq!(last, 100);
                assert_eq!(got, 100);
            }
            other => panic!("expected TimestampRegression, got {other:?}"),
        }
    }

    #[test]
    fn decode_invalid_pcr0_commitment() {
        let data = InvalidPcr0Commitment {}.abi_encode();
        assert!(matches!(
            decode_revert_data(&data),
            StateCommitError::InvalidPcr0Commitment
        ));
    }

    #[test]
    fn decode_invalid_new_state_root() {
        let data = InvalidNewStateRoot {}.abi_encode();
        assert!(matches!(
            decode_revert_data(&data),
            StateCommitError::InvalidNewStateRoot
        ));
    }

    #[test]
    fn decode_unsupported_version_extracts_fields() {
        let on_chain = UnsupportedStateCommitVersion { expected: 1, got: 2 };
        let data = on_chain.abi_encode();
        match decode_revert_data(&data) {
            StateCommitError::UnsupportedStateCommitVersion { expected, got } => {
                assert_eq!(expected, 1);
                assert_eq!(got, 2);
            }
            other => panic!("expected UnsupportedStateCommitVersion, got {other:?}"),
        }
    }

    #[test]
    fn decode_invalid_sealed_snapshot() {
        let data = InvalidSealedSnapshot {}.abi_encode();
        assert!(matches!(
            decode_revert_data(&data),
            StateCommitError::InvalidSealedSnapshot
        ));
    }

    #[test]
    fn decode_cert_message_hash_mismatch_extracts_fields() {
        let on_chain = CertificateMessageHashMismatch {
            expected: fb32(0xcc),
            actual: fb32(0xdd),
        };
        let data = on_chain.abi_encode();
        match decode_revert_data(&data) {
            StateCommitError::CertificateMessageHashMismatch { expected, actual } => {
                assert_eq!(expected, b32(0xcc));
                assert_eq!(actual, b32(0xdd));
            }
            other => panic!("expected CertificateMessageHashMismatch, got {other:?}"),
        }
    }

    // ---- decode_revert_data: edge cases ----

    #[test]
    fn decode_empty_data_returns_unknown() {
        match decode_revert_data(&[]) {
            StateCommitError::UnknownRevert { selector_hex } => assert!(selector_hex.is_empty()),
            other => panic!("expected UnknownRevert, got {other:?}"),
        }
    }

    #[test]
    fn decode_short_data_returns_unknown_with_partial_hex() {
        match decode_revert_data(&[0xab, 0xcd]) {
            StateCommitError::UnknownRevert { selector_hex } => assert_eq!(selector_hex, "abcd"),
            other => panic!("expected UnknownRevert, got {other:?}"),
        }
    }

    #[test]
    fn decode_unknown_selector_returns_unknown_with_hex() {
        // A selector not in the IStateRootCommittable set
        let data = [0xde, 0xad, 0xbe, 0xef];
        match decode_revert_data(&data) {
            StateCommitError::UnknownRevert { selector_hex } => assert_eq!(selector_hex, "deadbeef"),
            other => panic!("expected UnknownRevert, got {other:?}"),
        }
    }

    // ---- from_chainio: chainio variant routing ----

    #[test]
    fn from_chainio_timeout_maps_to_receipt_timeout() {
        let err = ChainIoError::TransactionTimeout { timeout_secs: 60 };
        match from_chainio(err) {
            StateCommitError::ReceiptTimeout { timeout_secs } => assert_eq!(timeout_secs, 60),
            other => panic!("expected ReceiptTimeout, got {other:?}"),
        }
    }

    #[test]
    fn from_chainio_reverted_maps_to_transaction_reverted() {
        let tx = b32(0x42);
        match from_chainio(ChainIoError::TransactionReverted(tx)) {
            StateCommitError::TransactionReverted { tx_hash } => assert_eq!(tx_hash, tx),
            other => panic!("expected TransactionReverted, got {other:?}"),
        }
    }

    #[test]
    fn from_chainio_non_revert_maps_to_onchain_call_failed() {
        // A ChainIoError that's neither TransactionTimeout, TransactionReverted, nor
        // a ContractError carrying revert data must surface as OnchainCallFailed.
        let err = ChainIoError::SendAggregatedResponseError;
        assert!(matches!(from_chainio(err), StateCommitError::OnchainCallFailed(_)));
    }
}