Skip to content

knotkit/cas

Addresses wire-envelope artifacts by content hash and stores them through an injected backend

import {
function contentAddressedStore(options: ContentAddressedStoreOptions): ContentAddressedStore

Create a store that names each artifact by the hash of its framed bytes.

Content addressing gives three properties a plain blob key cannot. Writing the same artifact twice stores one copy, because identical bytes produce one address. Reading an address cannot return different content later without failing, because the bytes are re-hashed before decoding. And an address is portable across processes and machines that share the hash function, which is why the hash is injected rather than chosen here.

A hash collision — two artifacts, one address — is detected rather than served: add compares the stored bytes with the ones it was about to write, and reports ADDRESS_COLLISION instead of returning an address whose content is the other artifact. That check costs one read on the duplicate path, which is the price of not depending on the hash being collision-free.

@param ― options - The backend, the hash, and the artifact family's magic.

@returns ― A store whose every failure carries a code from CAS_ERROR_CODES.

@throws ― {CasInvalidInputError} With INVALID_ARTIFACT when options.magic is not four bytes, since no artifact of this family could ever be valid.

contentAddressedStore
} from 'knotkit/cas'
import {
function xxh64(seed?: bigint): ScalarHash<"xxh64", bigint, bigint>

Create an XXH64 factory with an unsigned 64-bit seed.

XXH64 is non-cryptographic and is unsuitable for passwords, signatures, MACs, secret-derived identifiers, or hostile-input collision resistance.

xxh64
} from 'knotkit/hash'
const
const blobs: Map<string, Uint8Array<ArrayBufferLike>>
blobs
= new
var Map: MapConstructor
new <string, Uint8Array<ArrayBufferLike>>(iterable?: Iterable<readonly [string, Uint8Array<ArrayBufferLike>]> | null | undefined) => Map<string, Uint8Array<ArrayBufferLike>> (+3 overloads)
Map
<string,
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
>()
const
const hasher: ScalarHash<"xxh64", bigint, bigint>
hasher
=
function xxh64(seed?: bigint): ScalarHash<"xxh64", bigint, bigint>

Create an XXH64 factory with an unsigned 64-bit seed.

XXH64 is non-cryptographic and is unsuitable for passwords, signatures, MACs, secret-derived identifiers, or hostile-input collision resistance.

xxh64
()
const
const store: ContentAddressedStore
store
=
function contentAddressedStore(options: ContentAddressedStoreOptions): ContentAddressedStore

Create a store that names each artifact by the hash of its framed bytes.

Content addressing gives three properties a plain blob key cannot. Writing the same artifact twice stores one copy, because identical bytes produce one address. Reading an address cannot return different content later without failing, because the bytes are re-hashed before decoding. And an address is portable across processes and machines that share the hash function, which is why the hash is injected rather than chosen here.

A hash collision — two artifacts, one address — is detected rather than served: add compares the stored bytes with the ones it was about to write, and reports ADDRESS_COLLISION instead of returning an address whose content is the other artifact. That check costs one read on the duplicate path, which is the price of not depending on the hash being collision-free.

@param ― options - The backend, the hash, and the artifact family's magic.

@returns ― A store whose every failure carries a code from CAS_ERROR_CODES.

@throws ― {CasInvalidInputError} With INVALID_ARTIFACT when options.magic is not four bytes, since no artifact of this family could ever be valid.

contentAddressedStore
({
// Any object with has/get/set works: a Map, S3 client, or fetch-backed store.
ContentAddressedStoreOptions.backend: ArtifactBackend

Where bytes are stored and read. The store never assumes it is local.

backend
: {
ArtifactBackend.has: (address: string) => Promise<boolean>

Whether address is present. O(1) expected for a map-backed backend.

has
: async (
address: string
address
) =>
const blobs: Map<string, Uint8Array<ArrayBufferLike>>
blobs
.
Map<string, Uint8Array<ArrayBufferLike>>.has(key: string): boolean

@returns ― boolean indicating whether an element with the specified key exists or not.

has
(
address: string
address
),
ArtifactBackend.get: (address: string) => Promise<Uint8Array | undefined>

Return the bytes stored under address, or undefined when the address is absent.

get
: async (
address: string
address
) =>
const blobs: Map<string, Uint8Array<ArrayBufferLike>>
blobs
.
Map<string, Uint8Array<ArrayBufferLike>>.get(key: string): Uint8Array<ArrayBufferLike> | undefined

Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.

@returns ― Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.

get
(
address: string
address
),
ArtifactBackend.set: (address: string, bytes: Uint8Array) => Promise<void>

Store bytes under address, replacing whatever was there.

Content addressing makes a rewrite idempotent when the hash is deterministic, so a backend need not be idempotent itself: the store writes an address only when it read nothing back, or read back different bytes that it has already reported as a failure.

set
: async (
address: string
address
,
bytes: Uint8Array<ArrayBufferLike>
bytes
) => void
const blobs: Map<string, Uint8Array<ArrayBufferLike>>
blobs
.
Map<string, Uint8Array<ArrayBufferLike>>.set(key: string, value: Uint8Array<ArrayBufferLike>): Map<string, Uint8Array<ArrayBufferLike>>

Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.

set
(
address: string
address
,
bytes: Uint8Array<ArrayBufferLike>
bytes
),
},
// Injected, so the address can be reproduced by every reader that shares it.
ContentAddressedStoreOptions.hash: (bytes: Uint8Array) => string

Content hash from framed bytes to address. Injected, so a caller chooses the algorithm and its width, and so a test can use a hash that cannot collide.

It must be deterministic — two calls on equal bytes return one string — and collision-resistant enough for the store's expected population. A 64-bit non-cryptographic hash is adequate below roughly 2^32 artifacts; above that, or against an adversary choosing the inputs, use SHA-256. A collision is not silent: see

ContentAddressedStore.add

.

hash
: (
bytes: Uint8Array<ArrayBufferLike>
bytes
) =>
const hasher: ScalarHash<"xxh64", bigint, bigint>
hasher
.
ScalarHash<"xxh64", bigint, bigint>.encodeHex(output: bigint): string
encodeHex
(
const hasher: ScalarHash<"xxh64", bigint, bigint>
hasher
.
ScalarHash<"xxh64", bigint, bigint>.bytes(input: Uint8Array): bigint
bytes
(
bytes: Uint8Array<ArrayBufferLike>
bytes
)),
// One store addresses one family of artifacts.
ContentAddressedStoreOptions.magic: Uint8Array<ArrayBufferLike>

The four-byte family marker this store accepts and writes. One store addresses one family of artifacts, so a knotkit/heap artifact read through a knotkit/trie store fails as INVALID_MAGIC rather than decoding under the wrong package's rules.

magic
:
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(0x4b, 0x4b, 0x48, 0x50),
})
const
const artifact: {
payloadVersion: number;
packageHeader: Uint8Array<ArrayBuffer>;
sections: {
tag: number;
bytes: Uint8Array<ArrayBuffer>;
}[];
}
artifact
= {
payloadVersion: number
payloadVersion
: 1,
packageHeader: Uint8Array<ArrayBuffer>
packageHeader
:
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(1, 0, 0, 0),
sections: {
tag: number;
bytes: Uint8Array<ArrayBuffer>;
}[]
sections
: [{
tag: number
tag
: 1,
bytes: Uint8Array<ArrayBuffer>
bytes
: new
var Uint8Array: Uint8ArrayConstructor
new (elements: Iterable<number>) => Uint8Array<ArrayBuffer> (+6 overloads)
Uint8Array
([1, 2, 3]) }],
}
const
const address: string
address
= await
const store: ContentAddressedStore
store
.
ContentAddressedStore.add: (artifact: Artifact) => Promise<string>

Frame the artifact, then store it under its address unless the same bytes are already there. Returns the address. O(bytes).

@throws ― {CasInvalidInputError} As addressOf, plus BACKEND_FAILURE when the backend throws.

@throws ― {CasParseError} With ADDRESS_COLLISION when the address is present but holds different bytes, which means the injected hash mapped two artifacts to one address.

add
(
const artifact: {
payloadVersion: number;
packageHeader: Uint8Array<ArrayBuffer>;
sections: {
tag: number;
bytes: Uint8Array<ArrayBuffer>;
}[];
}
artifact
)
const address: string
address
// a 16-character hex address for these exact bytes
await
const store: ContentAddressedStore
store
.
ContentAddressedStore.add: (artifact: Artifact) => Promise<string>

Frame the artifact, then store it under its address unless the same bytes are already there. Returns the address. O(bytes).

@throws ― {CasInvalidInputError} As addressOf, plus BACKEND_FAILURE when the backend throws.

@throws ― {CasParseError} With ADDRESS_COLLISION when the address is present but holds different bytes, which means the injected hash mapped two artifacts to one address.

add
(
const artifact: {
payloadVersion: number;
packageHeader: Uint8Array<ArrayBuffer>;
sections: {
tag: number;
bytes: Uint8Array<ArrayBuffer>;
}[];
}
artifact
) // one stored copy: the address is already present
const
const envelope: WireEnvelope | undefined
envelope
= await
const store: ContentAddressedStore
store
.
ContentAddressedStore.get: (address: string) => Promise<WireEnvelope | undefined>

Read and verify the artifact stored under address, or undefined when the address is absent. O(bytes).

The bytes are re-hashed before decoding, so a backend that returned the wrong content, or a hash that stopped being deterministic, fails as ADDRESS_MISMATCH rather than as a payload that happens to decode.

@throws ― {CasInvalidInputError} With INVALID_ADDRESS when the address is not a safe storage key, or BACKEND_FAILURE when the backend throws.

@throws ― {CasParseError} With ADDRESS_MISMATCH when the stored bytes do not hash to their address, or with any knotkit/wire failure the envelope raises under this store's magic.

get
(
const address: string
address
) // re-hashed, then decoded
cas.ts
  • store the same artifact once no matter how many callers write it
  • prove that the bytes a store returned are the content a key names
  • share artifacts between processes that do not share a filesystem
  • keep serialized structures in an object store, a browser cache, or a Map behind one interface
{"v":1,"box":[44.6024,94.1597,786.3333,437.3555],"x":{"s":"linear","lim":[-0.54,12.54],"inv":false,"g":0,"t":"Add requests","tk":[[0,"0"],[1,"1"],[3,"3"],[5,"5"],[12,"12"]]},"y":{"s":"linear","lim":[-0.54,12.54],"inv":false,"g":0,"tk":[[0,"0"],[3,"3"],[12,"12"]]},"ti":"12 add requests stored 3 blobs: only a first occurrence writes","a":[{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12],"p":[75.22,423.19,131.93,396.95,188.64,370.71,245.35,344.47,302.05,318.23,358.76,292,415.47,265.76,472.18,239.52,528.88,213.28,585.59,187.04,642.3,160.8,699,134.57,755.71,108.33]},{"k":"line","c":"#5b6b7c","s":"x","d":[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12],"p":[75.22,423.19,131.93,396.95,188.64,370.71,245.35,344.47,302.05,318.23,358.76,292,415.47,265.76,472.18,239.52,528.88,213.28,585.59,187.04,642.3,160.8,699,134.57,755.71,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,1,3,2,4,2,5,3,6,3,7,3,8,3,9,3,10,3,11,3,12,3],"p":[75.22,423.19,131.93,396.95,188.64,396.95,245.35,370.71,302.05,370.71,358.76,344.47,415.47,344.47,472.18,344.47,528.88,344.47,585.59,344.47,642.3,344.47,699,344.47,755.71,344.47],"ds":"post"},{"k":"line","c":"#1d5fa6","s":"x","d":[0,0,1,1,2,1,3,2,4,2,5,3,6,3,7,3,8,3,9,3,10,3,11,3,12,3],"p":[75.22,423.19,131.93,396.95,188.64,396.95,245.35,370.71,302.05,370.71,358.76,344.47,415.47,344.47,472.18,344.47,528.88,344.47,585.59,344.47,642.3,344.47,699,344.47,755.71,344.47],"ds":"post"},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 0 1 3 5 12 Add requests 0 3 12 9 duplicates, 4× fewer blobs Stored blobs One blob per request Content-addressed backend 12 add requests stored 3 blobs: only a first occurrence writes
{"v":1,"box":[44.6024,122.3921,338.3333,437.3555],"x":{"s":"linear","lim":[-0.54,12.54],"inv":false,"g":0,"t":"Add requests","tk":[[0,"0"],[1,"1"],[3,"3"],[5,"5"],[12,"12"]]},"y":{"s":"linear","lim":[-0.54,12.54],"inv":false,"g":0,"tk":[[0,"0"],[3,"3"],[12,"12"]]},"ti":"12 add requests stored 3 blobs: only a\nfirst occurrence writes","a":[{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12],"p":[56.73,424.35,79.19,400.27,101.64,376.19,124.1,352.11,146.55,328.03,169.01,303.95,191.47,279.87,213.92,255.79,236.38,231.71,258.84,207.63,281.29,183.55,303.75,159.47,326.21,135.4]},{"k":"line","c":"#5b6b7c","s":"x","d":[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12],"p":[56.73,424.35,79.19,400.27,101.64,376.19,124.1,352.11,146.55,328.03,169.01,303.95,191.47,279.87,213.92,255.79,236.38,231.71,258.84,207.63,281.29,183.55,303.75,159.47,326.21,135.4]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,1,3,2,4,2,5,3,6,3,7,3,8,3,9,3,10,3,11,3,12,3],"p":[56.73,424.35,79.19,400.27,101.64,400.27,124.1,376.19,146.55,376.19,169.01,352.11,191.47,352.11,213.92,352.11,236.38,352.11,258.84,352.11,281.29,352.11,303.75,352.11,326.21,352.11],"ds":"post"},{"k":"line","c":"#1d5fa6","s":"x","d":[0,0,1,1,2,1,3,2,4,2,5,3,6,3,7,3,8,3,9,3,10,3,11,3,12,3],"p":[56.73,424.35,79.19,400.27,101.64,400.27,124.1,376.19,146.55,376.19,169.01,352.11,191.47,352.11,213.92,352.11,236.38,352.11,258.84,352.11,281.29,352.11,303.75,352.11,326.21,352.11],"ds":"post"},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"}],"lg":[]} 0 1 3 5 12 Add requests 0 3 12 9 duplicates, 4× fewer blobs Stored blobs One blob per request Content-addressed backend 12 add requests stored 3 blobs: only a first occurrence writes
  • 12 writes requested, 3 distinct blobs stored.
  • Reading 558718ba60ab8ed6 verifies its address and returns payload 1.
  • Identical artifact bytes share one address and one backend entry.

Hover or focus a chart for exact values. Drawn by demo.ts against knotkit/cas.

ExportReturnsDoes
contentAddressedStoreContentAddressedStoreBind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store.

Cost per member. Open a row for every operation.

contentAddressedStore 4 members
MemberCost
addressOfO(n)
addO(n)
hasO(1) expected
getO(n)
InputTypeGet one from
content hash from framed bytes to address(bytes: Uint8Array) => stringknotkit/hash or crypto.subtle
durable storageArtifactBackendthe caller's backend

Every error this module throws is CasInvalidInputError or CasParseError, with a code from a closed, exported list. Branch on the code; the message is for people.

CasInvalidInputError
INVALID_ARTIFACT
CasParseError
INVALID_ADDRESS INVALID_HASH HASH_FAILURE BACKEND_FAILURE INVALID_MAGIC UNSUPPORTED_ENVELOPE_VERSION UNSUPPORTED_PAYLOAD_VERSION INVALID_SECTION_GEOMETRY NONZERO_PADDING MISALIGNED_SECTION TRUNCATED_PAYLOAD INVALID_CODEC_RESULT DECODE_BUDGET_EXCEEDED UNSTABLE_BUFFER WRONG_FORMAT INTEGRITY_MISMATCH UNKNOWN_KIND ADDRESS_MISMATCH ADDRESS_COLLISION
If you need to…Use instead
persist a structure to local disk in one processthe structure package's serialize function and the platform file API
an artifact that must be readable without the hash that produced its keya caller-chosen storage key and an envelope from knotkit/wire
cryptographic collision resistance or signed artifactscrypto.subtle with SHA-256, or signature verification over the envelope bytes
a cache with eviction, expiry, or least-recently-used orderingknotkit/cache
mutable blobs whose key stays stable as content changesa plain key-value backend; a content address changes with the content

Measured by the suite in packages/cas/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/cas
Use knotkit/cas for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/cas'.

Exports:
- `contentAddressedStore` → `ContentAddressedStore`: Bind a backend, a deterministic content hash, and one family magic into a deduplicating, verifying store.

Inputs and their sources:
- content hash from framed bytes to address: `(bytes: Uint8Array) => string` from `knotkit/hash or crypto.subtle`
- durable storage: `ArtifactBackend` from `the caller's backend`

Use something else when:
- persist a structure to local disk in one process → the structure package's serialize function and the platform file API
- an artifact that must be readable without the hash that produced its key → a caller-chosen storage key and an envelope from knotkit/wire
- cryptographic collision resistance or signed artifacts → crypto.subtle with SHA-256, or signature verification over the envelope bytes
- a cache with eviction, expiry, or least-recently-used ordering → knotkit/cache
- mutable blobs whose key stays stable as content changes → a plain key-value backend; a content address changes with the content

Errors are CasInvalidInputError or CasParseError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/cas.md
Types: node_modules/knotkit/cas/ and https://knotkit.jkomyno.dev/reference/knotkit/cas/