did-btcr2-js

@did-btcr2/api

High-level SDK facade for the did:btcr2 DID method. Wraps @did-btcr2/method and the surrounding crypto / bitcoin / key-management packages behind a single ergonomic entry point.

Part of the did-btcr2-js monorepo.

Summary

The lower-level packages (@did-btcr2/method, @did-btcr2/integrity, @did-btcr2/key-manager, @did-btcr2/bitcoin) are designed to be composable and sans-I/O. This package is the thin layer above them: it owns Bitcoin endpoint configuration, CAS retrieval, key management, and the dispatch loop for the sans-I/O state machines.

If you’re integrating did:btcr2 into an app, start here. If you’re customizing the protocol, drop down to @did-btcr2/method directly.

The api wires the configured BitcoinApi into the sans-I/O Resolver and Updater state machines, fulfilling NeedBeaconSignals, NeedFunding, NeedBroadcast, and CAS-related needs (NeedGenesisDocument, NeedCASAnnouncement, NeedSignedUpdate) automatically. How NeedBeaconSignals is fulfilled follows the connection’s btc.signalDiscovery mode: 'indexer' (the default) reads beacon-address transaction listings from the Esplora-compatible REST backend, while 'fullnode' scans every block from genesis over Bitcoin Core RPC and needs an rpc config (the BitcoinApi constructor refuses 'fullnode' without one), a node with -txindex=1, and Bitcoin Core >= 25; the linear scan makes it practical only on regtest.

NeedSMTProof is not auto-fulfilled by the facade: an SMT proof has no content address on chain (the signal is the tree root, and the proof of one DID is not derivable from it), so it must be provided upfront via options.sidecar.smtProofs; resolution fails with MISSING_UPDATE_DATA and that pointer otherwise. The resolver ignores a sidecar proof whose id does not decode to 32 bytes, for example an id with non-zero pad bits (ADR 146).

Multi-party aggregation is out of scope here. Make the signed update with api.btcr2.constructUpdate and api.btcr2.signUpdate, and give it to the aggregation participant of @did-btcr2/aggregation (submitUpdate). On the read path, a signal below minConf confirmations is excluded before any fetch: the api requests no update, announcement, or proof for it, and the resolved document does not show it until the transaction reaches the depth.

On the write path, announce.publishToCas ('never' 'auto' 'always', default 'never') controls whether update artifacts are published to the configured CAS before the on-chain broadcast. CAS publication is optional and never required: every update, for every beacon type, completes and is distributable via sidecar regardless. Publishing is opt-in: pass 'auto' (publishes when a writable CAS is configured, otherwise skips silently) or 'always' (requires a writable CAS and throws up-front when none is available). Under both modes, a failed publication stops the update before the broadcast, and the beacon UTXO stays unspent. When publication happens, the canonical signed update (all beacon types) plus the CAS Announcement (CAS beacons) reach the CAS, so resolvers can fetch every OP_RETURN update hash from the CAS with no sidecar. Update calls return a DidUpdateResult carrying the signal txid and the per-beacon-type sidecar artifacts (announcement, SMT proof).

The write path refuses these inputs before any CAS publication or broadcast:

The first five refusals run before the signature. Each refusal is an UpdateError. The publishToCas refusal has the type INVALID_OPTIONS, and each other refusal in the list has the type INVALID_DID_UPDATE. resolve() refuses the network mismatch too, with a ResolveError.

The api refuses an api option that is not valid with an UpdateError of type INVALID_OPTIONS (ADR 150). The specification makes INVALID_DID_UPDATE a refinement of INVALID_DID_DOCUMENT, which DID Resolution defines for a malformed DID document. DID Resolution defines INVALID_OPTIONS for options that are not valid. These refusals have the type INVALID_OPTIONS:

The BitcoinApi constructor refuses these btc config values with a MethodError of type INVALID_OPTIONS (ADR 156):

createApi makes the BitcoinApi at the first access of api.btc or api.btcr2. Thus the refusal comes at that access. tryResolveDid reports it as the error INVALID_OPTIONS.

An error message holds a value of the caller only if the value is a primitive, for example a string or a number. For an object or a function, the message holds no value. The error data always holds the value (ADR 156).

Install

npm install @did-btcr2/api

Or with pnpm:

pnpm add @did-btcr2/api

Runtime note: ESM-first package; a CJS build ships via the require export condition (some transitive deps are ESM-only, so import is the reliable path). Ships a browser bundle at dist/browser.mjs for bundler-based environments. Requires Node >= 22.

Key Exports

The api is the one entry point of the implementation (ADR 132). It exports no class of a lower package as a value: each CRUD step is a function of a sub-facade. It exports each type that a public signature uses. src/index.ts lists the full surface.

Concern Entry point
Main facade DidBtcr2Api, createApi(config?)
Sub-facades BitcoinApi, CasApi, CryptoApi (KeyPairApi, MultikeyApi, CryptosuiteApi, DataIntegrityProofApi), DidApi, DidMethodApi, KeyManagerApi, SmtApi
Config ApiConfig, BitcoinApiConfig, SignalDiscoveryMode, CasConfig, Logger, HttpGatewayCasExecutor, IpfsRpcCasExecutor, BlockstoreCasExecutor
Constants and presets DEFAULT_MIN_CONF, DEFAULT_CAS_GATEWAY, DEFAULT_CAS_TIMEOUT_MS, DEFAULT_BITCOIN_NETWORK_CONFIG, NETWORK_PRESETS, explorerTxUrl, explorerAddressUrl, faucetUrl, the genesis constants
Errors DidMethodError (the base class), IdentifierError, DidDocumentError, MethodError, UpdateError, ResolveError, CanonicalizationError, CryptosuiteError
Resolution ResolutionOptions, Sidecar, DidResolutionResult, ResolutionError (the error object of a failed resolution), ResolutionResult (tryResolveDid return type)
Signers and keys Signer (from api.kms.signer(id)), KeyManager (your own KMS for createApi({ kms })), SchnorrKeyPair
Write inputs UpdateSource, SourceState, UpdateOptions, DidUpdateOptions, AnnounceOptions, PublishToCasMode, PatchOperation
Write results DidUpdateResult, BeaconInfo, UnsignedBTCR2Update, SignedBTCR2Update, RootCapability
SMT SmtEntry, SmtTree, SMTProof
Identifier validation DidComponents, IdentifierReport, IdentifierCheck, IdentifierCheckName, IdentifierValidateOptions
Message signatures SignedMessage, SignMessageOptions, MessageReport, MessageCheck, MessageCheckName
Data Integrity proofs DataIntegrityProofOptions, SecuredDocument, CryptosuiteVerificationResult, VerificationResult, ProblemDetails

Quick Start

Generate a DID and resolve it

import { createApi } from '@did-btcr2/api';

const api = createApi({ btc: { network: 'mutinynet' } });

// Generate a keypair, derive the DID, import the secret into the in-process KMS.
// The DID inherits the network of the connection: mutinynet here.
const { did, keyId } = api.generateDid();

// Resolve. Bitcoin signals are fetched automatically via the configured BitcoinApi.
const resolution = await api.resolveDid(did);
console.log(resolution.didDocument?.id);

Find the beacon address to fund, with no chain read

// The initial document of a `k` DID is a pure function of its key. The beacon
// addresses are known before the DID touches the chain.
const beacons = api.btcr2.getBeacons(api.btcr2.getInitialDocument(did));
const beacon = beacons.find((b) => b.id.endsWith('#initialP2WPKH'))!;
console.log(beacon.address); // fund this address before the first update

Build an EXTERNAL DID from a genesis document

// One key with all four relationships, one P2WPKH Singleton beacon on mutinynet.
const genesisDocument = api.btcr2.buildGenesisDocument({
  network             : 'mutinynet',
  verificationMethods : [{ publicKey: kp.publicKey.compressed }],
});
// Hash exactly the bytes you keep or publish.
const json = JSON.stringify(genesisDocument, null, 2);
const { did, didDocument } = api.btcr2.createExternalFromDocument(JSON.parse(json), { network: 'mutinynet' });
const [beacon] = api.btcr2.getBeacons(didDocument);
console.log(did, beacon.address); // fund this address before the first update
// Later: api.resolveDid(did, { sidecar: { genesisDocument: JSON.parse(json) } })

A spec can name several keys with chosen relationships, a CASBeacon or SMTBeacon with the address of a cohort, and other services. The builder refuses a spec with no capabilityInvocation method or no beacon. createExternalFromDocument refuses a genesis document if no capabilityInvocation method of the initial DID document can sign an update. The error text is Invalid genesis document: the DID document has no capabilityInvocation method that can sign an update. Nobody can update or deactivate the DID.

Update

The update arguments follow the update operation of the specification:

// spec: update(sourceDidDocument, jsonPatch, targetVersionId, verificationMethodId, signer)
api.updateDid(source, patch, signer, options?)
// spec: deactivate(sourceDidDocument, targetVersionId, verificationMethodId, signer)
api.deactivateDid(source, signer, options?)
// The source is the DID: the api resolves it and takes the document and its
// versionId from the resolution. The verification method is the one
// capabilityInvocation method that can sign an update and has the key of
// the signer. The beacon is the one funded beacon.
const { signedUpdate, txid } = await api.updateDid(
  did,
  [{ op: 'add', path: '/service/-', value: newService }],
  api.kms.signer(keyId),
);

If you resolved the DID already, pass the state as the source. The api then does not resolve. The versionId must come from the resolution that returned the document:

const source = { document: currentDoc, versionId: 2 };
await api.updateDid(source, patch, signer, {
  // Ids are resolved against the document before matching, so a full DID URL
  // (`${did}#initialKey`) and a bare fragment (`#initialKey`) both work.
  verificationMethodId : `${did}#initialKey`,
  announce             : { beaconId: `${did}#initialP2WPKH` },
});

api.btcr2.update(source, patch, signer, options?) takes the same arguments, but the source must be a SourceState.

Publish update artifacts to a CAS before broadcasting

// A writable CAS (an IPFS node's RPC endpoint) makes updates resolvable
// without sidecar data: the signed update (and, for CAS beacons, the
// announcement) is published before the beacon transaction is broadcast.
const api = createApi({
  btc : { network: 'mutinynet' },
  cas : { rpcUrl: 'http://127.0.0.1:5001' },
});

const first = await api.updateDid(
  did,
  [{ op: 'add', path: '/service/-', value: newService }],
  api.kms.signer(keyId),
  // publishToCas defaults to 'never' (opt-in): update artifacts are returned
  // for sidecar distribution and nothing is published. Opt in with 'auto' to
  // publish to the writable CAS configured above. Note 'auto'/'always' publish
  // canonical signed updates to the configured (possibly public) CAS before the
  // on-chain anchor, so keep the 'never' default for sidecar-only privacy.
  { announce: { publishToCas: 'auto' } },
);
console.log(first.txid, first.publishedToCas); // e.g. { update: true, announcement: false }

Resolve without throwing

const result = await api.tryResolveDid(did);
if (result.ok) {
  console.log(result.document);
} else {
  console.warn(`resolve failed: ${result.error} - ${result.errorMessage}`);
  // result.cause holds the original error, for instanceof checks.
}

Update a DID that already has updates, with the facade’s signer

// api.kms.signer(keyId) wraps the KMS key behind the Signer interface. It also
// works with an external KeyManager (HSM, cloud KMS) passed to createApi({ kms }).
const signer = api.kms.signer(keyId);

// A DID with prior updates resolves only with its sidecar. resolutionOptions
// hands the sidecar to the auto-resolution. The api derives the two ids.
// The signal of `first` must have minConf (default 6) confirmations. If not,
// the resolution cannot see `first`, and the api refuses the update.
const second = await api.updateDid(did, [{ op: 'add', path: '/service/-', value: newService }], signer, {
  resolutionOptions : { sidecar: { updates: [first.signedUpdate] } },
});

Deactivate

// Deactivation is permanent. It is an ordinary update that carries the
// deactivation patch. Pass the full update history in the sidecar.
const { txid } = await api.deactivateDid(did, signer, {
  resolutionOptions : { sidecar: { updates: [first.signedUpdate, second.signedUpdate] } },
});

A later updateDid on a deactivated DID is refused before any signature or broadcast. The patch is DEACTIVATION_PATCH of @did-btcr2/method; DidMethodApi.DEACTIVATION_PATCH is the same object.

Update failures

Every update failure that the specification names is an UpdateError of type INVALID_DID_UPDATE. The refusals of the api in this section have the same type. A refusal of an api option has the type INVALID_OPTIONS, for example an announce.publishToCas value that is not valid (ADR 150). The method package applies the patch with the rules of RFC 6902 and RFC 6901 (ADR 155). The first operation that fails, a failed test included, fails the whole patch. Examples: a remove of a location that does not exist, and an array index with a leading zero.

The verification method that signs an update must agree with these conditions (ADR 147):

  1. An entry of capabilityInvocation identifies the method. The entry is a reference to a member of verificationMethod, or the method as an embedded object. An embedded method signs like a referenced one, also if verificationMethod does not list it.
  2. The type of the method is Multikey.
  3. The controller of the method is the DID.
  4. The publicKeyMultibase of the method is the BIP340 Multikey text of a secp256k1 public key. A publicKeyMultibase that only starts with zQ3s does not agree with this condition.

In this README, a method that agrees with these conditions is a method that “can sign an update”. The key of the signer must be the key of the method. verificationMethodId is a DID URL under the DID, or a relative DID URL (#key-1, ?key=1, /keys/1). The api resolves a relative DID URL against the DID by RFC 3986, section 5 (ADR 162).

Failure Error text
verificationMethodId is not a DID URL under the DID, and not a relative DID URL that resolves to one. Invalid verificationMethodId: expected ...
No entry of capabilityInvocation identifies the method. Invalid verificationMethodId: not authorized for capabilityInvocation
The entry is a reference, and verificationMethod has no method with that id. Invalid verificationMethodId: not found in source document
The method does not agree with condition 2, 3, or 4. data.field names the field. Invalid update: verificationMethod.type must equal "Multikey", and the same form for controller and publicKeyMultibase
The key of the signer is not the key of the method. Signing key does not match verification method "<id>": ...
The public key of the signer is not a valid secp256k1 public key. Invalid signer: <message>
The signer or its key manager fails, for example with a watch-only key. A signature that does not have 64 bytes also fails here. data.cause holds the type and the message of the inner error, for example KEY_NOT_SIGNER or PROOF_GENERATION_ERROR. Invalid update: cannot make the proof with "<id>": <message>
The proof does not verify with the key of the method. Invalid update: the proof does not verify with the public key of "<id>"
The patch fails to apply, or the patched document changes the id or does not conform to DID Core. Invalid patch: ..., Patches must not change the DID document id ..., or Error validating targetDocument: ...
source.versionId is not an integer of 1 or more (constructUpdate, signUpdate). Invalid sourceVersionId: expected an integer of 1 or more.
targetVersionId is not source.versionId + 1 (signUpdate). Invalid update: targetVersionId is <n>, but the source has versionId <m>. Construct the update from this source.
After the update, no capabilityInvocation method can sign an update, and the target document does not have deactivated: true. Invalid update: after this update, the DID document has no capabilityInvocation method that can sign an update. Nobody can update or deactivate <did> again.

Nobody can update or deactivate a DID after an update that leaves no method that can sign an update. Thus the api refuses such an update. updateDid and api.btcr2.update refuse it before the signature. A deactivation always passes, because its target document has deactivated: true. signUpdate signs first, so that each refusal of the method package names its own cause. Then it refuses such an update and returns no signed update.

The api does not refuse an update that leaves no beacon service, for example a patch that removes /service (ADR 148). A beacon of the source document announces this update. After the update, nobody can announce a later update for the DID.

Before the signature, the method package also checks that the unsigned update belongs to the source document. It refuses the update at the first check that fails. The checks run in this order:

  1. Invalid unsignedUpdate: expected an object.
  2. Invalid unsignedUpdate: an unsigned update must not have a proof.
  3. Invalid unsignedUpdate: targetVersionId must be an integer of 2 or more.
  4. Invalid unsignedUpdate: @context must be the BTCR2 update context.
  5. Invalid unsignedUpdate: sourceHash is not the hash of sourceDocument.
  6. Invalid unsignedUpdate: the patch does not give a valid DID document from sourceDocument: <message>
  7. Invalid unsignedUpdate: targetHash is not the hash of the document that the patch gives.

If you make the unsigned update with constructUpdate from the same source, these checks pass.

Architecture Principles

Build & Test

# From packages/api/
pnpm build              # Compile ESM + CJS + browser bundle + type declarations
pnpm build:tests        # Compile tests to tests/compiled/
pnpm test               # Run the test suite with coverage
pnpm lint               # ESLint (zero warnings tolerated)

The lib/ directory contains end-to-end scripts that exercise the full update path against regtest, mutinynet, signet, testnet3, and testnet4. Run with bun packages/api/lib/e2e-*.ts or tsx. On non-regtest networks the scripts persist generated secret keys to lib/.e2e-keys/ (gitignored) so funds at beacon addresses can be recovered.

Documentation

License

MPL-2.0