← Back to Pull requests

feat(v2:shred): transaction sanitize and verify ticks #1660

Merged
yewman merged 4 files (878 lines) on Jul 09, 2026 00:42 UTC
View on GitHub
yewman yewman commented on Jul 01, 2026 11:36 UTC
Author

v2/solana: parse-level transaction + tick validation primitives

Adds three parse-time validation primitives the Solana protocol applies to every transaction and every slot's tick chain. Pure v2 library additions, no callers yet — the sol_compat_shred_parse_v1 differential harness wires them in a later PR.

Changes

  • verify_ticks (verify_ticks.zig) — enforces the three slot-level tick invariants: exact tick count for the window, final entry is a tick once full, inter-tick hash counts equal hashes_per_tick. Returns BlockError with the five failure modes. Lives under solana because v2 Entry uses bincode.Vec(VersionedTransaction) where v1 uses []const Transaction.
  • VersionedTransaction.serializedSize — analytical bincode size (no round-trip, allocation-free). Backs the MTU rule size > MAX_BYTES (1232). Per-component size functions co-located with each type.
  • VersionedTransaction.validateAccountLocks — pairwise-distinct check on static account_keys. Duplicates reject as AccountLoadedTwice. Static keys only; ALT-resolved entries must be re-checked post-resolution.
  • VersionedTransaction.sanitize — 13 numbered structural invariants (signature/header agreement, instruction indices, ALT bookkeeping, …). Each documented inline and individually tested. MTU and duplicate-key checks deliberately live in the two methods above — treating them as sanitize errors would conflate parse and account-locking stages.
  • Diff: 878 lines (+785 / -93) across 4 files Reviewer: InKryption Review duration: 10866m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.47) × (1 − Review Confidence (0.70)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.47 · 878 lines diff across 4 files
    0.47
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.48 · 5 substantive comment(s)
    0.48
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    70%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    28 items
    codecov[bot] codecov[bot] commented on Jul 01, 2026 12:00 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 95.01466% with 17 lines in your changes missing coverage. Please review.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | v2/services/replay.zig | 0.00% | 12 Missing :warning: |
    | v2/lib/solana/transaction.zig | 98.48% | 5 Missing :warning: |

    | Files with missing lines | Coverage Δ | |
    |---|---|---|
    | v2/lib/solana/transaction.zig | 96.87% <98.48%> (+96.87%) | :arrow_up: |
    | v2/services/replay.zig | 32.88% <0.00%> (+2.84%) | :arrow_up: |

    ... and 4 files with indirect coverage changes
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    InKryption InKryption commented on code on Jul 02, 2026 15:37 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.

    What is this in reference? I can't seem to find the switch (self) branch this is talking about.

    InKryption InKryption commented on code on Jul 02, 2026 15:46 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }

            for (0..keys.len - 1) |i| {
                for (i + 1..keys.len) |j| {
                    if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
                }
            }
    

    InKryption InKryption commented on code on Jul 02, 2026 15:50 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {

    Would there be any value in changing this from a boolean to an enum? The enum could then represent each "invariant", with the relevant member being annotated with the doc comment here, acting as the "numbering" directly in the code, instead of having to manually maintain these "comment links".

    InKryption InKryption commented on code on Jul 02, 2026 15:53 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {
    +        // `header`, `account_keys`, and `instructions` are field-identical
    +        // across both message variants; only ALTs are v0-only.
    +        const header: MessageHeader, //
    +        const account_keys: []const Pubkey, //
    +        const instructions: []const CompiledInstruction //
    +        = switch (self.message) {
    +            inline else => |m| .{ m.header, m.account_keys.items, m.instructions.items },
    +        };
    +        const address_table_lookups: []const AddressLookup = switch (self.message) {
    +            .legacy => &.{},
    +            .v0 => |m| m.address_table_lookups.items,
    +        };
    +
    +        const sig_cnt: usize = self.signatures.items.len;
    +        const acct_cnt: usize = account_keys.len;
    +        const req_sigs: usize = header.num_required_signatures;
    +        const ro_signed: usize = header.num_readonly_signed_accounts;
    +        const ro_unsigned: usize = header.num_readonly_unsigned_accounts;
    +
    +        // (1) signatures.len in [1, MAX_SIGNATURES]
    +        if (sig_cnt < 1 or sig_cnt > MAX_SIGNATURES) return false;
    +
    +        // (2) outer signatures vector length must match the message header.
    +        if (sig_cnt != req_sigs) return false;
    +
    +        // (3) at least one writable signer (the fee payer).
    +        if (ro_signed >= req_sigs) return false;
    +
    +        // (4) account_keys.len in [req_sigs, MAX_ACCOUNT_ADDRESSES].
    +        if (acct_cnt < req_sigs or acct_cnt > MAX_ACCOUNT_ADDRESSES) return false;
    +
    +        // (5) signing + readonly-unsigned regions must fit inside account_keys.
    +        if (req_sigs + ro_unsigned > acct_cnt) return false;
    +
    +        // (6) instruction count bound.
    +        if (instructions.len > MAX_INSTRUCTIONS) return false;
    +
    +        // (7) any instruction needs both a fee payer and a program (which
    +        // can't be the fee payer per check 8), so account_keys must have at
    +        // least 2.
    +        if (instructions.len > 0 and acct_cnt < 2) return false;
    +
    +        // (8) per-instruction: program_id_index is a static account, but
    +        // not the fee payer. Also collect the max account index referenced
    +        // for check 13.
    +        var max_acct_idx: usize = 0;
    +        for (instructions) |ix| {
    +            const pid: usize = ix.program_id_index;
    +            if (pid == 0 or pid >= acct_cnt) return false;
    +            for (ix.accounts.items) |a| {
    +                if (@as(usize, a) > max_acct_idx) max_acct_idx = a;

    Any reason to not simply use a u8 here?

            var max_acct_idx: u8 = 0;
            for (instructions) |ix| {
                const pid: usize = ix.program_id_index;
                if (pid == 0 or pid >= acct_cnt) return false;
                for (ix.accounts.items) |a| {
                    max_acct_idx = @max(max_acct_idx, a);
    

    InKryption InKryption commented on code on Jul 02, 2026 15:56 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,
    +
    +    fn deinit(self: *Builder) void {
    +        self.signatures.deinit(self.allocator);
    +        self.account_keys.deinit(self.allocator);
    +        for (self.instructions.items) |ix| {
    +            self.allocator.free(ix.accounts.items);
    +            self.allocator.free(ix.data.items);
    +        }
    +        self.instructions.deinit(self.allocator);
    +        for (self.alts.items) |alt| {
    +            self.allocator.free(alt.writable_indexes.items);
    +            self.allocator.free(alt.readonly_indexes.items);
    +        }
    +        self.alts.deinit(self.allocator);
    +    }
    +
    +    /// Distinct pubkey for index `i`. Last byte = `i`; the rest are zero.
    +    fn pubkey(i: u8) Pubkey {
    +        var p: Pubkey = Pubkey.ZEROES;
    +        p.data[31] = i;
    +        return p;
    +    }
    +
    +    /// Push `n` signatures (zeroed; content doesn't affect sanitize).
    +    fn pushSigs(self: *Builder, n: usize) !void {
    +        try self.signatures.appendNTimes(self.allocator, Signature.ZEROES, n);
    +    }
    +
    +    /// Push `n` distinct pubkeys.
    +    fn pushKeys(self: *Builder, n: u8) !void {
    +        var i: u8 = 0;
    +        while (i < n) : (i += 1) try self.account_keys.append(self.allocator, pubkey(i));
    +    }
    +
    +    fn pushInstr(self: *Builder, program_id_index: u8, accounts: []const u8) !void {
    +        const accounts_copy = try self.allocator.dupe(u8, accounts);
    +        const data_copy = try self.allocator.alloc(u8, 0);
    +        try self.instructions.append(self.allocator, .{
    +            .program_id_index = program_id_index,
    +            .accounts = .{ .items = accounts_copy },
    +            .data = .{ .items = data_copy },
    +        });
    +    }
    +
    +    fn pushAlt(self: *Builder, writable: []const u8, readonly: []const u8) !void {
    +        const w = try self.allocator.dupe(u8, writable);
    +        const r = try self.allocator.dupe(u8, readonly);

            const w = try self.allocator.dupe(u8, writable);
            errdefer self.allocator.free(w);
            const r = try self.allocator.dupe(u8, readonly);
            errdefer self.allocator.free(r);
    

    InKryption InKryption commented on code on Jul 02, 2026 16:01 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,
    +
    +    fn deinit(self: *Builder) void {
    +        self.signatures.deinit(self.allocator);
    +        self.account_keys.deinit(self.allocator);
    +        for (self.instructions.items) |ix| {
    +            self.allocator.free(ix.accounts.items);
    +            self.allocator.free(ix.data.items);
    +        }
    +        self.instructions.deinit(self.allocator);
    +        for (self.alts.items) |alt| {
    +            self.allocator.free(alt.writable_indexes.items);
    +            self.allocator.free(alt.readonly_indexes.items);
    +        }
    +        self.alts.deinit(self.allocator);
    +    }
    +
    +    /// Distinct pubkey for index `i`. Last byte = `i`; the rest are zero.
    +    fn pubkey(i: u8) Pubkey {
    +        var p: Pubkey = Pubkey.ZEROES;
    +        p.data[31] = i;
    +        return p;
    +    }
    +
    +    /// Push `n` signatures (zeroed; content doesn't affect sanitize).
    +    fn pushSigs(self: *Builder, n: usize) !void {
    +        try self.signatures.appendNTimes(self.allocator, Signature.ZEROES, n);
    +    }
    +
    +    /// Push `n` distinct pubkeys.
    +    fn pushKeys(self: *Builder, n: u8) !void {
    +        var i: u8 = 0;
    +        while (i < n) : (i += 1) try self.account_keys.append(self.allocator, pubkey(i));
    +    }
    +
    +    fn pushInstr(self: *Builder, program_id_index: u8, accounts: []const u8) !void {
    +        const accounts_copy = try self.allocator.dupe(u8, accounts);
    +        const data_copy = try self.allocator.alloc(u8, 0);
    +        try self.instructions.append(self.allocator, .{
    +            .program_id_index = program_id_index,
    +            .accounts = .{ .items = accounts_copy },
    +            .data = .{ .items = data_copy },
    +        });

    No need to allocate 0 bytes, can initialize []T with &.{}.

            const accounts_copy = try self.allocator.dupe(u8, accounts);
            errdefer self.allocator.free(accounts_copy);
            try self.instructions.append(self.allocator, .{
                .program_id_index = program_id_index,
                .accounts = .{ .items = accounts_copy },
                .data = .{ .items = &.{} },
            });
    

    InKryption InKryption commented on code on Jul 02, 2026 16:03 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,

    With the way this is used, should maybe instead modeled as a parameter on the build method, like builder.build(.v0).

    InKryption InKryption commented on code on Jul 02, 2026 16:04 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},

    General note: let's get used to using the new init decls, because the default initializations are deprecated. i.e. signatures: std.ArrayList(Signature) = .empty.

    InKryption InKryption requested changes on Jul 02, 2026 16:06 UTC
    Changes Requested Reviewer

    Requested changes.

    Sobeston Sobeston commented on code on Jul 02, 2026 17:05 UTC
    Code Review
    v2/lib/solana/verify_ticks.zig:1
    @@ -0,0 +1,93 @@
    +//! Tick verification for a deshredded slot.
    +//!
    +//! A Solana slot is a tick window: entries must include exactly
    +//! `max_tick_height - tick_height` ticks, the final entry must be a tick once
    +//! the window is full, and inter-tick hash counts must equal
    +//! `hashes_per_tick` (when non-zero).
    +//!
    +//! Lives in `v2/lib/solana/` because the v2 `Entry` uses
    +//! `bincode.Vec(VersionedTransaction)` for the transactions field rather than
    +//! v1's `[]const Transaction`. Once both layouts converge, this module
    +//! should move under `shared/core/`.
    +
    +const lib = @import("../lib.zig");
    +const Entry = lib.solana.transaction.Entry;
    +
    +/// Errors a block may fail with during validation. Not every variant is
    +/// produced by `verifyTicks` — the rest are reserved for higher-layer
    +/// validation (entry-batch hashing, duplicate-slot detection, ...).
    +///
    +/// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/ledger/src/block_error.rs#L3-L39
    +pub const BlockError = error{
    +    Incomplete,
    +    InvalidEntryHash,
    +    InvalidLastTick,
    +    TooFewTicks,
    +    TooManyTicks,
    +    InvalidTickHashCount,
    +    TrailingEntry,
    +    DuplicateBlock,
    +};
    +
    +pub const VerifyTicksParams = struct {
    +    hashes_per_tick: u64,
    +    slot: u64,
    +    max_tick_height: u64,
    +    tick_height: u64,
    +    /// True if the slot's last data shred carried the LAST_SHRED_IN_SLOT flag,
    +    /// i.e. all entries for the slot are present.
    +    slot_is_full: bool,
    +    /// Running hash count carried across batches; pass `0` for a single-batch
    +    /// call.
    +    tick_hash_count: u64 = 0,
    +};
    +
    +/// Count how many entries in `entries` are ticks (zero transactions).
    +pub fn tickCount(entries: []const Entry) u64 {
    +    var n: u64 = 0;
    +    for (entries) |e| {
    +        if (e.isTick()) n += 1;
    +    }
    +    return n;
    +}
    +
    +/// Verify that the supplied entries fit cleanly into the slot's tick window.
    +///
    +/// Returns the first `BlockError` detected, or success.
    +///
    +/// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/ledger/src/blockstore_processor.rs#L1057-L1104
    +pub fn verifyTicks(entries: []const Entry, params: VerifyTicksParams) BlockError!void {
    +    const tick_count_in_entries = tickCount(entries);
    +    const next_tick_height = params.tick_height +| tick_count_in_entries;
    +
    +    if (next_tick_height > params.max_tick_height) {
    +        return error.TooManyTicks;
    +    }
    +
    +    if (next_tick_height < params.max_tick_height and params.slot_is_full) {
    +        return error.TooFewTicks;
    +    }
    +
    +    if (next_tick_height == params.max_tick_height) {
    +        if (entries.len == 0 or !entries[entries.len - 1].isTick()) {
    +            return error.TrailingEntry;
    +        }
    +        if (!params.slot_is_full) return error.InvalidLastTick;
    +    }
    +
    +    // Verify inter-tick hash counts. When `hashes_per_tick == 0`, hashing is
    +    // disabled and any count is acceptable.
    +    //
    +    // [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/entry/src/entry.rs#L675-L698
    +    if (params.hashes_per_tick > 0) {
    +        var hash_count = params.tick_hash_count;
    +        for (entries) |entry| {
    +            hash_count = hash_count +| entry.num_hashes;
    +            if (entry.isTick()) {
    +                if (hash_count != params.hashes_per_tick) return error.InvalidTickHashCount;
    +                hash_count = 0;
    +            }
    +        }
    +        if (hash_count >= params.hashes_per_tick) return error.InvalidTickHashCount;

    sanity check, agave takes a tick_hash_count: &mut u64, is it fine to just copy rather than mutate?

    Sobeston Sobeston commented on code on Jul 02, 2026 17:07 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.

    How about we add an assert for this at the top?

    Sobeston Sobeston commented on code on Jul 02, 2026 17:13 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {
    +        // `header`, `account_keys`, and `instructions` are field-identical
    +        // across both message variants; only ALTs are v0-only.
    +        const header: MessageHeader, //
    +        const account_keys: []const Pubkey, //
    +        const instructions: []const CompiledInstruction //
    +        = switch (self.message) {
    +            inline else => |m| .{ m.header, m.account_keys.items, m.instructions.items },
    +        };
    +        const address_table_lookups: []const AddressLookup = switch (self.message) {
    +            .legacy => &.{},
    +            .v0 => |m| m.address_table_lookups.items,
    +        };
    +
    +        const sig_cnt: usize = self.signatures.items.len;
    +        const acct_cnt: usize = account_keys.len;
    +        const req_sigs: usize = header.num_required_signatures;
    +        const ro_signed: usize = header.num_readonly_signed_accounts;
    +        const ro_unsigned: usize = header.num_readonly_unsigned_accounts;
    +
    +        // (1) signatures.len in [1, MAX_SIGNATURES]
    +        if (sig_cnt < 1 or sig_cnt > MAX_SIGNATURES) return false;
    +
    +        // (2) outer signatures vector length must match the message header.
    +        if (sig_cnt != req_sigs) return false;
    +
    +        // (3) at least one writable signer (the fee payer).
    +        if (ro_signed >= req_sigs) return false;
    +
    +        // (4) account_keys.len in [req_sigs, MAX_ACCOUNT_ADDRESSES].
    +        if (acct_cnt < req_sigs or acct_cnt > MAX_ACCOUNT_ADDRESSES) return false;
    +
    +        // (5) signing + readonly-unsigned regions must fit inside account_keys.
    +        if (req_sigs + ro_unsigned > acct_cnt) return false;
    +
    +        // (6) instruction count bound.
    +        if (instructions.len > MAX_INSTRUCTIONS) return false;
    +
    +        // (7) any instruction needs both a fee payer and a program (which
    +        // can't be the fee payer per check 8), so account_keys must have at
    +        // least 2.
    +        if (instructions.len > 0 and acct_cnt < 2) return false;
    +
    +        // (8) per-instruction: program_id_index is a static account, but
    +        // not the fee payer. Also collect the max account index referenced
    +        // for check 13.
    +        var max_acct_idx: usize = 0;
    +        for (instructions) |ix| {
    +            const pid: usize = ix.program_id_index;
    +            if (pid == 0 or pid >= acct_cnt) return false;
    +            for (ix.accounts.items) |a| {
    +                if (@as(usize, a) > max_acct_idx) max_acct_idx = a;
    +            }
    +        }

    I think we're not fully supporting SIMD 406 here, not a huge deal as it's not active yet

    https://github.com/solana-foundation/solana-improvement-documents/blob/main/proposals/0406-maximum-instruction-accounts.md

    Sobeston Sobeston requested changes on Jul 02, 2026 17:13 UTC
    Changes Requested Reviewer

    Requested changes.

    yewman yewman commented on code on Jul 06, 2026 07:21 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.

    Thanks for highlighting, I should have fixed it directly. Added a round trip unit test and updated the switch
    8c495f7ca087d9f334083f0089e1c5c964771e13

    yewman yewman commented on code on Jul 06, 2026 07:36 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},

    fb08f9dc65770d7d7c3d677bb68753d0a9620d3f

    yewman yewman commented on code on Jul 06, 2026 07:36 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,
    +
    +    fn deinit(self: *Builder) void {
    +        self.signatures.deinit(self.allocator);
    +        self.account_keys.deinit(self.allocator);
    +        for (self.instructions.items) |ix| {
    +            self.allocator.free(ix.accounts.items);
    +            self.allocator.free(ix.data.items);
    +        }
    +        self.instructions.deinit(self.allocator);
    +        for (self.alts.items) |alt| {
    +            self.allocator.free(alt.writable_indexes.items);
    +            self.allocator.free(alt.readonly_indexes.items);
    +        }
    +        self.alts.deinit(self.allocator);
    +    }
    +
    +    /// Distinct pubkey for index `i`. Last byte = `i`; the rest are zero.
    +    fn pubkey(i: u8) Pubkey {
    +        var p: Pubkey = Pubkey.ZEROES;
    +        p.data[31] = i;
    +        return p;
    +    }
    +
    +    /// Push `n` signatures (zeroed; content doesn't affect sanitize).
    +    fn pushSigs(self: *Builder, n: usize) !void {
    +        try self.signatures.appendNTimes(self.allocator, Signature.ZEROES, n);
    +    }
    +
    +    /// Push `n` distinct pubkeys.
    +    fn pushKeys(self: *Builder, n: u8) !void {
    +        var i: u8 = 0;
    +        while (i < n) : (i += 1) try self.account_keys.append(self.allocator, pubkey(i));
    +    }
    +
    +    fn pushInstr(self: *Builder, program_id_index: u8, accounts: []const u8) !void {
    +        const accounts_copy = try self.allocator.dupe(u8, accounts);
    +        const data_copy = try self.allocator.alloc(u8, 0);
    +        try self.instructions.append(self.allocator, .{
    +            .program_id_index = program_id_index,
    +            .accounts = .{ .items = accounts_copy },
    +            .data = .{ .items = data_copy },
    +        });

    fb08f9dc65770d7d7c3d677bb68753d0a9620d3f

    yewman yewman commented on code on Jul 06, 2026 07:36 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,
    +
    +    fn deinit(self: *Builder) void {
    +        self.signatures.deinit(self.allocator);
    +        self.account_keys.deinit(self.allocator);
    +        for (self.instructions.items) |ix| {
    +            self.allocator.free(ix.accounts.items);
    +            self.allocator.free(ix.data.items);
    +        }
    +        self.instructions.deinit(self.allocator);
    +        for (self.alts.items) |alt| {
    +            self.allocator.free(alt.writable_indexes.items);
    +            self.allocator.free(alt.readonly_indexes.items);
    +        }
    +        self.alts.deinit(self.allocator);
    +    }
    +
    +    /// Distinct pubkey for index `i`. Last byte = `i`; the rest are zero.
    +    fn pubkey(i: u8) Pubkey {
    +        var p: Pubkey = Pubkey.ZEROES;
    +        p.data[31] = i;
    +        return p;
    +    }
    +
    +    /// Push `n` signatures (zeroed; content doesn't affect sanitize).
    +    fn pushSigs(self: *Builder, n: usize) !void {
    +        try self.signatures.appendNTimes(self.allocator, Signature.ZEROES, n);
    +    }
    +
    +    /// Push `n` distinct pubkeys.
    +    fn pushKeys(self: *Builder, n: u8) !void {
    +        var i: u8 = 0;
    +        while (i < n) : (i += 1) try self.account_keys.append(self.allocator, pubkey(i));
    +    }
    +
    +    fn pushInstr(self: *Builder, program_id_index: u8, accounts: []const u8) !void {
    +        const accounts_copy = try self.allocator.dupe(u8, accounts);
    +        const data_copy = try self.allocator.alloc(u8, 0);
    +        try self.instructions.append(self.allocator, .{
    +            .program_id_index = program_id_index,
    +            .accounts = .{ .items = accounts_copy },
    +            .data = .{ .items = data_copy },
    +        });
    +    }
    +
    +    fn pushAlt(self: *Builder, writable: []const u8, readonly: []const u8) !void {
    +        const w = try self.allocator.dupe(u8, writable);
    +        const r = try self.allocator.dupe(u8, readonly);

    fb08f9dc65770d7d7c3d677bb68753d0a9620d3f

    yewman yewman commented on code on Jul 06, 2026 07:37 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {
    +        // `header`, `account_keys`, and `instructions` are field-identical
    +        // across both message variants; only ALTs are v0-only.
    +        const header: MessageHeader, //
    +        const account_keys: []const Pubkey, //
    +        const instructions: []const CompiledInstruction //
    +        = switch (self.message) {
    +            inline else => |m| .{ m.header, m.account_keys.items, m.instructions.items },
    +        };
    +        const address_table_lookups: []const AddressLookup = switch (self.message) {
    +            .legacy => &.{},
    +            .v0 => |m| m.address_table_lookups.items,
    +        };
    +
    +        const sig_cnt: usize = self.signatures.items.len;
    +        const acct_cnt: usize = account_keys.len;
    +        const req_sigs: usize = header.num_required_signatures;
    +        const ro_signed: usize = header.num_readonly_signed_accounts;
    +        const ro_unsigned: usize = header.num_readonly_unsigned_accounts;
    +
    +        // (1) signatures.len in [1, MAX_SIGNATURES]
    +        if (sig_cnt < 1 or sig_cnt > MAX_SIGNATURES) return false;
    +
    +        // (2) outer signatures vector length must match the message header.
    +        if (sig_cnt != req_sigs) return false;
    +
    +        // (3) at least one writable signer (the fee payer).
    +        if (ro_signed >= req_sigs) return false;
    +
    +        // (4) account_keys.len in [req_sigs, MAX_ACCOUNT_ADDRESSES].
    +        if (acct_cnt < req_sigs or acct_cnt > MAX_ACCOUNT_ADDRESSES) return false;
    +
    +        // (5) signing + readonly-unsigned regions must fit inside account_keys.
    +        if (req_sigs + ro_unsigned > acct_cnt) return false;
    +
    +        // (6) instruction count bound.
    +        if (instructions.len > MAX_INSTRUCTIONS) return false;
    +
    +        // (7) any instruction needs both a fee payer and a program (which
    +        // can't be the fee payer per check 8), so account_keys must have at
    +        // least 2.
    +        if (instructions.len > 0 and acct_cnt < 2) return false;
    +
    +        // (8) per-instruction: program_id_index is a static account, but
    +        // not the fee payer. Also collect the max account index referenced
    +        // for check 13.
    +        var max_acct_idx: usize = 0;
    +        for (instructions) |ix| {
    +            const pid: usize = ix.program_id_index;
    +            if (pid == 0 or pid >= acct_cnt) return false;
    +            for (ix.accounts.items) |a| {
    +                if (@as(usize, a) > max_acct_idx) max_acct_idx = a;

    fb08f9dc65770d7d7c3d677bb68753d0a9620d3f

    yewman yewman commented on code on Jul 06, 2026 07:37 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }

    fb08f9dc65770d7d7c3d677bb68753d0a9620d3f

    yewman yewman commented on code on Jul 06, 2026 10:06 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -118,10 +341,335 @@ pub const CompiledInstruction = struct {
         program_id_index: u8,
         accounts: bincode.ShortVec(u8),
         data: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: CompiledInstruction) usize {
    +        var n: usize = 1; // program_id_index
    +        n += compactU16Len(self.accounts.items.len) + self.accounts.items.len;
    +        n += compactU16Len(self.data.items.len) + self.data.items.len;
    +        return n;
    +    }
     };
     
     pub const AddressLookup = struct {
         account_key: Pubkey,
         writable_indexes: bincode.ShortVec(u8),
         readonly_indexes: bincode.ShortVec(u8),
    +
    +    pub fn serializedSize(self: AddressLookup) usize {
    +        var n: usize = 32; // account_key (Pubkey)
    +        n += compactU16Len(self.writable_indexes.items.len) + self.writable_indexes.items.len;
    +        n += compactU16Len(self.readonly_indexes.items.len) + self.readonly_indexes.items.len;
    +        return n;
    +    }
     };
    +
    +/// Byte length of the compact-u16 (short-vec) length prefix for `n`.
    +/// Continuation-bit scheme: < 0x80 → 1 byte, < 0x4000 → 2, else 3.
    +fn compactU16Len(n: usize) usize {
    +    if (n < 0x80) return 1;
    +    if (n < 0x4000) return 2;
    +    return 3;
    +}
    +
    +// ---------------------------------------------------------------------------
    +// Tests for `VersionedTransaction.sanitize`.
    +//
    +// Each case maps to one of the 13 numbered invariants in the doc-comment
    +// table on `sanitize`. The shared `Builder` keeps test bodies focused on the
    +// single field they are exercising.
    +// ---------------------------------------------------------------------------
    +
    +const testing = std.testing;
    +
    +/// Test-only helper that builds in-memory `VersionedTransaction` values
    +/// without going through bincode. All slices are backed by the test
    +/// allocator so leaks surface via `testing.allocator`'s assertions.
    +const Builder = struct {
    +    allocator: std.mem.Allocator,
    +    signatures: std.ArrayList(Signature) = .{},
    +    header: MessageHeader = .{
    +        .num_required_signatures = 1,
    +        .num_readonly_signed_accounts = 0,
    +        .num_readonly_unsigned_accounts = 1,
    +    },
    +    account_keys: std.ArrayList(Pubkey) = .{},
    +    instructions: std.ArrayList(CompiledInstruction) = .{},
    +    alts: std.ArrayList(AddressLookup) = .{},
    +    is_v0: bool = false,

    5b125ccef7f0bbdf9de7cee0975953faa4406271

    yewman yewman commented on code on Jul 06, 2026 10:26 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {

    Good call, I like it! 15ece62d0930dc93437ec44f6d2319a7d7b55b3a

    yewman yewman commented on code on Jul 06, 2026 10:29 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.

    If we use std.debug.assert we may as well just have the check and return an error, since it will run in debug and release. This brings back the concept of having a debug assert which is omitted in ReleaseSafe. What are your thoughts?

    InKryption InKryption commented on code on Jul 06, 2026 16:04 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {

    Making it an actual error makes sense, that way can also get the stack trace for it in some contexts; not sure why that didn't occur to me lol.

    InKryption InKryption approved these changes on Jul 06, 2026 18:29 UTC
    Approved Reviewer

    Approved these changes.

    yewman yewman commented on code on Jul 07, 2026 10:28 UTC
    Code Review
    v2/lib/solana/verify_ticks.zig:1
    @@ -0,0 +1,93 @@
    +//! Tick verification for a deshredded slot.
    +//!
    +//! A Solana slot is a tick window: entries must include exactly
    +//! `max_tick_height - tick_height` ticks, the final entry must be a tick once
    +//! the window is full, and inter-tick hash counts must equal
    +//! `hashes_per_tick` (when non-zero).
    +//!
    +//! Lives in `v2/lib/solana/` because the v2 `Entry` uses
    +//! `bincode.Vec(VersionedTransaction)` for the transactions field rather than
    +//! v1's `[]const Transaction`. Once both layouts converge, this module
    +//! should move under `shared/core/`.
    +
    +const lib = @import("../lib.zig");
    +const Entry = lib.solana.transaction.Entry;
    +
    +/// Errors a block may fail with during validation. Not every variant is
    +/// produced by `verifyTicks` — the rest are reserved for higher-layer
    +/// validation (entry-batch hashing, duplicate-slot detection, ...).
    +///
    +/// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/ledger/src/block_error.rs#L3-L39
    +pub const BlockError = error{
    +    Incomplete,
    +    InvalidEntryHash,
    +    InvalidLastTick,
    +    TooFewTicks,
    +    TooManyTicks,
    +    InvalidTickHashCount,
    +    TrailingEntry,
    +    DuplicateBlock,
    +};
    +
    +pub const VerifyTicksParams = struct {
    +    hashes_per_tick: u64,
    +    slot: u64,
    +    max_tick_height: u64,
    +    tick_height: u64,
    +    /// True if the slot's last data shred carried the LAST_SHRED_IN_SLOT flag,
    +    /// i.e. all entries for the slot are present.
    +    slot_is_full: bool,
    +    /// Running hash count carried across batches; pass `0` for a single-batch
    +    /// call.
    +    tick_hash_count: u64 = 0,
    +};
    +
    +/// Count how many entries in `entries` are ticks (zero transactions).
    +pub fn tickCount(entries: []const Entry) u64 {
    +    var n: u64 = 0;
    +    for (entries) |e| {
    +        if (e.isTick()) n += 1;
    +    }
    +    return n;
    +}
    +
    +/// Verify that the supplied entries fit cleanly into the slot's tick window.
    +///
    +/// Returns the first `BlockError` detected, or success.
    +///
    +/// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/ledger/src/blockstore_processor.rs#L1057-L1104
    +pub fn verifyTicks(entries: []const Entry, params: VerifyTicksParams) BlockError!void {
    +    const tick_count_in_entries = tickCount(entries);
    +    const next_tick_height = params.tick_height +| tick_count_in_entries;
    +
    +    if (next_tick_height > params.max_tick_height) {
    +        return error.TooManyTicks;
    +    }
    +
    +    if (next_tick_height < params.max_tick_height and params.slot_is_full) {
    +        return error.TooFewTicks;
    +    }
    +
    +    if (next_tick_height == params.max_tick_height) {
    +        if (entries.len == 0 or !entries[entries.len - 1].isTick()) {
    +            return error.TrailingEntry;
    +        }
    +        if (!params.slot_is_full) return error.InvalidLastTick;
    +    }
    +
    +    // Verify inter-tick hash counts. When `hashes_per_tick == 0`, hashing is
    +    // disabled and any count is acceptable.
    +    //
    +    // [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/entry/src/entry.rs#L675-L698
    +    if (params.hashes_per_tick > 0) {
    +        var hash_count = params.tick_hash_count;
    +        for (entries) |entry| {
    +            hash_count = hash_count +| entry.num_hashes;
    +            if (entry.isTick()) {
    +                if (hash_count != params.hashes_per_tick) return error.InvalidTickHashCount;
    +                hash_count = 0;
    +            }
    +        }
    +        if (hash_count >= params.hashes_per_tick) return error.InvalidTickHashCount;

    Fair, it wasn't required for shred parse harness but likely will be in v2, updated to use mutable u64 as in v1. aac674bc5f0657270a0898ef67a616be2b467815

    yewman yewman commented on code on Jul 07, 2026 10:33 UTC
    Code Review
    v2/lib/solana/transaction.zig:1
    @@ -12,11 +12,200 @@ pub const Entry = struct {
         num_hashes: u64,
         hash: Hash,
         transactions: bincode.Vec(VersionedTransaction),
    +
    +    /// An entry is a "tick" iff it carries no transactions.
    +    pub fn isTick(self: Entry) bool {
    +        return self.transactions.items.len == 0;
    +    }
     };
     
     pub const VersionedTransaction = struct {
         signatures: bincode.ShortVec(Signature),
         message: VersionedMessage,
    +
    +    /// Maximum on-the-wire size of a serialised transaction. Equal to the
    +    /// Solana packet MTU; the network refuses anything larger.
    +    pub const MAX_BYTES: usize = 1232;
    +
    +    /// Inclusive maximum number of signatures per transaction.
    +    pub const MAX_SIGNATURES: usize = 127;
    +
    +    /// Inclusive maximum number of static account addresses per transaction
    +    /// (i.e. excluding ALT-loaded addresses). Matches the bank's
    +    /// `MAX_TX_ACCOUNT_LOCKS`.
    +    pub const MAX_ACCOUNT_ADDRESSES: usize = 128;
    +
    +    /// Inclusive maximum number of top-level instructions per transaction.
    +    pub const MAX_INSTRUCTIONS: usize = 64;
    +
    +    /// Total bincode-serialised size in bytes (signatures + message).
    +    ///
    +    /// Computed analytically (compact-u16 length prefixes + fixed-size
    +    /// fields + variable-size payloads) rather than by round-tripping the
    +    /// structure through `bincode.write`. This also sidesteps the latent
    +    /// `VersionedMessage.bincodeWrite` path (a `switch (self)` over a
    +    /// pointer rather than the tag) which has never been exercised.
    +    pub fn serializedSize(self: VersionedTransaction) usize {
    +        var n: usize = 0;
    +        n += compactU16Len(self.signatures.items.len);
    +        n += 64 * self.signatures.items.len;
    +        n += self.message.serializedSize();
    +        return n;
    +    }
    +
    +    /// Returns `true` iff the message's static `account_keys` are pairwise
    +    /// distinct. Solana rejects transactions whose visible accounts contain
    +    /// a duplicate (`AccountLoadedTwice`).
    +    ///
    +    /// Only the keys carried directly in the message are checked here;
    +    /// entries resolved from address-lookup tables are invisible without
    +    /// ALUT resolution and must be re-checked once those are loaded.
    +    ///
    +    /// O(n^2); `account_keys.len ≤ 128` by transaction MTU.
    +    ///
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/accounts-db/src/account_locks.rs#L143-L155
    +    pub fn validateAccountLocks(self: VersionedTransaction) bool {
    +        const keys = switch (self.message) {
    +            .legacy => |m| m.account_keys.items,
    +            .v0 => |m| m.account_keys.items,
    +        };
    +        var i: usize = 0;
    +        while (i < keys.len) : (i += 1) {
    +            var j: usize = i + 1;
    +            while (j < keys.len) : (j += 1) {
    +                if (std.mem.eql(u8, &keys[i].data, &keys[j].data)) return false;
    +            }
    +        }
    +        return true;
    +    }
    +
    +    /// Returns `true` iff the message and signature vector are well-formed
    +    /// at the parse layer.
    +    ///
    +    /// Each invariant below is a structural constraint of the Solana wire
    +    /// format: violating it means the bytes can't represent a transaction
    +    /// the runtime would ever accept — the signature count disagrees with
    +    /// the header, an instruction's program index points at the fee payer
    +    /// or off the end of the account vector, ALT bookkeeping overflows
    +    /// the static caps, etc. Rejecting these here prevents malformed
    +    /// transactions from reaching account-locking or message resolution
    +    /// and keeps later stages from having to defend against shapes the
    +    /// protocol forbids.
    +    ///
    +    /// Two related checks are intentionally not part of this method:
    +    ///
    +    ///   * MTU (`serializedSize ≤ MAX_BYTES`). Owned by the caller and
    +    ///     usually enforced at the packet boundary; doing it again here
    +    ///     would just be defensive.
    +    ///   * Duplicate static account keys. Owned by `validateAccountLocks`;
    +    ///     the protocol treats `AccountLoadedTwice` as an account-locking
    +    ///     concern, not a parse error.
    +    ///
    +    /// Invariants enforced (numbered for cross-reference with the inline
    +    /// comments and the tests below):
    +    ///
    +    /// | #  | Invariant |
    +    /// |----|-----------|
    +    /// |  1 | `1 ≤ signatures.len ≤ MAX_SIGNATURES` |
    +    /// |  2 | `signatures.len == header.num_required_signatures` |
    +    /// |  3 | `header.num_readonly_signed < header.num_required_signatures` (the fee payer is writable) |
    +    /// |  4 | `header.num_required_signatures ≤ account_keys.len ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// |  5 | `num_required_signatures + num_readonly_unsigned ≤ account_keys.len` |
    +    /// |  6 | `instructions.len ≤ MAX_INSTRUCTIONS` |
    +    /// |  7 | `instructions.len > 0  ⇒  account_keys.len ≥ 2` |
    +    /// |  8 | per instruction: `0 < program_id_index < account_keys.len` |
    +    /// |  9 | `address_table_lookups.len ≤ V0Message.MAX_ADDR_TABLE_LOOKUPS` (v0 only) |
    +    /// | 10 | per ALT: `writable_indexes.len + readonly_indexes.len ≥ 1` |
    +    /// | 11 | per ALT: each of `writable_indexes.len`, `readonly_indexes.len ≤ MAX_ACCOUNT_ADDRESSES - account_keys.len` |
    +    /// | 12 | `account_keys.len + Σ ALT-loaded ≤ MAX_ACCOUNT_ADDRESSES` |
    +    /// | 13 | max account index used by any instruction `< account_keys.len + Σ ALT-loaded` |
    +    ///
    +    /// [firedancer] https://github.com/firedancer-io/firedancer/blob/main/src/ballet/txn/fd_txn_parse.c
    +    /// [agave] https://github.com/anza-xyz/agave/blob/v4.1.0-rc.1/transaction-view/src/sanitize.rs
    +    pub fn sanitize(self: VersionedTransaction) bool {
    +        // `header`, `account_keys`, and `instructions` are field-identical
    +        // across both message variants; only ALTs are v0-only.
    +        const header: MessageHeader, //
    +        const account_keys: []const Pubkey, //
    +        const instructions: []const CompiledInstruction //
    +        = switch (self.message) {
    +            inline else => |m| .{ m.header, m.account_keys.items, m.instructions.items },
    +        };
    +        const address_table_lookups: []const AddressLookup = switch (self.message) {
    +            .legacy => &.{},
    +            .v0 => |m| m.address_table_lookups.items,
    +        };
    +
    +        const sig_cnt: usize = self.signatures.items.len;
    +        const acct_cnt: usize = account_keys.len;
    +        const req_sigs: usize = header.num_required_signatures;
    +        const ro_signed: usize = header.num_readonly_signed_accounts;
    +        const ro_unsigned: usize = header.num_readonly_unsigned_accounts;
    +
    +        // (1) signatures.len in [1, MAX_SIGNATURES]
    +        if (sig_cnt < 1 or sig_cnt > MAX_SIGNATURES) return false;
    +
    +        // (2) outer signatures vector length must match the message header.
    +        if (sig_cnt != req_sigs) return false;
    +
    +        // (3) at least one writable signer (the fee payer).
    +        if (ro_signed >= req_sigs) return false;
    +
    +        // (4) account_keys.len in [req_sigs, MAX_ACCOUNT_ADDRESSES].
    +        if (acct_cnt < req_sigs or acct_cnt > MAX_ACCOUNT_ADDRESSES) return false;
    +
    +        // (5) signing + readonly-unsigned regions must fit inside account_keys.
    +        if (req_sigs + ro_unsigned > acct_cnt) return false;
    +
    +        // (6) instruction count bound.
    +        if (instructions.len > MAX_INSTRUCTIONS) return false;
    +
    +        // (7) any instruction needs both a fee payer and a program (which
    +        // can't be the fee payer per check 8), so account_keys must have at
    +        // least 2.
    +        if (instructions.len > 0 and acct_cnt < 2) return false;
    +
    +        // (8) per-instruction: program_id_index is a static account, but
    +        // not the fee payer. Also collect the max account index referenced
    +        // for check 13.
    +        var max_acct_idx: usize = 0;
    +        for (instructions) |ix| {
    +            const pid: usize = ix.program_id_index;
    +            if (pid == 0 or pid >= acct_cnt) return false;
    +            for (ix.accounts.items) |a| {
    +                if (@as(usize, a) > max_acct_idx) max_acct_idx = a;
    +            }
    +        }

    Here is the parse update we discussed. Lmk your thoughts c69859d7d95f38f2d5e0e029f9f6d4d2c503710a

    Reviewers
    Assignees
    yewman yewman
    Labels
    risk: low confidence: 70.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 47.4% (MEDIUM) · Higher = larger blast radius
    47.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 70.2% · Lower = rushed or shallow review
    70.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.1% · Safe to merge
    14.1%
    Repository