hldb / welo

peer-to-peer, collaborative states using Merkle-CRDTs
Other
32 stars 2 forks source link

bug: bloom filter stack overflow #113

Closed saul-jb closed 6 months ago

saul-jb commented 6 months ago

The bloom filter's getDistinctIndexes with some inputs can cause a stack overflow.

The following inputs are known to cause it:

getDistinctIndexes(
  new Uint8Array([0x01, 0x71, 0x12, 0x20, 0x9c, 0x4e, 0x9b, 0x9f, 0x68, 0x6b, 0xeb, 0xd1, 0xf2, 0x2b, 0x65, 0x1f, 0x0a, 0x72, 0xf8, 0xb3, 0x14, 0xb7, 0xd1, 0x13, 0xb0, 0x58, 0xa6, 0x72, 0xf2, 0x09, 0x42, 0xe0, 0x04, 0x19, 0xcb, 0x80]),
  5,
  4,
  2000679582
)

The upstream seems to have a more reliable implementation:

function getDistinctIndices(element, size, number, seed) {
  let n = 0
  const indexes = new Set()
  let hashes = hashTwice(element, true, seed)

  while (indexes.size < number) {
    const ind = hashes.first % size

    if (!indexes.has(ind)) {
      indexes.add(ind)
    }

    hashes.first = (hashes.first + hashes.second) % size
    hashes.second = (hashes.second + n) % size
    n++

    if (n > size) {
      seed++
      hashes = hashTwice(element, true, seed)
    }
  }

  return [...indexes.values()]
}