ssz icon indicating copy to clipboard operation
ssz copied to clipboard

BitArray.get accepts out-of-range bitIndex while set rejects it

Open kutluhaneth46 opened this issue 2 days ago • 0 comments

Describe the bug

BitArray.set rejects bitIndex >= bitLen, but BitArray.get does not. An out-of-range get reads past the backing Uint8Array and returns false instead of throwing.

On current master (@chainsafe/ssz):

import {BitArray} from "@chainsafe/ssz";

const bits = BitArray.fromBitLen(8);
bits.get(0);   // false
bits.get(8);   // false  (out of range, silently wrong)
bits.get(100); // false  (out of range, silently wrong)
bits.set(8, true); // throws: BitArray set bitIndex 8 beyond bitLen 8

Expected behavior

get should reject out-of-range indexes the same way set does, for example:

BitArray get bitIndex 8 beyond bitLen 8

Actual behavior

get returns false for any index at or beyond bitLen (and for negative indexes), because uint8Array[byteIdx] is undefined and (undefined & mask) === mask is false.

Root cause

get(bitIndex: number): boolean {
  const byteIdx = Math.floor(bitIndex / 8);
  const bitInBit = bitIndex % 8;
  const mask = 1 << bitInBit;
  return (this.uint8Array[byteIdx] & mask) === mask;
}

set(bitIndex: number, bit: boolean): void {
  if (bitIndex >= this.bitLen) {
    throw Error(`BitArray set bitIndex ${bitIndex} beyond bitLen ${this.bitLen}`);
  }
  // ...
}

Version

@chainsafe/ssz on ChainSafe/ssz master (BitArray in packages/ssz/src/value/bitArray.ts).

kutluhaneth46 avatar Nov 30 '26 13:11 kutluhaneth46