# Corestore



<Status level="stable" />

`Corestore` manages many related [Hypercores](/p2p/reference/building-blocks/hypercore) behind one storage root and one replication surface. It is the helper you usually share across [Hyperbee](/p2p/reference/building-blocks/hyperbee), [Hyperdrive](/p2p/reference/building-blocks/hyperdrive), and [Autobase](/p2p/reference/building-blocks/autobase) instances. For upstream source and changelog context, see the [Corestore repository](https://github.com/holepunchto/corestore).

## Install [#install]

```sh
npm i corestore
```

## Quickstart [#quickstart]

```js
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 [#api-reference]

### Constructor and lifecycle [#constructor-and-lifecycle]

#### `new Corestore(storage, options = {})` [#new-corestorestorage-options--]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L207)

Create a new Corestore instance.

| Parameter | Type                                    | Default | Description                                               |
| --------- | --------------------------------------- | ------- | --------------------------------------------------------- |
| `storage` | `string\|object`                        | —       | can be either a `hypercore-storage` instance or a string. |
| `options` | [`CorestoreOptions`](#corestoreoptions) | `{}`    | Store options.                                            |

* Throws: `ERR_ASSERTION` if `primaryKey` is set on a root store without `unsafe: true`.

#### `await store.ready()` [#await-storeready]

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

#### `await store.close()` [#await-storeclose]

Fully close this Corestore instance.

#### `await store.suspend([options])` [#await-storesuspendoptions]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L355)

Suspend the underlying storage for the Corestore.

| Parameter | Type     | Default | Description      |
| --------- | -------- | ------- | ---------------- |
| `options` | `object` | `{}`    | Suspend options. |

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves once the storage is suspended.

Since 7.12.0 this no longer flushes the database first. Earlier releases flushed on every `suspend()` unless the store was read-only; flush explicitly if you were relying on that.

```js
await store.suspend()
```

#### `await store.resume()` [#await-storeresume]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L362)

Resume a suspended Corestore.

* Returns: [`Promise<void>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — Resolves once the storage is resumed.

```js
await store.resume()
```

### Store properties [#store-properties]

#### `store.storage` [#storestorage]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L242)

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

* Returns: `object`

#### `store.primaryKey` [#storeprimarykey]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L257)

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

* Returns: [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer)

#### `store.readOnly` [#storereadonly]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L255)

`true` when the store was opened without write access.

* Returns: `boolean`

#### `store.manifestVersion` [#storemanifestversion]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L258)

The Hypercore manifest version used when Corestore creates new writable cores. Set it with the [`manifestVersion` option](#corestoreoptions), or override it for a single core with [`store.get()`](#storegetkey---name-a-name-hypercoreopts).

* Returns: `number`

#### `store.alwaysLatestBlock` [#storealwayslatestblock]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L261)

`true` when every core this store loads asks for the latest block with each upgrade request. Set it with the [`alwaysLatestBlock` option](#corestoreoptions). Sessions and namespaces created from a store share its value.

* Returns: `boolean`

#### `store.active` [#storeactive]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L260)

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

* Returns: `boolean`

#### `store.opened` / `store.closed` [#storeopened--storeclosed]

`true` once [`store.ready()`](#await-storeready) has resolved / once [`store.close()`](#await-storeclose) has completed. Useful for guarding access to a store whose lifecycle you don't fully control.

* Returns: `boolean`

### Loading cores and scoping sessions [#loading-cores-and-scoping-sessions]

#### `store.get(key | { name: 'a-name', ...hypercoreOpts})` [#storegetkey---name-a-name-hypercoreopts]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L563)

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).

| Parameter | Type                                                                        | Description                                                                                                       |
| --------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `opts`    | [`Buffer\|string\|object`](https://nodejs.org/api/buffer.html#class-buffer) | A key (Buffer/hex/z32 string), or an options object with `name`, `key`, or `discoveryKey` plus Hypercore options. |

* Returns: [`Hypercore`](/p2p/reference/building-blocks/hypercore) — A Hypercore session for the requested core.

`allowLatestBlock` is forwarded through to the returned Hypercore's own [`allowLatestBlock` option](/p2p/reference/building-blocks/hypercore#hypercoreoptions). When you set it, even to `false`, it takes precedence over the store's [`alwaysLatestBlock`](#storealwayslatestblock).

When `get()` creates a new writable core, from `name` or `keyPair`, you can pass `manifestVersion` to override [`store.manifestVersion`](#storemanifestversion) for that call. A core that already exists under that name keeps the manifest it was created with. Added in 7.12.6.

```js
const core = store.get({ name: 'my-core' })
```

#### `storeA.session()` [#storeasession]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L366)

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

| Parameter | Type     | Description                                       |
| --------- | -------- | ------------------------------------------------- |
| `opts`    | `object` | Session options (forwarded to the new Corestore). |

* Returns: [`Corestore`](/p2p/reference/helpers/corestore) — A new Corestore session sharing the same storage.

```js
const session = store.session()
```

#### `store.namespace(name)` [#storenamespacename]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L376)

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.

| Parameter | Type                                                                | Description                                                              |
| --------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| `name`    | [`string\|Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | Namespace name; combined with the current namespace to derive a new one. |
| `opts`    | `object`                                                            | Session options (forwarded to the new Corestore).                        |

* Returns: [`Corestore`](/p2p/reference/helpers/corestore) — A new namespaced Corestore session.

```js
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 [#replication-and-discovery]

#### `store.replicate(optsOrStream)` [#storereplicateoptsorstream]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L480)

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.

| Parameter     | Type                                                    | Description                                                                     |
| ------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `isInitiator` | [`boolean\|Stream`](https://nodejs.org/api/stream.html) | `true`/`false` to initiate, or an existing stream/connection to replicate over. |
| `opts`        | `object`                                                | Replication options, forwarded to the protocol stream.                          |

* Returns: [`Stream`](https://nodejs.org/api/stream.html) — The replication stream.

```js
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()` [#storefindingpeers]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L340)

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.

```js
const done = store.findingPeers()
swarm.flush().then(done, done)
```

#### `store.list(namespace)` [#storelistnamespace]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L383)

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

| Parameter   | Type                                                        | Description                          |
| ----------- | ----------------------------------------------------------- | ------------------------------------ |
| `namespace` | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | to scope to; omit to list all cores. |

* Returns: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) — A stream of discovery keys.

```js
for await (const discoveryKey of store.list()) console.log(discoveryKey)
```

#### `store.getAuth(discoveryKey)` [#storegetauthdiscoverykey]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L387)

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

| Parameter      | Type                                                        | Description                           |
| -------------- | ----------------------------------------------------------- | ------------------------------------- |
| `discoveryKey` | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | Discovery key of the core to look up. |

* Returns: [`Promise<object\|null>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — The auth record, or `null` if not stored.

```js
const auth = await store.getAuth(discoveryKey)
```

### Key derivation and maintenance [#key-derivation-and-maintenance]

#### `await store.createKeyPair(name, ns = this.ns)` [#await-storecreatekeypairname-ns--thisns]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L620)

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.

| Parameter | Type                                                        | Default   | Description                  |
| --------- | ----------------------------------------------------------- | --------- | ---------------------------- |
| `name`    | `string`                                                    | —         | to derive the key pair from. |
| `ns`      | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | `this.ns` | —                            |

* Returns: [`Promise<{publicKey: Buffer, secretKey: Buffer}>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) — The derived key pair.

```js
const keyPair = await store.createKeyPair('signer')
```

#### `store.audit(opts = {})` [#storeauditopts--]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L351)

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

| Parameter | Type     | Default | Description                           |
| --------- | -------- | ------- | ------------------------------------- |
| `opts`    | `object` | `{}`    | Audit options (for example `dryRun`). |

* Returns: `AsyncGenerator<object>` — Yields a result per core as it is audited.

```js
for await (const report of store.audit()) console.log(report)
```

#### `await store.staticify(core, opts)` [#await-storestaticifycore-opts]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L519)

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

| Parameter | Type                                                    | Description                                          |
| --------- | ------------------------------------------------------- | ---------------------------------------------------- |
| `core`    | [`Hypercore`](/p2p/reference/building-blocks/hypercore) | The source core to snapshot. Must have data.         |
| `opts`    | `object`                                                | Options forwarded to `store.get()` for the new core. |

* Returns: [`Promise<Hypercore>`](/p2p/reference/building-blocks/hypercore) — The new static Hypercore.
* Throws: if the core has no data to staticify.

```js
const staticCore = await store.staticify(core)
```

### Watchers [#watchers]

#### `store.watch((core) => {})` [#storewatchcore--]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L282)

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:

| Parameter | Type       | Description                                                                |
| --------- | ---------- | -------------------------------------------------------------------------- |
| `fn`      | `Function` | Callback invoked with the internal `core` each time a Hypercore is opened. |

* Returns: `void`

```js
store.watch(function (core) {
  const weakCore = new Hypercore({ core, weak: true })
})
```

#### `store.unwatch(callback)` [#storeunwatchcallback]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L291)

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

| Parameter  | Type       | Description                                        |
| ---------- | ---------- | -------------------------------------------------- |
| `callback` | `Function` | The callback previously passed to `store.watch()`. |

* Returns: `void`

```js
store.unwatch(onCore)
```

### Group notifications (experimental) [#group-notifications-experimental]

#### `store.notifyGroup(topic)` [#storenotifygrouptopic]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L311)

Get a `handle` for updates from all `hypercore`s with the group `topic` set.

| Parameter | Type                                                        | Description                       |
| --------- | ----------------------------------------------------------- | --------------------------------- |
| `topic`   | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | The 32-byte group topic to watch. |

* Returns: [`GroupNotifyHandle`](/p2p/reference/helpers/corestore) — A handle that emits `update` when a core in the group changes.

```js
const handle = store.notifyGroup(topic)
handle.on('update', () => console.log('group changed'))
```

<Callout type="warn">
  Group notifications are experimental. The API is subject to change and may break in any release.
</Callout>

#### `handle.update(opts = {})` [#handleupdateopts--]

Gets updates for the `topic` the handle is for.

| Parameter | Default |
| --------- | ------- |
| `opts`    | `{}`    |

| Option    | Default | Description                                                                          |
| --------- | ------- | ------------------------------------------------------------------------------------ |
| `since`   | `0`     | What timestamp to start returning updates from. Default `0` returns all updates      |
| `reverse` | `true`  | Flag to return updates in reverse order. Defaults to `true` so latest returned first |

```js
for await (const key of handle.updates()) {
  // ...
}
```

#### `handle.destroy()` [#handledestroy]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L231)

Destroys and unregisters the `handle` from its `store`.

#### `handle.on('update', callback)` [#handleonupdate-callback]

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

#### `store.on('group-active', (topic) => {})` [#storeongroup-active-topic--]

[src](https://github.com/holepunchto/corestore/blob/v7.13.0/index.js#L303)

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

## Types [#types]

### CorestoreOptions [#corestoreoptions]

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

| Property            | Type                                                        | Default | Description                                                                                                                                                                                                                                        |
| ------------------- | ----------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `primaryKey`        | [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) | —       | The 32-byte master key from which all writable named cores are derived. Generated and persisted automatically when omitted.                                                                                                                        |
| `writable`          | `boolean`                                                   | `true`  | Set to `false` to open the store read-only; loaded cores default to read-only too.                                                                                                                                                                 |
| `readOnly`          | `boolean`                                                   | `false` | Open the backing storage in read-only mode.                                                                                                                                                                                                        |
| `active`            | `boolean`                                                   | `true`  | Whether loaded cores are automatically attached to active replication streams.                                                                                                                                                                     |
| `unsafe`            | `boolean`                                                   | `false` | Acknowledge that passing `primaryKey` directly is unsafe; required when `primaryKey` is set on a root store.                                                                                                                                       |
| `treeCache`         | `object`                                                    | —       | Passed to the default `hypercore-storage` instance to size its tree-node cache, for example `{ maxSize: 8192 }`. Added in 7.11.1.                                                                                                                  |
| `manifestVersion`   | `number`                                                    | `1`     | The Hypercore manifest version used when the store creates new writable cores. Exposed as `store.manifestVersion`, and sessions inherit it.                                                                                                        |
| `alwaysLatestBlock` | `boolean`                                                   | `false` | Open every loaded core with `allowLatestBlock` on, so its replicator asks for the latest block with each upgrade request. Sessions and namespaces inherit it, and an `allowLatestBlock` passed to `store.get()` takes precedence. Added in 7.13.0. |

## Errors [#errors]

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

| Error       | Thrown when                                                    |
| ----------- | -------------------------------------------------------------- |
| `ASSERTION` | if `primaryKey` is set on a root store without `unsafe: true`. |

## See also [#see-also]

* [Work with many Hypercores using Corestore](/p2p/how-to/store-and-replicate/work-with-many-hypercores-using-corestore)—the task-oriented guide that shows how to share one store across your app.
* [Hypercore](/p2p/reference/building-blocks/hypercore)—the append-only log type Corestore opens and co-replicates.
* [Hyperbee](/p2p/reference/building-blocks/hyperbee)—commonly layered on top of named Hypercores from one store.
* [Hyperdrive](/p2p/reference/building-blocks/hyperdrive)—usually keeps filesystem metadata and content stores inside one shared Corestore.
* [Autobase](/p2p/reference/building-blocks/autobase)—multi-writer views often coordinate their input cores through one Corestore.
* [Hyperswarm](/p2p/reference/building-blocks/hyperswarm)—pass swarm connections to `store.replicate()` to co-replicate all managed cores over one stream.
* [Upstream Corestore repository](https://github.com/holepunchto/corestore)—source, releases, and implementation details.
