# Hash-prefix candidates: count is not probability

This executable companion to [Hash Challenges](https://hesela.dev/terms/hash-challenges/)
is a synthetic mathematical illustration, not a protocol implementation, benchmark,
cryptanalysis or reproduction of the 2012 paper.

## One absent query

Assume M distinct unrelated receiver chunks, one absent query and independent
uniform b-bit prefixes. Let X count stored prefixes equal to the query prefix.

- E[X] = M / 2^b by summing M indicator expectations.
- P(X >= 1) = 1 - (1 - 2^-b)^M by taking the complement of no matches.
- The count can exceed one. A probability cannot.
- Independence is required for the product, not for summing expectations when
  each match has the stated marginal probability.
- Repeated entries for identical bytes do not create independent digests.
- An already-present query needs its true match accounted for separately.
- No all-pairs birthday event, full-digest collision rate or data-loss rate is computed.

For M=3 and b=2, enumerating all 4^3=64 receiver-prefix assignments gives
48 candidate occurrences and 37 assignments with at least one candidate.
Hence E[X]=48/64=3/4 while P(X>=1)=37/64. These fractions are exact.
The model also reports floating-point examples for one million receiver chunks.
They are calculated scenarios, not measured populations. No sampling confidence
interval applies. The stable evaluation uses log1p and expm1.

## Candidate confirmation

The manufactured strings 12abcdee and 12abcdef share their first byte.
Only the latter matches query 12abcdef in full. The example rejects the former
after full comparison. These are invented digest strings, not hashes of files.
Full-digest equality itself does not prove byte equality or possession.

The example omits protocol framing, chunk indexes, offsets, candidate caps,
network latency, hash computation, chunk boundaries and adversarial behavior.
Do not infer transfer-time savings from its candidate counts.

## Directional traffic budget

**The width that minimizes total bytes need not minimize service cost on a slow
upload link.** The worked scenario below minimizes total bytes at a four-byte
prefix, but minimizes ideal serialized link service at three bytes, among
the eight widths evaluated. These are different objectives.

The protocol's phase-ii responses carry a digest suffix and a query index.
Phase iii sends an offset for every candidate, including a rejection value for
a false candidate. That last field consumes sender-to-receiver bandwidth too.
This accounting follows section 2 and Appendix A of the
[original paper](https://doi.org/10.1016/j.ipl.2012.01.012); it should not be
dropped when assessing an asymmetric link.

### Explicit inventory and wire convention

The executable [traffic.mjs](./traffic.mjs) makes these choices:

- Q fixed-length chunks are queried against M canonical distinct stored chunks.
- A query is already stored with probability r, with exactly one true match.
- Unrelated full digests are uniform without replacement over all values except the query digest.
- Full-digest collisions are excluded by construction, not proved impossible for a real hash.
- A full digest occupies N bytes, a query index I bytes and an offset O bytes.
- Every candidate gets a suffix-plus-index response and an offset-or-rejection reply.
- Each absent chunk contributes L payload bytes, without deduplication within the transfer.
- Prefixes occupy whole bytes and are shorter than the full digest.
- Transport/TLS headers, framing, compression, caps, retries, CPU and round-trip latency are omitted.

The index must represent Q positions. The offset must represent every chunk's
start position while reserving an all-ones rejection value. The input checker
rejects fields that cannot do so.

The true match occupies a slot in M. Therefore, conditioning on presence and
absence gives the expected number of unrelated prefix matches:

```text
p = (2^(8*(N-k)) - 1) / (2^(8*N) - 1)
F = Q * [(1-r)*M + r*(M-1)] * p
  = Q * (M-r) * p
C = Q*r + F
```

Here p excludes the query's full digest from both numerator and denominator.
For a two-byte full digest and one-byte prefix, p=255/65535, not 1/256.
For the 32-byte worked scenario, the correction is below displayed precision.
An inventory that cannot fit the collision-free digest space is rejected.
This finite-space model is distinct from the earlier unconstrained prefix example.

This is an expectation under the stated digest model, not a realized count.
The paper uses the conservative M term for unrelated candidates; the M-r
adjustment here belongs to the explicitly deduplicated, one-true-match inventory.
Full-digest collisions are excluded. Correlation between queries does not affect
this linear expectation, but the model supplies no variance or tail estimate.

The ledger is then:

| Component | Direction | Expected bytes |
| --- | --- | ---: |
| Initial prefixes | Sender to receiver | Q*k |
| Candidate suffixes and indexes | Receiver to sender | C*(N-k+I) |
| Copy offsets and rejections | Sender to receiver | C*O |
| Missing chunk payload | Sender to receiver | Q*(1-r)*L |

A count of false matches cannot be replaced with the probability of at least
one match: every returned candidate generates fields. This implementation
also does not impose a candidate cap or stop at the first true match.

### Worked scenario

Inputs are chosen, not fitted: Q=100,000, M=1,000,000, r=0.8, L=1024 B,
N=32 B, I=4 B and O=8 B. Forward and reverse capacities are respectively
125,000 and 12,500,000 bytes/s (1 and 100 Mbit/s).
MB below means 1,000,000 bytes; figures are rounded from
[traffic-results.json](./traffic-results.json).

| Prefix bytes | Expected candidates | Forward metadata MB | Reverse metadata MB | Total with payload MB | Serialized service s |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 2 | 1,605,877.69 | 13.047 | 54.600 | 88.127 | 272.584 |
| 3 | 85,960.46 | 0.988 | 2.837 | 24.304 | 171.968 |
| 4 | 80,023.28 | 1.040 | 2.561 | 24.081 | 172.366 |
| 5 | 80,000.09 | 1.140 | 2.480 | 24.100 | 173.158 |

The two-byte prefix alone costs 0.2 MB, yet its forward metadata reaches
13.047 MB once offsets are counted. For context, the complete 32-byte digest
list alone is 3.2 MB. That list is **not** a complete compare-by-hash session,
so this comparison is not a claim about overall protocol speedup.

Among widths 1 through 8, four bytes minimize total traffic, while three bytes
minimize the weighted service sum. At four bytes, the modest reverse-traffic
reduction does not compensate for extra bytes on the slower forward link.

The service column is forward bytes divided by forward capacity plus reverse
bytes divided by reverse capacity. It assumes serialization without overlap.
It is not an estimate of measured completion time: scheduling, pipelining,
latency, congestion and local processing can change the result. No sampling
confidence interval applies to these deterministic scenario calculations.

### Checks and use

[traffic.test.mjs](./traffic.test.mjs) independently enumerates all 65,535
nonquery two-byte digests, once with an absent query and once with a true match
also present. It constructs outgoing and returning message bytes, then
compares their mean lengths with the analytical ledger. Further tests cover
rejection costs, true-match accounting, malformed inputs, field capacity and
rate changes.

Use the ledger to make a traffic hypothesis explicit, then measure the actual
protocol and workload before choosing an operating prefix width. A different
wire format, inventory, redundancy rate or objective can change the choice.

## Reproduce

Use Node.js 22 or later, with no third-party dependencies. Keep these files together:

- [model.mjs](./model.mjs)
- [model.test.mjs](./model.test.mjs)
- [results.json](./results.json)
- [sources.json](./sources.json)
- [traffic.mjs](./traffic.mjs)
- [traffic.test.mjs](./traffic.test.mjs)
- [traffic-results.json](./traffic-results.json)

Run:

```sh
node model.mjs
node traffic.mjs
node --test model.test.mjs
```

The tests independently enumerate prefix spaces, check empty inventories and
small probabilities, reject malformed inputs and exercise prefix false matches.
The site's publication tests compare generated JSON and built exports.

## Evidence and licensing

The source review is identified in sources.json. The paper is linked, not
redistributed. NIST documents hash security properties and SHA-1's transition.
Hesela's illustrative code and explanation are original; this directory grants
no license to third-party papers or software. See the site's reuse policy.
