Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/bytes/bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ export class Bytes {
}
this.bytes = hexToUint8Array(bytes)
} else if (bytes instanceof ArrayBuffer) {
this.bytes = new Uint8Array(bytes)
this.bytes = new Uint8Array(bytes.slice(0))
} else if (bytes instanceof Uint8Array) {
this.bytes = bytes
this.bytes = bytes.slice()
} else {
const unknownInput = bytes as unknown
if (hasToHexMethod(unknownInput)) {
Expand Down
16 changes: 11 additions & 5 deletions src/bytes/encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export function commonPrefix(one: Uint8Array, other: Uint8Array): Uint8Array {
* contiguous subsequence of `bytes`, or -1 if it doesn't occur.
*/
export function indexOf(bytes: Uint8Array, value: Uint8Array, start = 0): number {
if (value.length === 0) {
return Math.min(start, bytes.length)
}
for (let i = start; i < bytes.length; i++) {
for (let j = 0; j < value.length; j++) {
if (bytes[i + j] !== value[j]) {
Expand Down Expand Up @@ -108,6 +111,9 @@ export function uint256ToNumber(bytes: Uint8Array, endian: 'LE' | 'BE'): bigint
*/
export function hexToUint8Array(hex: string): Uint8Array {
const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex
if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) {
throw new Error(`hexToUint8Array: invalid hex string: ${hex}`)
}
const result = new Uint8Array(clean.length / 2)
for (let i = 0; i < result.length; i++) {
result[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16)
Expand Down Expand Up @@ -143,7 +149,7 @@ function baseToUint8Array(baseString: string, baseChars: string): Uint8Array {
return new Uint8Array(array)
}

function uint8ArrayToBase(bytes: Uint8Array, baseChars: string): string {
function uint8ArrayToBase(bytes: Uint8Array, baseChars: string, paddingBlock: number): string {
const base = baseChars.length
let bits = 0
let value = 0
Expand All @@ -159,8 +165,8 @@ function uint8ArrayToBase(bytes: Uint8Array, baseChars: string): string {
if (bits > 0) {
result += baseChars.charAt((value << (Math.log2(base) - bits)) & (base - 1))
}
if (result.length % 4 !== 0) {
result += '='.repeat(4 - (result.length % 4))
if (result.length % paddingBlock !== 0) {
result += '='.repeat(paddingBlock - (result.length % paddingBlock))
}
return result
}
Expand All @@ -176,7 +182,7 @@ export function base64ToUint8Array(base64: string): Uint8Array {
* Encodes bytes as a padded base64 string.
*/
export function uint8ArrayToBase64(bytes: Uint8Array): string {
return uint8ArrayToBase(bytes, BASE64_CHARS)
return uint8ArrayToBase(bytes, BASE64_CHARS, 4)
}

/**
Expand All @@ -190,7 +196,7 @@ export function base32ToUint8Array(base32: string): Uint8Array {
* Encodes bytes as a padded base32 string.
*/
export function uint8ArrayToBase32(bytes: Uint8Array): string {
return uint8ArrayToBase(bytes, BASE32_CHARS)
return uint8ArrayToBase(bytes, BASE32_CHARS, 8)
}

/**
Expand Down
4 changes: 4 additions & 0 deletions src/bytes/reference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export class Reference extends Bytes {
* Encodes the reference as a `"bah5..."` CID string of the given type.
*/
toCid(type: 'feed' | 'manifest'): string {
if (this.length !== Reference.LENGTH) {
throw new Error(`Reference#toCid: only 32-byte references can be encoded as a CID, got ${this.length} bytes`)
}

const header = Bytes.concat(
new Uint8Array([1]), // version
new Uint8Array([type === 'feed' ? SWARM_FEED_CODEC : SWARM_MANIFEST_CODEC]),
Expand Down
19 changes: 2 additions & 17 deletions src/chunk/joiner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,6 @@ import { decryptChunk } from '../encryption/stream-cipher.js'
import { decodeRedundancyLevel, referenceCount } from '../erasure-coding/span.js'
import { Bytes } from '../bytes/bytes.js'

function isAllZero(bytes: Uint8Array): boolean {
for (let i = 0; i < bytes.length; i++) {
if (bytes[i] !== 0) return false
}

return true
}

/**
* Reconstructs the original data behind a chunk tree (as produced by
* ChunkSplitter), fetching chunks on demand via a caller-supplied callback.
Expand Down Expand Up @@ -88,18 +80,11 @@ export class ChunkJoiner {
return
}

const maxRefs = Math.floor(4096 / this.refSize)
// Without redundancy there's no way to tell real children from padding
// apart from the all-zero terminator. With redundancy, the data/parity
// split is computed from the span instead - parity refs are appended
// right after the data refs with no marker of their own, and must be
// skipped rather than descended into.
const dataRefCount = level > 0 ? referenceCount(span, level, this.encrypted).dataShardCount : maxRefs
const { dataShardCount } = referenceCount(span, level, this.encrypted)

for (let i = 0; i < Math.min(dataRefCount, maxRefs); i++) {
for (let i = 0; i < dataShardCount; i++) {
const ref = data.subarray(i * this.refSize, (i + 1) * this.refSize)
const childAddress = ref.subarray(0, 32)
if (level === 0 && isAllZero(childAddress)) break
await this.join(childAddress, this.encrypted ? ref.subarray(32, 64) : undefined)
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/encryption/xor-cipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
* obfuscation key.
*/
export function xorCypher(bytes: Uint8Array, key: Uint8Array): Uint8Array {
if (key.length === 0) {
throw new Error('xorCypher: key must not be empty')
}
const result = new Uint8Array(bytes.length)
for (let i = 0; i < bytes.length; i++) {
result[i] = bytes[i]! ^ key[i % key.length]!
Expand Down
1 change: 1 addition & 0 deletions src/erasure-coding/reed-solomon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ function getParityRows(dataShards: number, parityShards: number): number[][] {
* the same scheme real Bee nodes use, so this interoperates with them.
*/
export function rsEncode(data: Uint8Array[], parityCount: number): Uint8Array[] {
if (data.length === 0) throw new Error('rsEncode: expected at least one data shard')
if (parityCount === 0) return []
const dataCount = data.length
const shardSize = data[0]!.length
Expand Down
8 changes: 7 additions & 1 deletion src/stamper/stamper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { PrivateKey } from '../bytes/private-key.js'
import { EnvelopeWithBatchId } from './marshal.js'
import { Bytes } from '../bytes/bytes.js'

const BUCKET_DEPTH = 16

/**
* Signs a single chunk address into a postage stamp envelope.
*
Expand Down Expand Up @@ -48,11 +50,15 @@ export class Stamper {
maxSlot: number

private constructor(signer: PrivateKey, batchId: BatchId, buckets: Uint32Array, depth: number) {
if (!Number.isInteger(depth) || depth <= BUCKET_DEPTH) {
throw new Error(`Stamper#constructor depth must be an integer above ${BUCKET_DEPTH}, got ${depth}`)
}

this.signer = signer
this.batchId = batchId
this.buckets = buckets
this.depth = depth
this.maxSlot = 2 ** (depth - 16)
this.maxSlot = 2 ** (depth - BUCKET_DEPTH)
}

/**
Expand Down
64 changes: 64 additions & 0 deletions test/regression/joiner-encrypted-bee-padding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { describe, expect, it } from 'vitest'
import { Bytes } from '../../src/bytes/bytes.js'
import { numberToUint64, uint8ArrayToHex } from '../../src/bytes/encoding.js'
import { calculateChunkAddress } from '../../src/chunk/bmt.js'
import { ChunkJoiner } from '../../src/chunk/joiner.js'
import { ChunkBuilder, ChunkEntry, ChunkSplitter } from '../../src/chunk/splitter.js'
import { encryptData, encryptSpan } from '../../src/encryption/stream-cipher.js'

const REF_SIZE = 64

function makeStorage() {
const store = new Map<string, Uint8Array>()

const put = (address: Uint8Array, data: Uint8Array) => store.set(uint8ArrayToHex(address), data)

async function onBatch(entries: ChunkEntry[]): Promise<ChunkEntry[]> {
for (const { chunk, key } of entries) {
const { address } = chunk.encryptedHash(key)
put(address.toUint8Array(), encryptLikeBee(chunk, key!, chunk.writer.buffer))
}

return []
}

async function fetch(address: Uint8Array): Promise<Uint8Array> {
const data = store.get(uint8ArrayToHex(address))
if (!data) throw new Error(`not found: ${uint8ArrayToHex(address)}`)

return data
}

return { put, onBatch, fetch }
}

function encryptLikeBee(chunk: ChunkBuilder, key: Uint8Array, plaintext: Uint8Array): Uint8Array {
const padding = crypto.getRandomValues(new Uint8Array(4096 - plaintext.length))

return Bytes.concat(encryptSpan(key, numberToUint64(chunk.span, 'LE')), encryptData(key, plaintext), padding)
}

async function beeStyleEncryptedTree(data: Uint8Array) {
const storage = makeStorage()
const splitter = new ChunkSplitter(storage.onBatch, undefined, true)
await splitter.append(data)
const root = await splitter.finalize()

const childCount = Math.ceil(data.length / 4096)
const refs = root.writer.buffer.subarray(0, childCount * REF_SIZE)
const key = crypto.getRandomValues(new Uint8Array(32))
const rootChunk = encryptLikeBee(root, key, refs)
const address = calculateChunkAddress(rootChunk).toUint8Array()
storage.put(address, rootChunk)

return { address, key, fetch: storage.fetch }
}

describe('joining an encrypted tree whose intermediate chunks Bee padded with random bytes', () => {
it.each([4097, 4096 * 2, 4096 * 5 + 777])('reads back %i bytes', async length => {
const data = Uint8Array.from({ length }, (_, i) => (i * 7 + 3) & 0xff)
const { address, key, fetch } = await beeStyleEncryptedTree(data)

expect(await ChunkJoiner.collectEncrypted(address, key, fetch)).toEqual(data)
})
})
Loading
Loading