Skip to content

writeInt incorrectly encodes numeric -1 for 1-bit integers #75

@Gusarich

Description

@Gusarich

BitBuilder.writeInt dangerously misencodes the numeric value -1 (JavaScript number) for 1-bit integers, resulting in silently corrupted serialized data. Instead of encoding -1 correctly as bit 1, it encodes it incorrectly as bit 0, causing runtime deserialization failures and severe data corruption.

Minimal Reproduction:

import { beginCell } from '@ton/core';

// Store numeric -1 in a single-bit integer (number, not BigInt)
const cell = beginCell().storeInt(-1, 1).endCell();
const slice = cell.beginParse();

console.log(slice.loadInt(1)); // Outputs: 0 (INCORRECT! Should be -1)

Cause:
The special-case logic for single-bit integers compares the original input directly to BigInt (-1n) without normalizing the numeric input (number), leading to incorrect encoding:

// Current broken logic:
this.writeBit(value === -1n); // fails when value = -1 (number)

Impact:

  • Silent corruption: Negative values stored as number are incorrectly serialized.
  • Severe consequences: Deserialization returns incorrect values, causing potential logic errors, invalid contract states, incorrect transfers, and financial loss.

Expected behavior:
Encoding numeric -1 as a single-bit integer (storeInt(-1, 1)) MUST produce a correct bit (1) identical to BigInt -1n.


LLM Fuzzing discovery (see tact-lang/tact#3123)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions