File size: 1,084 Bytes
b855ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Length padding (Cryptography and Transport, "Padding"). Every text frame on
// the gateway and on federation sockets is padded to its Padmé bucket, so
// frame sizes reveal only O(log log L) bits of the real length.

export const MIN_PADDED = 256;

// Padmé (Nikitin et al., PETS 2019), with a 256-byte minimum.
export function padme(length) {
  const L = Math.max(length, MIN_PADDED);
  const E = Math.floor(Math.log2(L));
  const S = Math.floor(Math.log2(E)) + 1;
  const unit = 2 ** (E - S);
  return Math.ceil(L / unit) * unit;
}

// Serialize a frame with a top-level `pad` property of ASCII filler, so its
// UTF-8 length is exactly padme(length). Receivers ignore `pad`.
export function paddedJson(frame) {
  const bytes = Buffer.byteLength(JSON.stringify({ ...frame, pad: '' }));
  return JSON.stringify({ ...frame, pad: '0'.repeat(padme(bytes) - bytes) });
}

// Pad a binary chunk with zeros to exactly `size` bytes.
export function padChunk(chunk, size) {
  if (chunk.length === size) return chunk;
  const out = Buffer.alloc(size);
  chunk.copy(out);
  return out;
}