newton-chainio 0.5.2

newton prover chainio
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
//! Gateway-to-operator RPC authentication envelope (EIP-712 typed-data).
//!
//! Operator RPC methods that should only be callable by an authorized task
//! generator (the gateway acting on behalf of a registered task generator)
//! wrap their request body in an [`Authenticated`] envelope carrying an
//! [`OperatorRpcAuth`] EIP-712 signature over an [`OperatorRpcCall`] struct.
//!
//! ## Wire format
//!
//! ```json
//! {
//!   "auth": {
//!     "call": {
//!       "method": "newt_simulatePolicyData",
//!       "paramsHash": "0x...",
//!       "chainId": 31337,
//!       "expiresAt": 1700000060,
//!       "taskManager": "0x..."
//!     },
//!     "signature": "0x..."
//!   },
//!   "inner": { /* the original request body */ }
//! }
//! ```
//!
//! ## Replay protection
//!
//! Expiry-only — no per-signer nonce. Reasoning:
//! - All endpoints in scope are either pure-compute reads (`simulate*`,
//!   `validateSecretsSchema`, `getPublicKey`) or have downstream
//!   application-layer replay protection. `signStateCommit` is bound to
//!   `(sequenceNo, prevStateRoot)` enforced on-chain by `StateCommitRegistry`
//!   typed reverts. `signedRead` (post-Phase-1.3) is bound to
//!   `(sequence_no, cert_hash)`.
//! - Per-signer nonce tracking would add ~1-2µs CAS per request and per-signer
//!   memory state — strictly redundant for the threat model where the gateway
//!   is the sole legitimate caller.
//! - 60s expiry window minimizes the value of a captured envelope while
//!   tolerating clock skew between gateway and operator.
//!
//! `DEFAULT_EXPIRY_SECS = 60` is what the gateway signs with on every forward;
//! `MAX_EXPIRY_WINDOW_SECS = 120` is the operator-side cap that bounds an
//! attacker's choice if the gateway is compromised and tries to mint
//! long-lived envelopes. The 2× ratio is the slack budget for clock skew.
//!
//! ## Params hash
//!
//! `OperatorRpcCall.paramsHash = keccak256(bincode::serialize(&inner))`.
//!
//! Both gateway and operator share the request struct definitions via
//! `newton-prover-core`, so bincode produces byte-identical output on both
//! sides without canonicalization rules. JSON serialization would require
//! sorted-key + whitespace normalization, which is fragile.

use alloy::{
    primitives::{keccak256, Address, Bytes, Signature, B256, U256},
    signers::{local::PrivateKeySigner, SignerSync},
};
use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;

/// EIP-712 domain name for operator RPC envelopes.
pub const OPERATOR_RPC_DOMAIN_NAME: &str = "Newton Operator RPC";

/// EIP-712 domain version.
pub const OPERATOR_RPC_DOMAIN_VERSION: &str = "1";

/// Maximum acceptable forward expiry window from now, in seconds.
///
/// An envelope with `expiresAt > now() + MAX_EXPIRY_WINDOW_SECS` is rejected.
/// Prevents a hostile or buggy gateway from minting envelopes valid for an
/// unbounded time. Set at 2× the nominal 60s expiry window to tolerate
/// modest clock skew between gateway and operator.
pub const MAX_EXPIRY_WINDOW_SECS: u64 = 120;

/// Default forward expiry window for newly-signed envelopes.
///
/// Production gateway forwarders pass this value to [`sign_authenticated`].
/// Tests may pass smaller values to exercise expiry-edge behavior.
pub const DEFAULT_EXPIRY_SECS: u64 = 60;

/// EIP-712 type string for [`OperatorRpcCall`]. Used to compute the typehash.
const OPERATOR_RPC_CALL_TYPE: &[u8] =
    b"OperatorRpcCall(string method,bytes32 paramsHash,uint64 chainId,uint64 expiresAt,address taskManager)";

/// EIP-712 typed-data envelope binding a gateway-signed RPC call to a
/// specific method, chain, body hash, and expiry.
///
/// Field naming matches the EIP-712 type string above (camelCase).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperatorRpcCall {
    /// Fully-qualified RPC method name (e.g. `"newt_simulatePolicyData"`).
    pub method: String,
    /// `keccak256(bincode::serialize(&inner))` of the request body, excluding
    /// the auth envelope itself.
    pub params_hash: B256,
    /// Chain ID this RPC call targets. Operator rejects if mismatched.
    pub chain_id: u64,
    /// Unix timestamp (seconds) past which this envelope is rejected.
    pub expires_at: u64,
    /// Task manager address binding the EIP-712 verifying contract.
    pub task_manager: Address,
}

/// Wire-format envelope wrapping an [`OperatorRpcCall`] with its EIP-712 signature.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperatorRpcAuth {
    /// The signed call descriptor.
    pub call: OperatorRpcCall,
    /// 65-byte EIP-712 signature (r || s || v) over `call`.
    pub signature: Bytes,
}

/// Generic authenticated wrapper. RPC handlers parse params as
/// `Authenticated<TheirRequestType>`.
///
/// Wire format: `{ auth: OperatorRpcAuth, inner: T }`. The gateway constructs
/// `auth.call.params_hash = keccak256(bincode::serialize(&inner))` and signs
/// the EIP-712 hash of `auth.call`; the operator recomputes the params hash
/// from the deserialized `inner` and checks it matches `auth.call.params_hash`
/// before any other validation. Bincode is chosen for byte-deterministic
/// serialization — JSON would let key reordering produce a different hash.
///
/// `T` only needs `Serialize`; the operator-side handler deserializes from
/// JSON-RPC params, then re-serializes via bincode for hashing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Authenticated<T> {
    /// Auth envelope.
    pub auth: OperatorRpcAuth,
    /// The original request body (must implement [`Serialize`] for hashing).
    pub inner: T,
}

/// Error variants for operator RPC envelope validation.
#[derive(Debug, Error)]
pub enum OperatorRpcAuthError {
    /// 65-byte signature failed to parse.
    #[error("Invalid signature format: {0}")]
    InvalidSignature(String),
    /// Signer recovery from the EIP-712 prehash failed.
    #[error("Failed to recover signer: {0}")]
    SignerRecoveryFailed(String),
    /// Recovered signer is not in the task generator set.
    #[error("Signer {0} is not an authorized task generator")]
    NotAuthorizedTaskGenerator(Address),
    /// On-chain `isTaskGenerator` lookup failed (transport or RPC error).
    #[error("Failed to check task generator: {0}")]
    TaskGeneratorCheckFailed(String),
    /// Envelope `method` field does not match the dispatched RPC method.
    #[error("Method mismatch: envelope claims '{claimed}', actual '{actual}'")]
    MethodMismatch {
        /// Method name in the envelope.
        claimed: String,
        /// Method name actually being dispatched.
        actual: String,
    },
    /// Envelope `chainId` does not match the operator's chain context.
    #[error("Chain ID mismatch: envelope claims {claimed}, expected {expected}")]
    ChainIdMismatch {
        /// chainId in the envelope.
        claimed: u64,
        /// chainId expected by this dispatch site.
        expected: u64,
    },
    /// Envelope `expiresAt` is at or before the current time.
    #[error("Envelope expired at {expires_at}, current time is {now}")]
    Expired {
        /// expiresAt from the envelope.
        expires_at: u64,
        /// Operator's current unix timestamp.
        now: u64,
    },
    /// Envelope `expiresAt` is too far in the future (capped by [`MAX_EXPIRY_WINDOW_SECS`]).
    #[error("Envelope expiry window too far in future: expiresAt={expires_at}, now+max={max_allowed}")]
    ExpiryTooFar {
        /// expiresAt from the envelope.
        expires_at: u64,
        /// Maximum allowed (`now + MAX_EXPIRY_WINDOW_SECS`).
        max_allowed: u64,
    },
    /// Envelope `paramsHash` does not match the operator-computed hash of the body.
    #[error("Params hash mismatch: envelope claims {claimed}, computed {computed}")]
    ParamsHashMismatch {
        /// paramsHash in the envelope.
        claimed: B256,
        /// keccak256 the operator computed over the inner body.
        computed: B256,
    },
    /// bincode serialization of the inner body failed.
    #[error("Failed to serialize params for hashing: {0}")]
    ParamsSerializationFailed(String),
    /// `SystemTime::now()` is before `UNIX_EPOCH` — the host clock is invalid.
    ///
    /// Without a valid `now`, the envelope's `expires_at` would default to a
    /// past value (`UNIX_EPOCH + DEFAULT_EXPIRY_SECS`), which every operator
    /// rejects as `Expired` — silently taking the entire signed-read surface
    /// offline until the gateway is restarted with a healthy clock. Returning
    /// a typed error fails one request loudly instead of all requests
    /// silently.
    #[error("System clock failure: {0}")]
    ClockFailure(String),
}

/// EIP-712 domain configuration for [`OperatorRpcCall`] signing.
#[derive(Debug, Clone)]
pub struct OperatorRpcEip712Domain {
    /// Domain name. Always [`OPERATOR_RPC_DOMAIN_NAME`].
    pub name: String,
    /// Domain version. Always [`OPERATOR_RPC_DOMAIN_VERSION`].
    pub version: String,
    /// Chain ID that scopes this domain.
    pub chain_id: u64,
    /// Verifying contract address. Bound to the per-chain task manager so
    /// envelopes for one chain's task manager can never verify under another.
    pub verifying_contract: Address,
}

impl OperatorRpcEip712Domain {
    /// Build a domain pinned to a specific chain ID and task manager.
    pub fn new(chain_id: u64, verifying_contract: Address) -> Self {
        Self {
            name: OPERATOR_RPC_DOMAIN_NAME.to_string(),
            version: OPERATOR_RPC_DOMAIN_VERSION.to_string(),
            chain_id,
            verifying_contract,
        }
    }
}

/// Compute the EIP-712 struct hash for an [`OperatorRpcCall`].
fn operator_rpc_call_struct_hash(call: &OperatorRpcCall) -> B256 {
    let type_hash = keccak256(OPERATOR_RPC_CALL_TYPE);
    let method_hash = keccak256(call.method.as_bytes());

    let mut buf = Vec::with_capacity(192);
    buf.extend_from_slice(&type_hash[..]);
    buf.extend_from_slice(&method_hash[..]);
    buf.extend_from_slice(&call.params_hash[..]);
    buf.extend_from_slice(&U256::from(call.chain_id).to_be_bytes::<32>());
    buf.extend_from_slice(&U256::from(call.expires_at).to_be_bytes::<32>());
    let mut padded = [0u8; 32];
    padded[12..].copy_from_slice(&call.task_manager.into_array());
    buf.extend_from_slice(&padded);

    keccak256(&buf)
}

/// Compute the EIP-712 message hash for an [`OperatorRpcCall`] under the given domain.
///
/// Layout: `keccak256("\x19\x01" || domainSeparator || structHash)`.
pub fn compute_operator_rpc_call_hash(call: &OperatorRpcCall, domain: &OperatorRpcEip712Domain) -> B256 {
    let domain_type_hash =
        keccak256(b"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    let name_hash = keccak256(domain.name.as_bytes());
    let version_hash = keccak256(domain.version.as_bytes());

    let mut domain_data = Vec::with_capacity(192);
    domain_data.extend_from_slice(&domain_type_hash[..]);
    domain_data.extend_from_slice(&name_hash[..]);
    domain_data.extend_from_slice(&version_hash[..]);
    domain_data.extend_from_slice(&U256::from(domain.chain_id).to_be_bytes::<32>());
    let mut padded_contract = [0u8; 32];
    padded_contract[12..].copy_from_slice(&domain.verifying_contract.into_array());
    domain_data.extend_from_slice(&padded_contract);

    let domain_separator = keccak256(&domain_data);
    let struct_hash = operator_rpc_call_struct_hash(call);

    let mut message_data = Vec::with_capacity(66);
    message_data.push(0x19u8);
    message_data.push(0x01u8);
    message_data.extend_from_slice(&domain_separator[..]);
    message_data.extend_from_slice(&struct_hash[..]);
    keccak256(&message_data)
}

/// Recover the signer address from an EIP-712 signature over an [`OperatorRpcCall`].
pub fn recover_operator_rpc_signer(
    call: &OperatorRpcCall,
    domain: &OperatorRpcEip712Domain,
    signature_bytes: &Bytes,
) -> Result<Address, OperatorRpcAuthError> {
    let eip712_hash = compute_operator_rpc_call_hash(call, domain);
    let signature = Signature::try_from(signature_bytes.as_ref())
        .map_err(|e| OperatorRpcAuthError::InvalidSignature(e.to_string()))?;
    signature
        .recover_address_from_prehash(&eip712_hash)
        .map_err(|e| OperatorRpcAuthError::SignerRecoveryFailed(e.to_string()))
}

/// Compute the canonical params hash for an RPC request body.
///
/// Uses bincode for deterministic byte-level encoding. Both gateway and
/// operator share the request struct definition via `newton-prover-core`,
/// so the bytes are guaranteed identical.
pub fn compute_params_hash<T: Serialize>(request: &T) -> Result<B256, OperatorRpcAuthError> {
    let bytes =
        bincode::serialize(request).map_err(|e| OperatorRpcAuthError::ParamsSerializationFailed(e.to_string()))?;
    Ok(keccak256(&bytes))
}

/// Validate the structural fields of an [`OperatorRpcCall`] against runtime context.
///
/// Checks (in order):
/// 1. Method name matches the dispatched RPC method
/// 2. Chain ID matches the operator's chain context
/// 3. `expiresAt` is in the future
/// 4. `expiresAt` is not too far in the future
/// 5. `paramsHash` matches the operator-computed hash of the body
///
/// Cheapest-first ordering for DoS resistance: structural checks before
/// any cryptographic recovery.
pub fn validate_operator_rpc_call(
    call: &OperatorRpcCall,
    expected_method: &str,
    expected_chain_id: u64,
    now_secs: u64,
    computed_params_hash: B256,
) -> Result<(), OperatorRpcAuthError> {
    if call.method != expected_method {
        return Err(OperatorRpcAuthError::MethodMismatch {
            claimed: call.method.clone(),
            actual: expected_method.to_string(),
        });
    }
    if call.chain_id != expected_chain_id {
        return Err(OperatorRpcAuthError::ChainIdMismatch {
            claimed: call.chain_id,
            expected: expected_chain_id,
        });
    }
    if call.expires_at <= now_secs {
        return Err(OperatorRpcAuthError::Expired {
            expires_at: call.expires_at,
            now: now_secs,
        });
    }
    let max_allowed = now_secs.saturating_add(MAX_EXPIRY_WINDOW_SECS);
    if call.expires_at > max_allowed {
        return Err(OperatorRpcAuthError::ExpiryTooFar {
            expires_at: call.expires_at,
            max_allowed,
        });
    }
    if call.params_hash != computed_params_hash {
        return Err(OperatorRpcAuthError::ParamsHashMismatch {
            claimed: call.params_hash,
            computed: computed_params_hash,
        });
    }
    Ok(())
}

/// Sign an [`Authenticated<T>`] envelope around `inner`.
///
/// This is the canonical gateway-side helper for wrapping an outbound
/// operator-RPC request body in an EIP-712-authenticated envelope. The signer
/// must be the gateway's task-generator key (the operator side will verify
/// it against on-chain `isTaskGenerator(signer)`).
///
/// `expiry_secs` is the forward window from now until the envelope expires;
/// production callers should pass [`DEFAULT_EXPIRY_SECS`]. Tests may pass
/// smaller values to drive expiry-edge behavior.
///
/// # Errors
///
/// - [`OperatorRpcAuthError::ParamsSerializationFailed`] if `inner` cannot be
///   bincoded (typically only from non-`Serialize` content like raw byte
///   slices that exceed bincode's size cap; ordinary structs do not fail).
/// - [`OperatorRpcAuthError::SignerRecoveryFailed`] if the local signing
///   operation itself fails (effectively impossible for `PrivateKeySigner`
///   but reported as a typed error rather than a panic).
pub fn sign_authenticated<T: Serialize>(
    signer: &PrivateKeySigner,
    method: &'static str,
    chain_id: u64,
    task_manager: Address,
    expiry_secs: u64,
    inner: T,
) -> Result<Authenticated<T>, OperatorRpcAuthError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .map_err(|e| OperatorRpcAuthError::ClockFailure(e.to_string()))?;
    let expires_at = now.saturating_add(expiry_secs);

    let params_hash = compute_params_hash(&inner)?;

    let call = OperatorRpcCall {
        method: method.to_string(),
        params_hash,
        chain_id,
        expires_at,
        task_manager,
    };

    let domain = OperatorRpcEip712Domain::new(chain_id, task_manager);
    let digest = compute_operator_rpc_call_hash(&call, &domain);

    let signature = signer
        .sign_hash_sync(&digest)
        .map_err(|e| OperatorRpcAuthError::SignerRecoveryFailed(e.to_string()))?;

    let signature_bytes = Bytes::from(signature.as_bytes().to_vec());

    Ok(Authenticated {
        auth: OperatorRpcAuth {
            call,
            signature: signature_bytes,
        },
        inner,
    })
}

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

    fn test_domain() -> OperatorRpcEip712Domain {
        OperatorRpcEip712Domain::new(31337, Address::repeat_byte(0xab))
    }

    fn test_call() -> OperatorRpcCall {
        OperatorRpcCall {
            method: "newt_simulatePolicyData".to_string(),
            params_hash: B256::repeat_byte(0x42),
            chain_id: 31337,
            expires_at: 1_700_000_060,
            task_manager: Address::repeat_byte(0xab),
        }
    }

    #[test]
    fn struct_hash_is_deterministic() {
        let call = test_call();
        let h1 = operator_rpc_call_struct_hash(&call);
        let h2 = operator_rpc_call_struct_hash(&call);
        assert_eq!(h1, h2);
    }

    #[test]
    fn message_hash_changes_with_method() {
        let call_a = test_call();
        let mut call_b = call_a.clone();
        call_b.method = "newt_signStateCommit".to_string();
        let domain = test_domain();
        assert_ne!(
            compute_operator_rpc_call_hash(&call_a, &domain),
            compute_operator_rpc_call_hash(&call_b, &domain)
        );
    }

    #[test]
    fn message_hash_changes_with_chain_id() {
        let call = test_call();
        let domain_a = OperatorRpcEip712Domain::new(31337, Address::repeat_byte(0xab));
        let domain_b = OperatorRpcEip712Domain::new(1, Address::repeat_byte(0xab));
        assert_ne!(
            compute_operator_rpc_call_hash(&call, &domain_a),
            compute_operator_rpc_call_hash(&call, &domain_b)
        );
    }

    #[test]
    fn message_hash_changes_with_task_manager() {
        let call = test_call();
        let domain_a = OperatorRpcEip712Domain::new(31337, Address::repeat_byte(0xab));
        let domain_b = OperatorRpcEip712Domain::new(31337, Address::repeat_byte(0xcd));
        assert_ne!(
            compute_operator_rpc_call_hash(&call, &domain_a),
            compute_operator_rpc_call_hash(&call, &domain_b)
        );
    }

    #[test]
    fn message_hash_changes_with_params_hash() {
        let call_a = test_call();
        let mut call_b = call_a.clone();
        call_b.params_hash = B256::repeat_byte(0x43);
        let domain = test_domain();
        assert_ne!(
            compute_operator_rpc_call_hash(&call_a, &domain),
            compute_operator_rpc_call_hash(&call_b, &domain)
        );
    }

    #[test]
    fn params_hash_deterministic_for_same_input() {
        #[derive(Serialize)]
        struct Dummy {
            chain_id: u64,
            value: String,
        }
        let req = Dummy {
            chain_id: 1,
            value: "hello".to_string(),
        };
        let h1 = compute_params_hash(&req).unwrap();
        let h2 = compute_params_hash(&req).unwrap();
        assert_eq!(h1, h2);
    }

    #[test]
    fn params_hash_changes_with_field_value() {
        #[derive(Serialize)]
        struct Dummy {
            value: String,
        }
        let h1 = compute_params_hash(&Dummy { value: "a".to_string() }).unwrap();
        let h2 = compute_params_hash(&Dummy { value: "b".to_string() }).unwrap();
        assert_ne!(h1, h2);
    }

    #[test]
    fn validate_happy_path() {
        let call = test_call();
        validate_operator_rpc_call(
            &call,
            "newt_simulatePolicyData",
            31337,
            1_700_000_000,
            B256::repeat_byte(0x42),
        )
        .expect("happy path validates");
    }

    #[test]
    fn validate_rejects_method_mismatch() {
        let call = test_call();
        let err = validate_operator_rpc_call(&call, "newt_signStateCommit", 31337, 1_700_000_000, call.params_hash)
            .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::MethodMismatch { .. }));
    }

    #[test]
    fn validate_rejects_chain_mismatch() {
        let call = test_call();
        let err = validate_operator_rpc_call(&call, &call.method, 1, 1_700_000_000, call.params_hash).unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::ChainIdMismatch { .. }));
    }

    #[test]
    fn validate_rejects_expired_envelope() {
        let mut call = test_call();
        call.expires_at = 1_699_999_999;
        let err = validate_operator_rpc_call(&call, &call.method, call.chain_id, 1_700_000_000, call.params_hash)
            .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::Expired { .. }));
    }

    #[test]
    fn validate_rejects_envelope_at_exact_expiry() {
        // Boundary: expires_at == now should be rejected (envelope only valid for expires_at > now).
        let mut call = test_call();
        call.expires_at = 1_700_000_000;
        let err = validate_operator_rpc_call(&call, &call.method, call.chain_id, 1_700_000_000, call.params_hash)
            .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::Expired { .. }));
    }

    #[test]
    fn validate_rejects_far_future_expiry() {
        let mut call = test_call();
        call.expires_at = 1_700_000_000 + MAX_EXPIRY_WINDOW_SECS + 1;
        let err = validate_operator_rpc_call(&call, &call.method, call.chain_id, 1_700_000_000, call.params_hash)
            .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::ExpiryTooFar { .. }));
    }

    #[test]
    fn validate_rejects_params_hash_mismatch() {
        let call = test_call();
        let err = validate_operator_rpc_call(
            &call,
            &call.method,
            call.chain_id,
            1_700_000_000,
            B256::repeat_byte(0xff),
        )
        .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::ParamsHashMismatch { .. }));
    }

    #[test]
    fn validate_accepts_expiry_at_max_window() {
        let mut call = test_call();
        call.expires_at = 1_700_000_000 + MAX_EXPIRY_WINDOW_SECS;
        validate_operator_rpc_call(&call, &call.method, call.chain_id, 1_700_000_000, call.params_hash)
            .expect("expiry at exact max should be accepted");
    }

    #[test]
    fn sign_authenticated_round_trips_through_recovery() {
        #[derive(Serialize, Deserialize, Debug, PartialEq)]
        struct Inner {
            chain_id: u64,
            payload: String,
        }
        let signer = PrivateKeySigner::random();
        let expected_signer = signer.address();
        let task_manager = Address::repeat_byte(0xab);
        let chain_id = 31337;
        let inner = Inner {
            chain_id,
            payload: "round-trip".to_string(),
        };

        let env = sign_authenticated(
            &signer,
            "newt_simulatePolicyData",
            chain_id,
            task_manager,
            DEFAULT_EXPIRY_SECS,
            inner,
        )
        .expect("sign succeeds");

        // Recovered signer matches the key that signed.
        let domain = OperatorRpcEip712Domain::new(chain_id, task_manager);
        let recovered =
            recover_operator_rpc_signer(&env.auth.call, &domain, &env.auth.signature).expect("recover succeeds");
        assert_eq!(recovered, expected_signer);

        // Envelope params hash matches the inner body's bincode hash.
        let recomputed = compute_params_hash(&env.inner).expect("hash inner");
        assert_eq!(env.auth.call.params_hash, recomputed);

        // Envelope passes structural validation against the same context.
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        validate_operator_rpc_call(&env.auth.call, "newt_simulatePolicyData", chain_id, now, recomputed)
            .expect("validate succeeds");
    }

    #[test]
    fn sign_authenticated_inner_tamper_is_detected() {
        // If a man-in-the-middle replaces inner with different bytes, params_hash recomputed by
        // the operator no longer matches the signed envelope.
        #[derive(Serialize, Deserialize)]
        struct Inner {
            payload: String,
        }
        let signer = PrivateKeySigner::random();
        let task_manager = Address::repeat_byte(0xab);
        let chain_id = 31337;

        let env = sign_authenticated(
            &signer,
            "newt_simulatePolicyData",
            chain_id,
            task_manager,
            DEFAULT_EXPIRY_SECS,
            Inner {
                payload: "original".to_string(),
            },
        )
        .expect("sign succeeds");

        // Operator side: replace inner, recompute params_hash, validation must reject.
        let tampered = Inner {
            payload: "tampered".to_string(),
        };
        let tampered_hash = compute_params_hash(&tampered).expect("hash tampered");
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        let err = validate_operator_rpc_call(&env.auth.call, "newt_simulatePolicyData", chain_id, now, tampered_hash)
            .unwrap_err();
        assert!(matches!(err, OperatorRpcAuthError::ParamsHashMismatch { .. }));
    }

    #[test]
    fn authenticated_envelope_round_trips_via_json() {
        #[derive(Serialize, Deserialize, Debug, PartialEq)]
        struct Inner {
            chain_id: u64,
            payload: String,
        }
        let envelope = Authenticated {
            auth: OperatorRpcAuth {
                call: test_call(),
                signature: Bytes::from(vec![0xde, 0xad, 0xbe, 0xef]),
            },
            inner: Inner {
                chain_id: 31337,
                payload: "hi".to_string(),
            },
        };
        let json = serde_json::to_string(&envelope).expect("serialize");
        let decoded: Authenticated<Inner> = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(decoded.inner, envelope.inner);
        assert_eq!(decoded.auth.call.method, envelope.auth.call.method);
        assert_eq!(decoded.auth.signature, envelope.auth.signature);
    }
}