zisk-common 1.1.0-alpha

Common utilities and shared types for the ZisK zkVM
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
//! Hints for ZisK Precompiles stream processing
//!
//! This module provides functionality for parsing precompile hints
//! that are received as a stream of `u64` values. Hints are used to provide preprocessed
//! data to precompile operations in the ZisK zkVM.
//!
//! # Hint Format
//!
//! Each hint consists of:
//! - A **header** (`u64`): Contains the hint type (upper 32 bits) and data length (lower 32 bits)
//! - **Data** (`[u64; length]`): The hint payload, where `length` is specified in the header
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                         Header (u64)                        │
//! ├·····························································┤
//! │      Hint Code (32 bits)           Length (32 bits).        │
//! ├─────────────────────────────────────────────────────────────┤
//! │                        Data[0] (u64)                        │
//! ├─────────────────────────────────────────────────────────────┤
//! │                        Data[1] (u64)                        │
//! ├─────────────────────────────────────────────────────────────┤
//! │                             ...                             │
//! ├─────────────────────────────────────────────────────────────┤
//! │                       Data[N-1] (u64)                       │
//! └─────────────────────────────────────────────────────────────┘
//!
//! where N = ceil(Length / 8)
//!
//! - Hint Code — Control code or Data Hint Type
//! - Length — Data length in bytes
//!
//! ## Hint Type Layout
//!
//! ### Control codes
//!
//! The following control codes are defined:
//! - `0x00` (START): Reset processor state and global sequence.
//! - `0x01` (END): Wait until completion of all pending hints.
//! - `0x02` (CANCEL): Cancel current stream and stop processing further hints.
//! - `0x03` (ERROR): Indicate an error has occurred; stop processing further hints.
//!
//! Control codes are for control only and do not have any associated data (Length should be zero).
//!
//! ### Data Hint Types:
//!
//! For data hints, the hint code (32 bits) is structured as follows:
//! - **Bit 31 (MSB)**: Indicates if the data is pass-through (1) or requires computation (0)
//! - **Bits 0-30**: Encode the built-in hint code as defined in the constants
//!   (e.g., `HINT_SHA256`, `HINT_BN254_G1_ADD`, `HINT_SECP256K1_RECOVER`, etc.)
//! ```

use std::fmt::Display;

use crate::error::{CommonError, Result};

// Hint code constants live in `zisk-definitions` (a dependency-free, `no_std` leaf
// crate) so the guest-side `ziskos` crate can share them without pulling in this
// crate's prover stack. Re-exported here so existing `zisk_common::HINT_*`
// consumers keep working unchanged.
pub use zisk_definitions::hints::*;

/// Control code variants for stream control.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum CtrlHint {
    /// Reset processor state and global sequence.
    Start = CTRL_START,
    /// Wait until completion of all pending hints.
    End = CTRL_END,
    /// Cancel current stream and stop processing.
    Cancel = CTRL_CANCEL,
    /// Signal error and stop processing.
    Error = CTRL_ERROR,
}

impl Display for CtrlHint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            CtrlHint::Start => "CTRL_START",
            CtrlHint::End => "CTRL_END",
            CtrlHint::Cancel => "CTRL_CANCEL",
            CtrlHint::Error => "CTRL_ERROR",
        };
        write!(f, "{} ({:#x})", name, *self as u32)
    }
}

impl TryFrom<u32> for CtrlHint {
    type Error = CommonError;

    fn try_from(value: u32) -> Result<Self> {
        match value {
            CTRL_START => Ok(Self::Start),
            CTRL_END => Ok(Self::End),
            CTRL_CANCEL => Ok(Self::Cancel),
            CTRL_ERROR => Ok(Self::Error),
            _ => Err(CommonError::InvalidHint(format!("Invalid control code: {:#x}", value))),
        }
    }
}

/// Built-in hint type variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum BuiltInHint {
    // INPUT hint types.
    /// Input data hint.
    Input = HINT_INPUT,

    // SHA256 hint types.
    /// Compute SHA-256 hash
    Sha256 = HINT_SHA256,

    // BN254 hint types
    /// BN254 elliptic curve addition.
    Bn254G1Add = HINT_BN254_G1_ADD,
    /// BN254 elliptic curve scalar multiplication.
    Bn254G1Mul = HINT_BN254_G1_MUL,
    /// BN254 pairing check.
    Bn254PairingCheck = HINT_BN254_PAIRING_CHECK,

    // Secp256k1 hint types.
    /// secp256k1 ECDSA recovery returning raw 64-byte public key (matches zkvm_secp256k1_ecrecover).
    Secp256k1Ecrecover = HINT_SECP256K1_ECRECOVER,
    /// secp256k1 ECDSA signature verification (matches zkvm_secp256k1_verify).
    Secp256k1EcdsaVerify = HINT_SECP256K1_ECDSA_VERIFY,

    // Secp256r1 hint types.
    /// secp256r1 (P-256) signature verification.
    Secp256r1EcdsaVerify = HINT_SECP256R1_ECDSA_VERIFY,

    // BLS12-381 hint types.
    /// BLS12-381 G1 addition (returns 96-byte unpadded G1 point)
    Bls12_381G1Add = HINT_BLS12_381_G1_ADD,
    /// BLS12-381 G1 multi-scalar multiplication (returns 96-byte unpadded G1 point)
    Bls12_381G1Msm = HINT_BLS12_381_G1_MSM,
    /// BLS12-381 G2 addition (returns 192-byte unpadded G2 point)
    Bls12_381G2Add = HINT_BLS12_381_G2_ADD,
    /// BLS12-381 G2 multi-scalar multiplication (returns 192-byte unpadded G2 point)
    Bls12_381G2Msm = HINT_BLS12_381_G2_MSM,
    /// BLS12-381 pairing check.
    Bls12_381PairingCheck = HINT_BLS12_381_PAIRING_CHECK,
    /// BLS12-381 map field element to G1.
    Bls12_381FpToG1 = HINT_BLS12_381_FP_TO_G1,
    /// BLS12-381 map field element to G2.
    Bls12_381Fp2ToG2 = HINT_BLS12_381_FP2_TO_G2,

    // Modular exponentiation hint types.
    /// Modular exponentiation.
    ModExp = HINT_MODEXP,
    /// 256-bit modular multiplication (EVM MULMOD opcode).
    MulMod256 = HINT_MULMOD256,
    /// 256-bit modular reduction.
    ReduceMod256 = HINT_REDUCE_MOD256,
    /// 256-bit modular addition.
    AddMod256 = HINT_ADD_MOD256,
    /// 256-bit modular squaring.
    SquareMod256 = HINT_SQUARE_MOD256,
    /// 256-bit modular exponentiation.
    PowMod256 = HINT_POW_MOD256,
    /// 256-bit modular inverse.
    InvMod256 = HINT_INV_MOD256,

    // KZG hint types.
    /// Verify KZG proof.
    VerifyKzgProof = HINT_VERIFY_KZG_PROOF,

    // Keccak256 hint types.
    /// Compute Keccak-256 hash.
    Keccak256 = HINT_KECCAK256,

    // Blake2b hint types.
    /// Blake2b compression function.
    Blake2bCompress = HINT_BLAKE2B_COMPRESS,

    // RIPEMD-160 hint types.
    /// RIPEMD-160 hash (pure software implementation, no ZK circuit witness).
    Ripemd160 = HINT_RIPEMD160,
}

impl Display for BuiltInHint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            // INPUT hint types
            BuiltInHint::Input => "INPUT",
            // SHA256 hint types
            BuiltInHint::Sha256 => "SHA256",
            // BN254 Hints
            BuiltInHint::Bn254G1Add => "BN254_G1_ADD",
            BuiltInHint::Bn254G1Mul => "BN254_G1_MUL",
            BuiltInHint::Bn254PairingCheck => "BN254_PAIRING_CHECK",
            // Secp256k1 Hints
            BuiltInHint::Secp256k1Ecrecover => "SECP256K1_ECRECOVER",
            BuiltInHint::Secp256k1EcdsaVerify => "SECP256K1_ECDSA_VERIFY",
            // Secp256r1 Hints
            BuiltInHint::Secp256r1EcdsaVerify => "SECP256R1_ECDSA_VERIFY",
            // BLS12-381 Hints
            BuiltInHint::Bls12_381G1Add => "BLS12_381_G1_ADD",
            BuiltInHint::Bls12_381G1Msm => "BLS12_381_G1_MSM",
            BuiltInHint::Bls12_381G2Add => "BLS12_381_G2_ADD",
            BuiltInHint::Bls12_381G2Msm => "BLS12_381_G2_MSM",
            BuiltInHint::Bls12_381PairingCheck => "BLS12_381_PAIRING_CHECK",
            BuiltInHint::Bls12_381FpToG1 => "BLS12_381_FP_TO_G1",
            BuiltInHint::Bls12_381Fp2ToG2 => "BLS12_381_FP2_TO_G2",
            // Modular Exponentiation Hint
            BuiltInHint::ModExp => "MODEXP",
            BuiltInHint::MulMod256 => "MULMOD256",
            BuiltInHint::ReduceMod256 => "REDUCE_MOD256",
            BuiltInHint::AddMod256 => "ADD_MOD256",
            BuiltInHint::SquareMod256 => "SQUARE_MOD256",
            BuiltInHint::PowMod256 => "POW_MOD256",
            BuiltInHint::InvMod256 => "INV_MOD256",
            // KZG Hint
            BuiltInHint::VerifyKzgProof => "VERIFY_KZG_PROOF",
            // Keccak256 Hint
            BuiltInHint::Keccak256 => "KECCAK256",
            // Blake2b Hint
            BuiltInHint::Blake2bCompress => "BLAKE2B_COMPRESS",
            // RIPEMD-160 Hint
            BuiltInHint::Ripemd160 => "RIPEMD160",
        };

        write!(f, "{} ({:#x})", name, *self as u32)
    }
}

impl TryFrom<u32> for BuiltInHint {
    type Error = CommonError;

    fn try_from(value: u32) -> Result<Self> {
        match value {
            // INPUT hint types
            HINT_INPUT => Ok(Self::Input),
            // SHA256 hint types
            HINT_SHA256 => Ok(Self::Sha256),
            // BN254 Hints
            HINT_BN254_G1_ADD => Ok(Self::Bn254G1Add),
            HINT_BN254_G1_MUL => Ok(Self::Bn254G1Mul),
            HINT_BN254_PAIRING_CHECK => Ok(Self::Bn254PairingCheck),
            // Secp256k1 Hints
            HINT_SECP256K1_ECRECOVER => Ok(Self::Secp256k1Ecrecover),
            HINT_SECP256K1_ECDSA_VERIFY => Ok(Self::Secp256k1EcdsaVerify),
            // Secp256r1 Hints
            HINT_SECP256R1_ECDSA_VERIFY => Ok(Self::Secp256r1EcdsaVerify),
            // BLS12-381 Hints
            HINT_BLS12_381_G1_ADD => Ok(Self::Bls12_381G1Add),
            HINT_BLS12_381_G1_MSM => Ok(Self::Bls12_381G1Msm),
            HINT_BLS12_381_G2_ADD => Ok(Self::Bls12_381G2Add),
            HINT_BLS12_381_G2_MSM => Ok(Self::Bls12_381G2Msm),
            HINT_BLS12_381_PAIRING_CHECK => Ok(Self::Bls12_381PairingCheck),
            HINT_BLS12_381_FP_TO_G1 => Ok(Self::Bls12_381FpToG1),
            HINT_BLS12_381_FP2_TO_G2 => Ok(Self::Bls12_381Fp2ToG2),
            // Modular Exponentiation Hint
            HINT_MODEXP => Ok(Self::ModExp),
            HINT_MULMOD256 => Ok(Self::MulMod256),
            HINT_REDUCE_MOD256 => Ok(Self::ReduceMod256),
            HINT_ADD_MOD256 => Ok(Self::AddMod256),
            HINT_SQUARE_MOD256 => Ok(Self::SquareMod256),
            HINT_POW_MOD256 => Ok(Self::PowMod256),
            HINT_INV_MOD256 => Ok(Self::InvMod256),
            // KZG Hint
            HINT_VERIFY_KZG_PROOF => Ok(Self::VerifyKzgProof),
            // Keccak256 Hint
            HINT_KECCAK256 => Ok(Self::Keccak256),
            // Blake2b Hint
            HINT_BLAKE2B_COMPRESS => Ok(Self::Blake2bCompress),
            // RIPEMD-160 Hint
            HINT_RIPEMD160 => Ok(Self::Ripemd160),
            _ => Err(CommonError::InvalidHint(format!("Invalid built-in hint code: {:#x}", value))),
        }
    }
}

/// Hint code representing either a control code or built-in hint type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum HintCode {
    /// Control code for stream management.
    Ctrl(CtrlHint),
    /// Built-in hint type.
    BuiltIn(BuiltInHint),
    /// Custom hint type
    Custom(u32),
}

impl Display for HintCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HintCode::Ctrl(ctrl) => write!(f, "{}", ctrl),
            HintCode::BuiltIn(builtin) => write!(f, "{}", builtin),
            HintCode::Custom(code) => write!(f, "CUSTOM_HINT_{:#x}", code),
        }
    }
}

impl TryFrom<u32> for HintCode {
    type Error = CommonError;

    fn try_from(value: u32) -> Result<Self> {
        // Try CtrlCode first
        if let Ok(ctrl) = CtrlHint::try_from(value) {
            return Ok(HintCode::Ctrl(ctrl));
        }
        // Try BuiltInHint next
        if let Ok(builtin) = BuiltInHint::try_from(value) {
            return Ok(HintCode::BuiltIn(builtin));
        }
        // Unknown codes return error - custom codes handled separately
        Err(CommonError::InvalidHint(format!("Unknown hint code: {:#x}", value)))
    }
}

impl HintCode {
    /// Convert HintCode to its u32 discriminant value.
    #[inline]
    pub const fn to_u32(self) -> u32 {
        match self {
            // Control Codes
            HintCode::Ctrl(CtrlHint::Start) => CTRL_START,
            HintCode::Ctrl(CtrlHint::End) => CTRL_END,
            HintCode::Ctrl(CtrlHint::Cancel) => CTRL_CANCEL,
            HintCode::Ctrl(CtrlHint::Error) => CTRL_ERROR,

            // Built-In Hint Codes
            // INPUT hint types
            HintCode::BuiltIn(BuiltInHint::Input) => HINT_INPUT,
            // SHA256 Hints
            HintCode::BuiltIn(BuiltInHint::Sha256) => HINT_SHA256,
            // BN254 Hints
            HintCode::BuiltIn(BuiltInHint::Bn254G1Add) => HINT_BN254_G1_ADD,
            HintCode::BuiltIn(BuiltInHint::Bn254G1Mul) => HINT_BN254_G1_MUL,
            HintCode::BuiltIn(BuiltInHint::Bn254PairingCheck) => HINT_BN254_PAIRING_CHECK,
            // Secp256k1 Hints
            HintCode::BuiltIn(BuiltInHint::Secp256k1Ecrecover) => HINT_SECP256K1_ECRECOVER,
            HintCode::BuiltIn(BuiltInHint::Secp256k1EcdsaVerify) => HINT_SECP256K1_ECDSA_VERIFY,
            // Secp256r1 Hints
            HintCode::BuiltIn(BuiltInHint::Secp256r1EcdsaVerify) => HINT_SECP256R1_ECDSA_VERIFY,
            // BLS12-381 Hints
            HintCode::BuiltIn(BuiltInHint::Bls12_381G1Add) => HINT_BLS12_381_G1_ADD,
            HintCode::BuiltIn(BuiltInHint::Bls12_381G1Msm) => HINT_BLS12_381_G1_MSM,
            HintCode::BuiltIn(BuiltInHint::Bls12_381G2Add) => HINT_BLS12_381_G2_ADD,
            HintCode::BuiltIn(BuiltInHint::Bls12_381G2Msm) => HINT_BLS12_381_G2_MSM,
            HintCode::BuiltIn(BuiltInHint::Bls12_381PairingCheck) => HINT_BLS12_381_PAIRING_CHECK,
            HintCode::BuiltIn(BuiltInHint::Bls12_381FpToG1) => HINT_BLS12_381_FP_TO_G1,
            HintCode::BuiltIn(BuiltInHint::Bls12_381Fp2ToG2) => HINT_BLS12_381_FP2_TO_G2,
            // Modular Exponentiation Hint
            HintCode::BuiltIn(BuiltInHint::ModExp) => HINT_MODEXP,
            HintCode::BuiltIn(BuiltInHint::MulMod256) => HINT_MULMOD256,
            HintCode::BuiltIn(BuiltInHint::ReduceMod256) => HINT_REDUCE_MOD256,
            HintCode::BuiltIn(BuiltInHint::AddMod256) => HINT_ADD_MOD256,
            HintCode::BuiltIn(BuiltInHint::SquareMod256) => HINT_SQUARE_MOD256,
            HintCode::BuiltIn(BuiltInHint::PowMod256) => HINT_POW_MOD256,
            HintCode::BuiltIn(BuiltInHint::InvMod256) => HINT_INV_MOD256,
            // KZG Hint
            HintCode::BuiltIn(BuiltInHint::VerifyKzgProof) => HINT_VERIFY_KZG_PROOF,
            // Keccak256 Hint
            HintCode::BuiltIn(BuiltInHint::Keccak256) => HINT_KECCAK256,

            // Blake2b Hint
            HintCode::BuiltIn(BuiltInHint::Blake2bCompress) => HINT_BLAKE2B_COMPRESS,
            // RIPEMD-160 Hint
            HintCode::BuiltIn(BuiltInHint::Ripemd160) => HINT_RIPEMD160,

            // Custom Hints
            HintCode::Custom(code) => code,
        }
    }
}

/// Represents a partially received hint when the slice doesn't contain all data.
///
/// This is returned when the hint header has been parsed but there isn't enough
/// data in the slice to complete the hint.
#[derive(Debug, Clone)]
pub struct PartialPrecompileHint {
    /// The type of hint, determining how the data should be processed.
    pub hint_code: HintCode,
    /// Whether this hint contains pass-through data (true) or requires computation (false).
    pub is_passthrough: bool,
    /// The partial hint payload data received so far.
    pub data: Vec<u64>,
    /// Total data length in bytes expected for this hint.
    pub expected_len_bytes: usize,
    /// Number of u64s still needed to complete the hint.
    pub remaining_u64s: usize,
}

/// Result of parsing a hint from a u64 slice.
#[derive(Debug)]
pub enum PrecompileHintParseResult {
    /// A complete hint was successfully parsed.
    Complete(PrecompileHint),
    /// A partial hint was received; more data is needed.
    Partial(PartialPrecompileHint),
}

/// Represents a single precompile hint parsed from a `u64` slice.
///
/// A hint consists of a type identifier and associated data. The hint type
/// determines how the data should be processed by the precompile hints processor.
pub struct PrecompileHint {
    /// The type of hint, determining how the data should be processed.
    pub hint_code: HintCode,
    /// Whether this hint contains pass-through data (true) or requires computation (false).
    /// Determined by bit 31 (MSB) of the hint code.
    pub is_passthrough: bool,
    /// The hint payload data.
    pub data: Vec<u64>,
    /// Data length in bytes
    pub data_len_bytes: usize,
}

impl std::fmt::Debug for PrecompileHint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let data_display = if self.data.len() <= 10 {
            format!("{:x?}", self.data)
        } else {
            format!("{:x?}... ({} more)", &self.data[..10], self.data.len() - 10)
        };
        f.debug_struct("PrecompileHint")
            .field("hint_type", &self.hint_code)
            .field("is_passthrough", &self.is_passthrough)
            .field("data_len_bytes", &self.data_len_bytes)
            .field("data", &data_display)
            .finish()
    }
}

impl PrecompileHint {
    /// Parses a [`PrecompileHint`] from a slice of `u64` values at the given index,
    /// optionally continuing from a previously received partial hint.
    ///
    /// # Arguments
    ///
    /// * `slice` - The source slice containing concatenated hints
    /// * `idx` - The index where the hint header starts
    /// * `allow_custom` - If true, unknown codes create Custom variant; if false, return error
    /// * `partial` - Optional partial hint from a previous call to continue accumulating
    ///
    /// # Returns
    ///
    /// * `Ok((PrecompileHintParseResult, usize))` - The parse result and number of u64s consumed
    /// * `PrecompileHintParseResult::Complete` - Successfully parsed a complete hint
    /// * `PrecompileHintParseResult::Partial` - Parsed header but slice doesn't contain all data
    /// * `Err` - If the slice is empty, index is out of bounds or hint code is invalid
    ///
    /// # Errors
    ///
    /// - [`CommonError::OutOfBounds`] if the slice is empty or the index is out of bounds.
    /// - [`CommonError::InvalidHint`] if the hint code is unrecognized and `allow_custom` is `false`.
    #[inline(always)]
    pub fn from_u64_slice(
        slice: &[u64],
        idx: usize,
        allow_custom: bool,
        partial: Option<PartialPrecompileHint>,
    ) -> Result<(PrecompileHintParseResult, usize)> {
        // If we have a partial hint, continue accumulating from it
        if let Some(partial_hint) = partial {
            let available = slice.len().checked_sub(idx).ok_or(CommonError::OutOfBounds)?;

            if available >= partial_hint.remaining_u64s {
                // We have enough data to complete the hint
                let consumed = partial_hint.remaining_u64s;
                let mut data = partial_hint.data;
                data.extend_from_slice(&slice[idx..idx + consumed]);

                return Ok((
                    PrecompileHintParseResult::Complete(PrecompileHint {
                        hint_code: partial_hint.hint_code,
                        is_passthrough: partial_hint.is_passthrough,
                        data,
                        data_len_bytes: partial_hint.expected_len_bytes,
                    }),
                    consumed,
                ));
            } else {
                // Still not enough data, accumulate what we have
                let mut data = partial_hint.data;
                data.extend_from_slice(&slice[idx..]);
                let remaining_u64s = partial_hint.remaining_u64s - available;

                return Ok((
                    PrecompileHintParseResult::Partial(PartialPrecompileHint {
                        hint_code: partial_hint.hint_code,
                        is_passthrough: partial_hint.is_passthrough,
                        data,
                        expected_len_bytes: partial_hint.expected_len_bytes,
                        remaining_u64s,
                    }),
                    available,
                ));
            }
        }

        // No partial hint, parse from scratch
        if slice.len() <= idx {
            return Err(CommonError::OutOfBounds);
        }

        let header = slice[idx];

        // Extract length from lower 32 bits
        let length = header & 0xFFFFFFFF;
        let length_bytes = length as usize;

        // Calculate how many u64s are needed to hold length
        let num_u64s = length.div_ceil(8) as usize;

        // Extract hint code from upper 32 bits
        let hint_code_32 = (header >> 32) as u32;
        // Extract pass-through flag from bit 31 (MSB) - shift is faster than mask
        let is_passthrough = hint_code_32 >> 31 != 0;
        // Extract the actual hint code from bits 0-30 - mask is optimal
        let hint_code_value = hint_code_32 & 0x7FFFFFFF;

        let hint_code = if allow_custom {
            HintCode::try_from(hint_code_value).unwrap_or(HintCode::Custom(hint_code_value))
        } else {
            HintCode::try_from(hint_code_value)?
        };

        let available_u64s = slice.len() - idx - 1;

        // Check if we have enough data for the complete hint
        if available_u64s < num_u64s {
            // Return partial hint with whatever data we have
            let data = slice[idx + 1..].to_vec();
            let remaining_u64s = num_u64s - available_u64s;
            // Consumed: 1 header + all available data
            let consumed = 1 + available_u64s;

            return Ok((
                PrecompileHintParseResult::Partial(PartialPrecompileHint {
                    hint_code,
                    is_passthrough,
                    data,
                    expected_len_bytes: length_bytes,
                    remaining_u64s,
                }),
                consumed,
            ));
        }

        // Create a new Vec with the hint data.
        let data = slice[idx + 1..idx + 1 + num_u64s].to_vec();
        // Consumed: 1 header + num_u64s data
        let consumed = 1 + num_u64s;

        Ok((
            PrecompileHintParseResult::Complete(PrecompileHint {
                hint_code,
                is_passthrough,
                data,
                data_len_bytes: length_bytes,
            }),
            consumed,
        ))
    }
}