LogoPear Docs
ReferencesHelpers

Corestore

Factory and replication manager for groups of named Hypercores.

stable

Corestore manages many related Hypercores behind one storage root and one replication surface. It is the helper you usually share across Hyperbee, Hyperdrive, and Autobase instances. For upstream source and changelog context, see the Corestore repository.

Install

npm i corestore

Quickstart

import Corestore from 'corestore'

const store = new Corestore('./app-storage')
await store.ready()

const messages = store.get({
  name: 'messages',
  valueEncoding: 'json'
})

await messages.ready()
await messages.append({ text: 'hello from corestore' })

console.log(await messages.get(0))

await store.close()

API Reference

Constructor and lifecycle

new Corestore(storage, options = {})

src

Create a new Corestore instance.

ParameterTypeDefaultDescription
storagestring|objectcan be either a hypercore-storage instance or a string.
optionsCorestoreOptions{}Store options.
  • Throws: ASSERTION if primaryKey is set on a root store without unsafe: true.

await store.ready()

A promise that resolves once the storage seed is loaded and properties such as store.primaryKey are available.

await store.close()

Fully close this Corestore instance.

await store.suspend()

src

Suspend the underlying storage for the Corestore.

ParameterTypeDefaultDescription
optionsobject{}Suspend options.
  • Returns: Promise<void> — Resolves once the storage is flushed and suspended.
await store.suspend()

await store.resume()

src

Resume a suspended Corestore.

  • Returns: Promise<void> — Resolves once the storage is resumed.
await store.resume()

Store properties

store.storage

src

The backing storage adapter used for aliases, seeds, and Hypercore data files.

  • Returns: object

store.primaryKey

src

The 32-byte primary key used to deterministically derive writable named cores and namespaced key pairs.

store.readOnly

src

true when the store was opened without write access.

  • Returns: boolean

store.manifestVersion

src

The Hypercore manifest version used when Corestore creates new writable cores.

  • Returns: number

store.active

src

true when the store should automatically attach loaded cores to active replication streams.

  • Returns: boolean

Loading cores and scoping sessions

store.get(key | { name: 'a-name', ...hypercoreOpts})

src

Loads a Hypercore, either by name (if the name option is provided), or from the provided key (if the first argument is a Buffer or String with hex/z32 key, or if the key options is set).

ParameterTypeDescription
optsBuffer|string|objectA key (Buffer/hex/z32 string), or an options object with name, key, or discoveryKey plus Hypercore options.
  • Returns: Hypercore — A Hypercore session for the requested core.
const core = store.get({ name: 'my-core' })

storeA.session()

src

Create a new Corestore session. Closing a session will close all cores made from this session.

ParameterTypeDescription
optsobjectSession options (forwarded to the new Corestore).
  • Returns: Corestore — A new Corestore session sharing the same storage.
const session = store.session()

store.namespace(name)

src

Create a new namespaced Corestore session. Namespacing is useful if you're going to be sharing a single Corestore instance between many applications or components, as it prevents name collisions.

ParameterTypeDescription
namestring|BufferNamespace name; combined with the current namespace to derive a new one.
optsobjectSession options (forwarded to the new Corestore).
  • Returns: Corestore — A new namespaced Corestore session.
const ns1 = store.namespace('a')
const ns2 = ns1.namespace('b')
const core1 = ns1.get({ name: 'main' }) // These will load different Hypercores
const core2 = ns2.get({ name: 'main' })

Replication and discovery

store.replicate(optsOrStream)

src

Creates a replication stream that's capable of replicating all Hypercores that are managed by the Corestore, assuming the remote peer has the correct capabilities.

ParameterTypeDescription
isInitiatorboolean|Streamtrue/false to initiate, or an existing stream/connection to replicate over.
optsobjectReplication options, forwarded to the protocol stream.
  • Returns: Stream — The replication stream.
const swarm = new Hyperswarm()

// join the relevant topic
swarm.join(...)

// simply pass the connection stream to corestore
swarm.on('connection', (connection) => store.replicate(connection))

store.findingPeers()

src

A completion callback. Call it after the current peer-discovery pass finishes so pending update waits on loaded cores can unblock.

  • Returns: Function — A done function to call once peer discovery has finished.
const done = store.findingPeers()
swarm.flush().then(done, done)

store.list(namespace)

src

Creates a discovery key stream of all cores within a namespace or all cores in general if no namespace is provided.

ParameterTypeDescription
namespaceBufferto scope to; omit to list all cores.
  • Returns: Readable — A stream of discovery keys.
for await (const discoveryKey of store.list()) console.log(discoveryKey)

store.getAuth(discoveryKey)

src

The storage-layer auth metadata for that core, including manifest details when available.

ParameterTypeDescription
discoveryKeyBufferDiscovery key of the core to look up.
const auth = await store.getAuth(discoveryKey)

Key derivation and maintenance

await store.createKeyPair(name, ns = this.ns)

src

Generate a key pair seeded with the Corestore's primary key using a name and a ns aka namespace. ns defaults to the current namespace.

ParameterTypeDefaultDescription
namestringto derive the key pair from.
nsBufferthis.ns
const keyPair = await store.createKeyPair('signer')

store.audit(opts = {})

src

An audit report describing the state of the backing store and any detected inconsistencies.

ParameterTypeDefaultDescription
optsobject{}Audit options (e.g. dryRun).
  • Returns: AsyncGenerator<object> — Yields a result per core as it is audited.
for await (const report of store.audit()) console.log(report)

await store.staticify(core, opts)

src

A reopened Hypercore whose manifest is converted into a static prologue-based manifest for the current data snapshot.

ParameterTypeDescription
coreHypercoreThe source core to snapshot. Must have data.
optsobjectOptions forwarded to store.get() for the new core.
  • Returns: Promise<Hypercore> — The new static Hypercore.
  • Throws: if the core has no data to staticify.
const staticCore = await store.staticify(core)

Watchers

store.watch((core) => {})

src

Register a callback called when new Hypercores are opened. core is the internal core for the opened Hypercore. It can be used to create weak references to a Hypercore like so:

ParameterTypeDefaultDescription
fnFunction> {}Callback invoked with the internal core each time a Hypercore is opened.
  • Returns: void
store.watch(function (core) {
  const weakCore = new Hypercore({ core, weak: true })
})

store.unwatch(callback)

src

Unregister a callback used with store.watch(callback) so it no longer fires.

ParameterTypeDescription
callbackFunctionThe callback previously passed to store.watch().
  • Returns: void
store.unwatch(onCore)

Group notifications (experimental)

store.notifyGroup(topic)

src

Get a handle for updates from all hypercores with the group topic set.

ParameterTypeDescription
topicBufferThe 32-byte group topic to watch.
  • Returns: GroupNotifyHandle — A handle that emits update when a core in the group changes.
const handle = store.notifyGroup(topic)
handle.on('update', () => console.log('group changed'))

Group notifications are experimental. The API is subject to change and may break in any release.

handle.update(opts = {})

Gets updates for the topic the handle is for.

ParameterDefault
opts{}
OptionDefaultDescription
since0What timestamp to start returning updates from. Default 0 returns all updates
reversetrueFlag to return updates in reverse order. Defaults to true so latest returned first
for await (const key of handle.updates()) {
  // ...
}

handle.destroy()

src

Destroys and unregisters the handle from its store.

handle.on('update', callback)

Calls the callback whenever a core with the topic for the handle updates.

store.on('group-active', (topic) => {})

src

The group-active event emits whenever an opened Hypercore in the store updates. The topic is the group topic the core belongs to.

Types

CorestoreOptions

Options for the {@link Corestore} constructor. Any other options are forwarded to the underlying hypercore-storage instance.

PropertyTypeDefaultDescription
primaryKeyBufferThe 32-byte master key from which all writable named cores are derived. Generated and persisted automatically when omitted.
writablebooleantrueSet to false to open the store read-only; loaded cores default to read-only too.
readOnlybooleanfalseOpen the backing storage in read-only mode.
activebooleantrueWhether loaded cores are automatically attached to active replication streams.
unsafebooleanfalseAcknowledge that passing primaryKey directly is unsafe; required when primaryKey is set on a root store.

Errors

Coded errors this module can throw — catch them via err.code.

ErrorThrown when
ASSERTIONif primaryKey is set on a root store without unsafe: true.

See also

  • Work with many Hypercores using Corestore—the task-oriented guide that shows how to share one store across your app.
  • Hypercore—the append-only log type Corestore opens and co-replicates.
  • Hyperbee—commonly layered on top of named Hypercores from one store.
  • Hyperdrive—usually keeps filesystem metadata and content stores inside one shared Corestore.
  • Autobase—multi-writer views often coordinate their input cores through one Corestore.
  • Hyperswarm—pass swarm connections to store.replicate() to co-replicate all managed cores over one stream.
  • Upstream Corestore repository—source, releases, and implementation details.

On this page