@did-btcr2/api 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,95 +1,628 @@
1
- import { BitcoinCoreRpcClient, BitcoinNetworkConnection, BitcoinRestClient, BlockV3, RawTransactionV2, RestClientConfigParams, RpcClientConfig } from '@did-btcr2/bitcoin';
1
+ import { BitcoinConnection, BitcoinCoreRpcClient, BitcoinRestClient, type BlockV3, type HttpExecutor, type NetworkName, type RawTransactionRest, type RawTransactionV2, type RestConfig, type RpcConfig } from '@did-btcr2/bitcoin';
2
2
  import type { Bytes, CryptosuiteName, DocumentBytes, Entropy, HashBytes, Hex, HexString, JSONObject, KeyBytes, PatchOperation, ProofBytes, SchnorrKeyPairObject, SignatureBytes } from '@did-btcr2/common';
3
3
  import { IdentifierTypes } from '@did-btcr2/common';
4
- import type { MultikeyObject, SignedBTCR2Update } from '@did-btcr2/cryptosuite';
5
- import { SchnorrMultikey } from '@did-btcr2/cryptosuite';
6
- import { SchnorrKeyPair } from '@did-btcr2/keypair';
7
- import type { Btcr2DidDocument, DidCreateOptions, ResolutionOptions, SidecarData } from '@did-btcr2/method';
8
- import { DidDocument, DidDocumentBuilder, Identifier } from '@did-btcr2/method';
9
- import type { DidResolutionResult, DidService, DidVerificationMethod } from '@web5/dids';
4
+ import { BIP340Cryptosuite, BIP340DataIntegrityProof, BTCR2Update, DataIntegrityConfig, DataIntegrityProofObject, type FromPublicKey, type Multikey, MultikeyObject, SchnorrMultikey, SignedBTCR2Update, UnsignedBTCR2Update, VerificationResult } from '@did-btcr2/cryptosuite';
5
+ import { CompressedSecp256k1PublicKey, SchnorrKeyPair, Secp256k1SecretKey } from '@did-btcr2/keypair';
6
+ import { type GenerateKeyOptions, type ImportKeyOptions, KeyIdentifier, KeyManager, type SignOptions } from '@did-btcr2/kms';
7
+ import type { Btcr2DidDocument, DidCreateOptions, ResolutionOptions } from '@did-btcr2/method';
8
+ import { DidDocument, DidDocumentBuilder, Identifier, IdentifierComponents } from '@did-btcr2/method';
9
+ import { Did, type DidResolutionResult, type DidService, type DidVerificationMethod } from '@web5/dids';
10
10
  export { DidDocument, DidDocumentBuilder, Identifier, IdentifierTypes };
11
- export type { BlockV3, Bytes, CryptosuiteName, DidResolutionResult, DidService, DidVerificationMethod, DocumentBytes, HashBytes, Hex, JSONObject, KeyBytes, MultikeyObject, PatchOperation, ProofBytes, RawTransactionV2, RestClientConfigParams, RpcClientConfig, SchnorrKeyPairObject, SignatureBytes };
12
- export type NetworkName = 'mainnet' | 'testnet4' | 'signet' | 'regtest';
11
+ export type { BlockV3, Bytes, CryptosuiteName, DidResolutionResult, DidService, DidVerificationMethod, DocumentBytes, HashBytes, Hex, HttpExecutor, JSONObject, KeyBytes, MultikeyObject, NetworkName, PatchOperation, ProofBytes, RawTransactionV2, RestConfig, RpcConfig, SchnorrKeyPairObject, SignatureBytes };
12
+ /**
13
+ * Pluggable logger interface. All methods are optional-call; the default
14
+ * implementation is a silent no-op.
15
+ * @public
16
+ */
17
+ export type Logger = {
18
+ debug(message: string, ...args: unknown[]): void;
19
+ info(message: string, ...args: unknown[]): void;
20
+ warn(message: string, ...args: unknown[]): void;
21
+ error(message: string, ...args: unknown[]): void;
22
+ };
23
+ /**
24
+ * The two supported DID identifier types.
25
+ *
26
+ * Note: the upstream `DidCreateOptions.idType` is typed as `string` rather
27
+ * than a union. This local alias provides compile-time safety at the API
28
+ * facade level. Upstream runtime validation in `Identifier.encode()` still
29
+ * catches invalid values.
30
+ * @public
31
+ */
32
+ export type IdType = 'KEY' | 'EXTERNAL';
33
+ /**
34
+ * A branded string representing a DID identifier (e.g. `did:btcr2:k1q...`).
35
+ * Use branded types to prevent accidentally passing a txid where a DID is
36
+ * expected, or vice versa, at compile time.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const did = api.generateDid().did as DidString;
41
+ * api.resolveDid(did); // OK
42
+ * api.btc.getTransaction(did); // Type error — DidString is not TxId
43
+ * ```
44
+ * @public
45
+ */
46
+ export type DidString = string & {
47
+ readonly __brand: 'DidString';
48
+ };
49
+ /**
50
+ * A branded string representing a Bitcoin transaction ID (64-char hex).
51
+ * @public
52
+ */
53
+ export type TxId = string & {
54
+ readonly __brand: 'TxId';
55
+ };
56
+ /**
57
+ * Result of a DID resolution attempt. Wraps the standard
58
+ * {@link DidResolutionResult} with a discriminated `ok` flag for ergonomic
59
+ * pattern matching without exception handling.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const result = await api.tryResolveDid(did);
64
+ * if (result.ok) {
65
+ * console.log(result.document);
66
+ * } else {
67
+ * console.log(result.error, result.errorMessage);
68
+ * }
69
+ * ```
70
+ * @public
71
+ */
72
+ export type ResolutionResult = {
73
+ ok: true;
74
+ document: Btcr2DidDocument;
75
+ metadata: DidResolutionResult['didDocumentMetadata'];
76
+ raw: DidResolutionResult;
77
+ } | {
78
+ ok: false;
79
+ error: string;
80
+ errorMessage?: string;
81
+ raw: DidResolutionResult;
82
+ };
83
+ /**
84
+ * Bitcoin API configuration options.
85
+ * The `network` field is required and determines default REST/RPC endpoints.
86
+ * Optional `rest` and `rpc` fields override individual endpoints on top of
87
+ * the network defaults.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * // Use regtest defaults (localhost Polar + Esplora)
92
+ * { network: 'regtest' }
93
+ *
94
+ * // Use testnet4 with a custom REST endpoint
95
+ * { network: 'testnet4', rest: { host: 'https://my-mempool.example/api' } }
96
+ *
97
+ * // Use regtest with custom RPC credentials, default REST
98
+ * { network: 'regtest', rpc: { host: 'http://mynode:18443', username: 'u', password: 'p' } }
99
+ * ```
100
+ * @public
101
+ */
13
102
  export type BitcoinApiConfig = {
14
- /** Shortcut to compute base URLs and params via @did-btcr2/bitcoin getNetwork */
15
- network?: NetworkName;
16
- /** Override REST client settings */
17
- rest?: RestClientConfigParams;
18
- /** Override RPC client settings */
19
- rpc?: RpcClientConfig;
20
- /** Default number of confirmations to consider "final" */
21
- defaultConfirmations?: number;
103
+ /** Bitcoin network name (e.g., 'regtest', 'testnet4', 'bitcoin'). */
104
+ network: NetworkName;
105
+ /** Override REST client settings on top of network defaults. */
106
+ rest?: Partial<RestConfig>;
107
+ /** Override RPC client settings on top of network defaults. */
108
+ rpc?: RpcConfig;
109
+ /**
110
+ * Optional HTTP executor for sans-I/O usage. Defaults to global `fetch`.
111
+ * Inject a custom executor to intercept requests in tests or route through
112
+ * a proxy without monkey-patching globals.
113
+ */
114
+ executor?: HttpExecutor;
115
+ /**
116
+ * Optional request timeout in milliseconds for REST calls.
117
+ * When set, wraps the HTTP executor with an `AbortSignal.timeout()`.
118
+ * Has no effect when a custom `executor` is provided (the custom
119
+ * executor is responsible for its own timeouts).
120
+ */
121
+ timeoutMs?: number;
22
122
  };
123
+ /**
124
+ * Top-level API configuration options.
125
+ * @public
126
+ */
23
127
  export type ApiConfig = {
24
- bitcoin?: BitcoinApiConfig;
128
+ btc?: BitcoinApiConfig;
129
+ kms?: KeyManager;
130
+ /** Optional logger. Defaults to a silent no-op logger. */
131
+ logger?: Logger;
25
132
  };
133
+ /**
134
+ * Schnorr keypair operations.
135
+ * @public
136
+ */
26
137
  export declare class KeyPairApi {
27
- /** Generate a new Schnorr keypair (secp256k1). */
28
- static generate(): SchnorrKeyPair;
29
- /** Import from secret key bytes or bigint. */
30
- static fromSecret(ent: Entropy): SchnorrKeyPair;
138
+ /**
139
+ * Generate a new Schnorr keypair.
140
+ * @returns The generated Schnorr keypair.
141
+ */
142
+ generate(): SchnorrKeyPair;
143
+ /**
144
+ * Create a Schnorr keypair from secret key bytes or hex string.
145
+ * @param data The secret key bytes or hex string.
146
+ * @returns The created Schnorr keypair.
147
+ */
148
+ fromSecret(data: KeyBytes | HexString): SchnorrKeyPair;
149
+ /** Create a secret key from entropy (bytes or bigint). */
150
+ secretKeyFrom(ent: Entropy): Secp256k1SecretKey;
151
+ /** Create a compressed public key from bytes. */
152
+ publicKeyFrom(byt: Bytes): CompressedSecp256k1PublicKey;
153
+ /** Deserialize a keypair from a JSON object. */
154
+ fromJSON(obj: SchnorrKeyPairObject): SchnorrKeyPair;
155
+ /** Serialize a keypair to a JSON object. */
156
+ toJSON(kp: SchnorrKeyPair): SchnorrKeyPairObject;
157
+ /** Compare two keypairs for equality. */
158
+ equals(kp1: SchnorrKeyPair, kp2: SchnorrKeyPair): boolean;
159
+ }
160
+ /**
161
+ * Schnorr cryptosuite operations.
162
+ *
163
+ * Optionally stateful: call {@link use} to set a current cryptosuite, then
164
+ * call {@link createProof}, {@link verifyProof}, or {@link toDataIntegrityProof}
165
+ * without passing an explicit instance. Pass an explicit instance to any
166
+ * method to override the current one for that call.
167
+ * @public
168
+ */
169
+ export declare class CryptosuiteApi {
170
+ #private;
171
+ /** The currently active cryptosuite, or `undefined` if none is set. */
172
+ get current(): BIP340Cryptosuite | undefined;
173
+ /**
174
+ * Set the current cryptosuite for subsequent operations.
175
+ * @param cs The cryptosuite to activate.
176
+ * @returns `this` for chaining.
177
+ */
178
+ use(cs: BIP340Cryptosuite): this;
179
+ /** Clear the current cryptosuite. */
180
+ clear(): void;
181
+ /**
182
+ * Create a new Schnorr cryptosuite from a multikey.
183
+ * @param multikey The Schnorr multikey to use.
184
+ * @returns The created Schnorr cryptosuite.
185
+ */
186
+ create(multikey: SchnorrMultikey): BIP340Cryptosuite;
187
+ /**
188
+ * Convenience: resolve a key from the KMS and create a cryptosuite in one step.
189
+ * @param id The multikey ID (e.g. '#initialKey').
190
+ * @param controller The DID that controls this key.
191
+ * @param keyId The KMS key identifier to resolve.
192
+ * @param kms The KeyManagerApi instance holding the key.
193
+ * @returns The created Schnorr cryptosuite.
194
+ */
195
+ createFromKms(id: string, controller: string, keyId: KeyIdentifier, kms: KeyManagerApi): BIP340Cryptosuite;
196
+ /**
197
+ * Convert a cryptosuite to a Data Integrity Proof instance.
198
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
199
+ * @param cryptosuite Optional explicit cryptosuite to convert.
200
+ * @returns The Data Integrity Proof instance.
201
+ */
202
+ toDataIntegrityProof(cryptosuite?: BIP340Cryptosuite): BIP340DataIntegrityProof;
203
+ /**
204
+ * Create a proof for a document.
205
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
206
+ * @param document The document to create the proof for.
207
+ * @param config Configuration for the proof creation.
208
+ * @param cryptosuite Optional explicit cryptosuite; defaults to current.
209
+ * @returns The created proof.
210
+ */
211
+ createProof(document: BTCR2Update, config: DataIntegrityConfig, cryptosuite?: BIP340Cryptosuite): DataIntegrityProofObject;
212
+ /**
213
+ * Verify a proof for a document.
214
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
215
+ * @param document The document to verify the proof for.
216
+ * @param cryptosuite Optional explicit cryptosuite; defaults to current.
217
+ * @returns The full verification result.
218
+ */
219
+ verifyProof(document: SignedBTCR2Update, cryptosuite?: BIP340Cryptosuite): VerificationResult;
31
220
  }
221
+ /**
222
+ * Data Integrity Proof operations.
223
+ *
224
+ * Optionally stateful: call {@link use} to set a current proof instance, then
225
+ * call {@link addProof} or {@link verifyProof} without passing an explicit
226
+ * instance. Pass an explicit instance to override for that call.
227
+ * @public
228
+ */
229
+ export declare class DataIntegrityProofApi {
230
+ #private;
231
+ /** The currently active proof instance, or `undefined` if none is set. */
232
+ get current(): BIP340DataIntegrityProof | undefined;
233
+ /**
234
+ * Set the current proof instance for subsequent operations.
235
+ * @param p The proof instance to activate.
236
+ * @returns `this` for chaining.
237
+ */
238
+ use(p: BIP340DataIntegrityProof): this;
239
+ /** Clear the current proof instance. */
240
+ clear(): void;
241
+ /**
242
+ * Create a BIP340DataIntegrityProof instance with the given cryptosuite.
243
+ * @param cryptosuite The cryptosuite to use for proof operations.
244
+ * @returns The created BIP340DataIntegrityProof instance.
245
+ */
246
+ create(cryptosuite: BIP340Cryptosuite): BIP340DataIntegrityProof;
247
+ /**
248
+ * Add a proof to a document.
249
+ * Uses the current proof instance when `proof` is omitted.
250
+ * @param document The document to add the proof to.
251
+ * @param config Configuration for adding the proof.
252
+ * @param proof Optional explicit proof instance; defaults to current.
253
+ * @returns A document with a proof added.
254
+ */
255
+ addProof(document: UnsignedBTCR2Update, config: DataIntegrityConfig, proof?: BIP340DataIntegrityProof): SignedBTCR2Update;
256
+ /**
257
+ * Convenience: create a cryptosuite, proof instance, and sign a document
258
+ * in one call. Requires a multikey with signing capability.
259
+ * @param multikey The Schnorr multikey (must include secret key).
260
+ * @param document The unsigned document to sign.
261
+ * @param config The Data Integrity proof configuration.
262
+ * @returns The signed document with proof attached.
263
+ */
264
+ signDocument(multikey: SchnorrMultikey, document: UnsignedBTCR2Update, config: DataIntegrityConfig): SignedBTCR2Update;
265
+ /**
266
+ * Verify a proof using a BIP340DataIntegrityProof instance.
267
+ * Uses the current proof instance when `proof` is omitted.
268
+ * @param document The document to verify the proof for.
269
+ * @param expectedPurpose The expected proof purpose.
270
+ * @param mediaType The media type of the document.
271
+ * @param expectedDomain The expected domain for the proof.
272
+ * @param expectedChallenge The expected challenge for the proof.
273
+ * @param proof Optional explicit proof instance; defaults to current.
274
+ * @returns The result of verifying the proof.
275
+ */
276
+ verifyProof(document: string, expectedPurpose: string, mediaType?: string, expectedDomain?: string, expectedChallenge?: string, proof?: BIP340DataIntegrityProof): VerificationResult;
277
+ }
278
+ /**
279
+ * Schnorr multikey operations.
280
+ *
281
+ * Optionally stateful: call {@link use} to set a current multikey, then
282
+ * call {@link sign}, {@link verify}, or {@link toVerificationMethod} without
283
+ * passing an explicit instance. Pass an explicit instance to any method to
284
+ * override the current one for that call.
285
+ * @public
286
+ */
32
287
  export declare class MultikeyApi {
288
+ #private;
289
+ /** The currently active multikey, or `undefined` if none is set. */
290
+ get current(): SchnorrMultikey | undefined;
291
+ /**
292
+ * Set the current multikey for subsequent operations.
293
+ * @param mk The multikey to activate.
294
+ * @returns `this` for chaining.
295
+ */
296
+ use(mk: SchnorrMultikey): this;
297
+ /** Clear the current multikey. */
298
+ clear(): void;
299
+ /**
300
+ * Create a new Schnorr multikey from a keypair.
301
+ * @param id The multikey ID.
302
+ * @param controller The multikey controller.
303
+ * @param keyPair The Schnorr keypair to use.
304
+ * @returns The created Schnorr multikey.
305
+ */
306
+ create(id: string, controller: string, keyPair: SchnorrKeyPair): SchnorrMultikey;
307
+ /**
308
+ * Create a Schnorr multikey from raw secret key bytes.
309
+ * @param id The multikey ID.
310
+ * @param controller The multikey controller.
311
+ * @param secretKeyBytes The secret key bytes.
312
+ * @returns The created Schnorr multikey.
313
+ */
314
+ fromSecretKey(id: string, controller: string, secretKeyBytes: Bytes): SchnorrMultikey;
315
+ /**
316
+ * Create a verification-only multikey from public key bytes.
317
+ * @param params The id, controller, and publicKeyBytes.
318
+ * @returns The created Multikey.
319
+ */
320
+ fromPublicKey(params: FromPublicKey): Multikey;
321
+ /**
322
+ * Convenience: resolve a key from the KMS and create a multikey in one step.
323
+ * @param id The multikey ID.
324
+ * @param controller The multikey controller DID.
325
+ * @param keyId The KMS key identifier to resolve.
326
+ * @param kms The KeyManagerApi instance holding the key.
327
+ * @returns The created Multikey (verification-only; public key from KMS).
328
+ */
329
+ fromKms(id: string, controller: string, keyId: KeyIdentifier, kms: KeyManagerApi): Multikey;
330
+ /**
331
+ * Reconstruct a multikey from a DID document's verification method.
332
+ * @param verificationMethod The verification method to convert.
333
+ * @returns The reconstructed multikey.
334
+ */
335
+ fromVerificationMethod(verificationMethod: DidVerificationMethod): SchnorrMultikey;
33
336
  /**
34
- * Create a Schnorr Multikey wrapper (includes verificationMethod, sign/verify).
35
- * If secret is present, the multikey can sign.
36
- */
37
- static create(params: {
38
- id: string;
39
- controller: string;
40
- keys: SchnorrKeyPair;
41
- }): SchnorrMultikey;
42
- /** Produce a DID Verification Method JSON from a multikey. */
43
- static toVerificationMethod(mk: SchnorrMultikey): DidVerificationMethod;
44
- /** Sign bytes via the multikey (requires secret). */
45
- static sign(mk: SchnorrMultikey, data: Bytes): Promise<SignatureBytes>;
46
- /** Verify signature via multikey. */
47
- static verify(mk: SchnorrMultikey, data: Bytes, signature: SignatureBytes): Promise<boolean>;
337
+ * Produce a DID Verification Method JSON from a multikey.
338
+ * Uses the current multikey when `mk` is omitted.
339
+ * @param mk Optional explicit multikey; defaults to current.
340
+ */
341
+ toVerificationMethod(mk?: SchnorrMultikey): DidVerificationMethod;
342
+ /**
343
+ * Sign bytes via the multikey (requires secret).
344
+ * Uses the current multikey when `mk` is omitted.
345
+ * @param data The data to sign.
346
+ * @param mk Optional explicit multikey; defaults to current.
347
+ */
348
+ sign(data: Bytes, mk?: SchnorrMultikey): SignatureBytes;
349
+ /**
350
+ * Verify signature via multikey.
351
+ * Uses the current multikey when `mk` is omitted.
352
+ * @param data The data that was signed.
353
+ * @param signature The signature to verify.
354
+ * @param mk Optional explicit multikey; defaults to current.
355
+ */
356
+ verify(data: Bytes, signature: SignatureBytes, mk?: SchnorrMultikey): boolean;
48
357
  }
358
+ /**
359
+ * Aggregated cryptographic operations sub-facade.
360
+ *
361
+ * Provides direct access to the four sub-facades ({@link keypair},
362
+ * {@link multikey}, {@link cryptosuite}, {@link proof}) plus top-level
363
+ * convenience methods that orchestrate the full signing/verification
364
+ * pipeline using their stateful defaults.
365
+ *
366
+ * @example Stateful pipeline
367
+ * ```ts
368
+ * const api = createApi();
369
+ * const kp = api.crypto.keypair.generate();
370
+ * const mk = api.crypto.multikey.create('#key-1', 'did:btcr2:test', kp);
371
+ *
372
+ * // Set the active multikey — flows through to cryptosuite and proof
373
+ * api.crypto.activate(mk);
374
+ *
375
+ * // Now sign without threading instances
376
+ * const signed = api.crypto.signDocument(unsignedDoc, proofConfig);
377
+ * ```
378
+ * @public
379
+ */
49
380
  export declare class CryptoApi {
50
- static keyPairApi: KeyPairApi;
51
- static multikeyApi: MultikeyApi;
381
+ /** Schnorr keypair operations. */
382
+ readonly keypair: KeyPairApi;
383
+ /** Schnorr Multikey operations (optionally stateful). */
384
+ readonly multikey: MultikeyApi;
385
+ /** Schnorr Cryptosuite operations (optionally stateful). */
386
+ readonly cryptosuite: CryptosuiteApi;
387
+ /** Data Integrity Proof operations (optionally stateful). */
388
+ readonly proof: DataIntegrityProofApi;
389
+ /**
390
+ * Activate a multikey and propagate through the full pipeline.
391
+ * Sets the current multikey, creates a cryptosuite from it, and creates
392
+ * a proof instance from the cryptosuite — all three sub-facades become
393
+ * ready for stateful operations.
394
+ * @param mk The multikey to activate (must include a secret key for signing).
395
+ * @returns `this` for chaining.
396
+ */
397
+ activate(mk: SchnorrMultikey): this;
398
+ /**
399
+ * Clear stateful defaults from all sub-facades.
400
+ */
401
+ deactivate(): void;
402
+ /**
403
+ * Sign data using the current multikey.
404
+ * Shorthand for `crypto.multikey.sign(data)`.
405
+ * @param data The data to sign.
406
+ * @returns The signature bytes.
407
+ */
408
+ sign(data: Bytes): SignatureBytes;
409
+ /**
410
+ * Verify a signature using the current multikey.
411
+ * Shorthand for `crypto.multikey.verify(data, signature)`.
412
+ * @param data The data that was signed.
413
+ * @param signature The signature to verify.
414
+ * @returns `true` if the signature is valid.
415
+ */
416
+ verify(data: Bytes, signature: SignatureBytes): boolean;
417
+ /**
418
+ * Sign a BTCR2 update document using the current proof instance.
419
+ * Shorthand for `crypto.proof.addProof(document, config)`.
420
+ *
421
+ * Requires {@link activate} to have been called first, or the three
422
+ * sub-facades to have been configured individually.
423
+ * @param document The unsigned BTCR2 update document.
424
+ * @param config The Data Integrity proof configuration.
425
+ * @returns The signed document with proof attached.
426
+ */
427
+ signDocument(document: UnsignedBTCR2Update, config: DataIntegrityConfig): SignedBTCR2Update;
428
+ /**
429
+ * Verify a signed BTCR2 update document using the current cryptosuite.
430
+ * Shorthand for `crypto.cryptosuite.verifyProof(document)`.
431
+ * @param document The signed document to verify.
432
+ * @returns The full verification result.
433
+ */
434
+ verifyDocument(document: SignedBTCR2Update): VerificationResult;
52
435
  }
436
+ /**
437
+ * Bitcoin network operations sub-facade.
438
+ * Always backed by a {@link BitcoinConnection} so it can be passed to
439
+ * resolve/update without extra configuration.
440
+ *
441
+ * Lazily initialized by {@link DidBtcr2Api} to avoid connection overhead
442
+ * when Bitcoin features are not used.
443
+ * @public
444
+ */
53
445
  export declare class BitcoinApi {
54
- readonly rest: BitcoinRestClient;
55
- readonly rpc: BitcoinCoreRpcClient;
56
- readonly defaultConfirmations: number;
57
- constructor(cfg?: BitcoinApiConfig);
58
- /** Fetch a transaction by txid via REST. */
59
- getTransaction(txid: string): Promise<import("@did-btcr2/bitcoin").RawTransactionRest>;
60
- /** Broadcast a raw tx (hex) via REST. */
446
+ /** The underlying BitcoinConnection used for all operations. */
447
+ readonly connection: BitcoinConnection;
448
+ /** REST client for the active network. */
449
+ get rest(): BitcoinRestClient;
450
+ /**
451
+ * RPC client for the active network, or `undefined` if not configured.
452
+ * Use {@link requireRpc} when RPC is expected to be available.
453
+ */
454
+ get rpc(): BitcoinCoreRpcClient | undefined;
455
+ /** Whether an RPC client is available for this network. */
456
+ get hasRpc(): boolean;
457
+ /**
458
+ * RPC client for the active network.
459
+ * @throws {Error} If RPC was not configured for this network.
460
+ */
461
+ requireRpc(): BitcoinCoreRpcClient;
462
+ /**
463
+ * Create a BitcoinApi for a specific network with optional endpoint overrides.
464
+ * Uses BitcoinConnection.forNetwork() — no env vars consulted.
465
+ * @param cfg The network and optional REST/RPC overrides.
466
+ */
467
+ constructor(cfg: BitcoinApiConfig);
468
+ /**
469
+ * Fetch a transaction by txid via REST.
470
+ * @param txid The transaction ID (64-character hex string).
471
+ * @returns The fetched transaction.
472
+ */
473
+ getTransaction(txid: string): Promise<RawTransactionRest>;
474
+ /**
475
+ * Broadcast a raw tx (hex) via REST.
476
+ * @param rawTxHex The raw transaction hex string.
477
+ */
61
478
  send(rawTxHex: string): Promise<string>;
62
- /** Get UTXOs for an address via REST. */
479
+ /**
480
+ * Get UTXOs for an address via REST.
481
+ * @param address The Bitcoin address.
482
+ */
63
483
  getUtxos(address: string): Promise<import("@did-btcr2/bitcoin").AddressUtxo[]>;
64
- /** Get a block by hash or height via REST. */
484
+ /**
485
+ * Get a block by hash or height via REST.
486
+ * @param params Block identifier — at least one of `hash` or `height` is required.
487
+ */
65
488
  getBlock(params: {
66
489
  hash?: string;
67
490
  height?: number;
68
- }): Promise<import("@did-btcr2/bitcoin").BlockResponse | undefined>;
491
+ }): Promise<import("@did-btcr2/bitcoin").EsploraBlock | undefined>;
492
+ /** Convert BTC to satoshis (integer-safe string-split arithmetic). */
493
+ static btcToSats(btc: number): number;
494
+ /** Convert satoshis to BTC (integer-safe string-split arithmetic). */
495
+ static satsToBtc(sats: number): number;
69
496
  }
497
+ /**
498
+ * Key management operations sub-facade.
499
+ *
500
+ * Wraps a {@link KeyManager} interface. By default uses the built-in
501
+ * {@link Kms} implementation; a custom implementation can be injected
502
+ * via {@link ApiConfig}.
503
+ * @public
504
+ */
505
+ export declare class KeyManagerApi {
506
+ /** The backing KeyManager instance. */
507
+ readonly kms: KeyManager;
508
+ /** Create a new KeyManagerApi, optionally backed by a custom KeyManager. */
509
+ constructor(kms?: KeyManager);
510
+ /** Generate a new key directly in the KMS. */
511
+ generateKey(options?: GenerateKeyOptions): KeyIdentifier;
512
+ /** Set the active key by its identifier. */
513
+ setActive(id: KeyIdentifier): void;
514
+ /** Get the public key bytes for a key identifier. */
515
+ getPublicKey(id?: KeyIdentifier): Bytes;
516
+ /** Import a Schnorr keypair into the KMS. */
517
+ import(kp: SchnorrKeyPair, options?: ImportKeyOptions): KeyIdentifier;
518
+ /**
519
+ * Export a Schnorr keypair from the KMS.
520
+ * Only supported when the backing KMS is the built-in {@link Kms} class.
521
+ * @throws {Error} If the backing KMS does not support key export.
522
+ */
523
+ export(id: KeyIdentifier): SchnorrKeyPair;
524
+ /** List all managed key identifiers. */
525
+ listKeys(): KeyIdentifier[];
526
+ /** Remove a key from the KMS. */
527
+ removeKey(id: KeyIdentifier, options?: {
528
+ force?: boolean;
529
+ }): void;
530
+ /**
531
+ * Sign data via the KMS.
532
+ * @param data The data to sign (must be non-empty).
533
+ * @param id Optional key identifier; uses the active key if omitted.
534
+ * @param options Signing options (scheme defaults to 'schnorr').
535
+ */
536
+ sign(data: Bytes, id?: KeyIdentifier, options?: SignOptions): SignatureBytes;
537
+ /** Verify a signature via the KMS. */
538
+ verify(signature: SignatureBytes, data: Bytes, id?: KeyIdentifier, options?: SignOptions): boolean;
539
+ /** Compute a SHA-256 digest. */
540
+ digest(data: Uint8Array): HashBytes;
541
+ }
542
+ /**
543
+ * DID identifier operations sub-facade (encode, decode, generate, parse).
544
+ * @public
545
+ */
70
546
  export declare class DidApi {
71
547
  /**
72
- * Create a deterministic DID from a public key (bytes).
548
+ * Encode a DID from genesis bytes and options.
549
+ * @param genesisBytes The genesis document bytes.
550
+ * @param options The creation options.
551
+ * @returns The encoded DID string.
552
+ */
553
+ encode(genesisBytes: DocumentBytes, options: DidCreateOptions): string;
554
+ /**
555
+ * Decode a DID into its components.
556
+ * @param did The DID string to decode.
557
+ * @returns The decoded identifier components.
558
+ */
559
+ decode(did: string): IdentifierComponents;
560
+ /**
561
+ * Generate a new DID along with its keypair.
562
+ *
563
+ * When no `network` is given, defaults to `'regtest'` (upstream default).
564
+ * Pass an explicit network to generate DIDs for other networks.
565
+ *
566
+ * @param network Optional network to generate the DID for.
567
+ * @returns The generated keypair and DID string.
568
+ */
569
+ generate(network?: NetworkName): {
570
+ keyPair: SchnorrKeyPairObject;
571
+ did: string;
572
+ };
573
+ /**
574
+ * Check if a DID string is valid.
575
+ * @param did The DID string to validate.
576
+ * @returns `true` if valid, `false` otherwise.
577
+ */
578
+ isValid(did: string): boolean;
579
+ /**
580
+ * Parse a DID string into a Did instance.
581
+ * @param did The DID string to parse.
582
+ * @returns The parsed Did instance, or `null` if parsing failed.
583
+ */
584
+ parse(did: string): Did | null;
585
+ }
586
+ /**
587
+ * DID method operations sub-facade: create, resolve, update, deactivate.
588
+ *
589
+ * Lazily initialized by {@link DidBtcr2Api} because it depends on
590
+ * {@link BitcoinApi} which requires network configuration.
591
+ * @public
592
+ */
593
+ export declare class DidMethodApi {
594
+ #private;
595
+ constructor(btc?: BitcoinApi, logger?: Logger);
596
+ /**
597
+ * Create a deterministic (k1) DID from a public key.
598
+ * Sets idType to KEY automatically.
599
+ * @param genesisBytes The compressed public key bytes (33 bytes).
600
+ * @param options Creation options (idType is set for you).
601
+ * @returns The created DID identifier string.
73
602
  */
74
- createDeterministic({ genesisBytes, options }: {
75
- genesisBytes: KeyBytes;
76
- options: DidCreateOptions;
77
- }): Promise<string>;
603
+ createDeterministic(genesisBytes: KeyBytes, options?: Omit<DidCreateOptions, 'idType'>): string;
78
604
  /**
79
- * Create from an intermediate DID document (external genesis).
605
+ * Create a non-deterministic (x1) DID from external genesis document bytes.
606
+ * Sets idType to EXTERNAL automatically.
607
+ * @param genesisBytes The genesis document bytes.
608
+ * @param options Creation options (idType is set for you).
609
+ * @returns The created DID identifier string.
80
610
  */
81
- createExternal({ genesisBytes, options }: {
82
- genesisBytes: DocumentBytes;
83
- options: DidCreateOptions;
84
- }): Promise<string>;
611
+ createExternal(genesisBytes: DocumentBytes, options?: Omit<DidCreateOptions, 'idType'>): string;
85
612
  /**
86
- * Resolve DID document from DID (did:btcr2:...).
613
+ * Resolve a DID. If a Bitcoin connection is configured on the API, it is
614
+ * injected automatically as the driver — unless the caller explicitly
615
+ * provides `drivers.bitcoin` (even as `undefined`) in the options.
616
+ * @param did The DID to resolve.
617
+ * @param options Resolution options.
618
+ * @returns The resolution result.
87
619
  */
88
- resolve(did: string, options: ResolutionOptions): Promise<DidResolutionResult>;
620
+ resolve(did: string, options?: ResolutionOptions): Promise<DidResolutionResult>;
89
621
  /**
90
- * Update a DID Document using a JSON Patch, signed as capabilityInvocation.
91
- * You provide the prior DID Document (to pick VM), a JSON Patch, and a signer multikey.
92
- * This delegates to MethodUpdate (which follows the cryptosuite rules internally).
622
+ * Update an existing DID document. If a Bitcoin connection is configured on
623
+ * the API, it is injected automatically.
624
+ * @param params The update parameters.
625
+ * @returns The signed update.
93
626
  */
94
627
  update({ sourceDocument, patches, sourceVersionId, verificationMethodId, beaconId, signingMaterial, bitcoin, }: {
95
628
  sourceDocument: Btcr2DidDocument;
@@ -98,16 +631,167 @@ export declare class DidApi {
98
631
  verificationMethodId: string;
99
632
  beaconId: string;
100
633
  signingMaterial?: KeyBytes | HexString;
101
- bitcoin?: BitcoinNetworkConnection;
634
+ bitcoin?: BitcoinConnection;
102
635
  }): Promise<SignedBTCR2Update>;
103
- /** Deactivate convenience: applies the standard `deactivated: true` patch. */
104
- deactivate(): Promise<SidecarData>;
636
+ /**
637
+ * Get the signing method from a DID document by method ID.
638
+ * @param didDocument The DID document.
639
+ * @param methodId The method ID (if omitted, the first signing method is returned).
640
+ * @returns The found signing method.
641
+ */
642
+ getSigningMethod(didDocument: Btcr2DidDocument, methodId?: string): DidVerificationMethod;
643
+ /**
644
+ * Create a fluent builder for a DID update operation.
645
+ * @param sourceDocument The current DID document to update.
646
+ * @returns An {@link UpdateBuilder} for chaining update parameters.
647
+ *
648
+ * @example
649
+ * ```ts
650
+ * const signed = await api.btcr2
651
+ * .buildUpdate(currentDoc)
652
+ * .patch({ op: 'add', path: '/service/1', value: newService })
653
+ * .version(2)
654
+ * .signer('#initialKey')
655
+ * .beacon('#beacon-0')
656
+ * .execute();
657
+ * ```
658
+ */
659
+ buildUpdate(sourceDocument: Btcr2DidDocument): UpdateBuilder;
660
+ /** Deactivate a DID (not yet implemented in the core method). */
661
+ deactivate(): Promise<SignedBTCR2Update>;
105
662
  }
663
+ /**
664
+ * Fluent builder for DID update operations. Reduces the cognitive load of
665
+ * the 7-parameter `update()` call by letting callers chain named steps.
666
+ *
667
+ * Created via {@link DidMethodApi.buildUpdate}.
668
+ * @public
669
+ */
670
+ export declare class UpdateBuilder {
671
+ #private;
672
+ /** @internal */
673
+ constructor(methodApi: DidMethodApi, sourceDocument: Btcr2DidDocument);
674
+ /** Add a single JSON Patch operation. Can be called multiple times. */
675
+ patch(op: PatchOperation): this;
676
+ /** Set all patches at once (replaces any previously added). */
677
+ patches(ops: PatchOperation[]): this;
678
+ /** Set the source version ID. */
679
+ version(id: number): this;
680
+ /** Set the verification method ID used for signing. */
681
+ signer(methodId: string): this;
682
+ /** Set the beacon ID for the update announcement. */
683
+ beacon(beaconId: string): this;
684
+ /** Set the signing material (secret key bytes or hex). */
685
+ signingMaterial(material: KeyBytes | HexString): this;
686
+ /** Override the Bitcoin connection for this update. */
687
+ withBitcoin(connection: BitcoinConnection): this;
688
+ /**
689
+ * Execute the update.
690
+ * @throws {Error} If required fields (version, signer, beacon) are missing.
691
+ */
692
+ execute(): Promise<SignedBTCR2Update>;
693
+ }
694
+ /**
695
+ * Main DidBtcr2Api facade — the primary entry point for the SDK.
696
+ *
697
+ * Exposes sub-facades for Bitcoin, DID Method, KeyPair, Crypto, and
698
+ * KeyManager operations. Created via the {@link createApi} factory.
699
+ * @public
700
+ */
106
701
  export declare class DidBtcr2Api {
107
- readonly bitcoin: BitcoinApi;
108
- readonly did: DidApi;
109
- readonly keys: KeyPairApi;
702
+ #private;
703
+ /** Cryptographic operations (keypair, multikey, cryptosuite, proof). */
110
704
  readonly crypto: CryptoApi;
705
+ /** DID identifier operations (encode, decode, generate, parse). */
706
+ readonly did: DidApi;
707
+ /** Key management operations. */
708
+ readonly kms: KeyManagerApi;
111
709
  constructor(config?: ApiConfig);
710
+ /**
711
+ * Bitcoin API sub-facade (lazily initialized).
712
+ * Only available when `btc` config was provided to the constructor.
713
+ * @throws {Error} If the instance has been disposed or no Bitcoin config was provided.
714
+ */
715
+ get btc(): BitcoinApi;
716
+ /**
717
+ * DID Method API sub-facade (lazily initialized with bitcoin wiring).
718
+ * @throws {Error} If the instance has been disposed.
719
+ */
720
+ get btcr2(): DidMethodApi;
721
+ /**
722
+ * Whether this API instance has been disposed.
723
+ */
724
+ get disposed(): boolean;
725
+ /**
726
+ * Create a DID using either deterministic (KEY) or external (EXTERNAL) mode.
727
+ * @param type The creation mode.
728
+ * @param genesisBytes Public key bytes (deterministic) or document bytes (external).
729
+ * @param options Creation options (idType is set for you).
730
+ * @returns The created DID identifier string.
731
+ */
732
+ createDid(type: 'deterministic' | 'external', genesisBytes: KeyBytes | DocumentBytes, options?: Omit<DidCreateOptions, 'idType'>): string;
733
+ /**
734
+ * Generate a new DID, create the keypair, and import it into the KMS.
735
+ * @param options Optional settings.
736
+ * @param options.setActive Whether to set the imported key as active in the KMS (default `true`).
737
+ * @param options.network Network for the generated DID (default `'regtest'`).
738
+ * @returns The generated DID string and KMS key identifier.
739
+ */
740
+ generateDid(options?: {
741
+ setActive?: boolean;
742
+ network?: NetworkName;
743
+ }): {
744
+ did: string;
745
+ keyId: KeyIdentifier;
746
+ };
747
+ /**
748
+ * Resolve a DID, automatically injecting the configured Bitcoin connection.
749
+ * @param did The DID to resolve.
750
+ * @param options Optional resolution options.
751
+ * @returns The resolution result.
752
+ */
753
+ resolveDid(did: string, options?: ResolutionOptions): Promise<DidResolutionResult>;
754
+ /**
755
+ * Resolve a DID and return a discriminated result instead of throwing.
756
+ * Useful when resolution failure is an expected outcome (e.g. checking
757
+ * whether a DID exists before creating it).
758
+ * @param did The DID to resolve.
759
+ * @param options Optional resolution options.
760
+ * @returns A {@link ResolutionResult} with `ok: true` on success or
761
+ * `ok: false` with error details on failure.
762
+ */
763
+ tryResolveDid(did: string, options?: ResolutionOptions): Promise<ResolutionResult>;
764
+ /**
765
+ * Update a DID document: resolve the current state, apply patches, sign, and announce.
766
+ * Automatically injects the configured Bitcoin connection.
767
+ *
768
+ * If `sourceDocument` and `sourceVersionId` are both provided, resolution
769
+ * is skipped. Otherwise the DID is resolved first to obtain them.
770
+ * @param params The update parameters.
771
+ * @returns The signed update.
772
+ */
773
+ updateDid({ did, patches, verificationMethodId, beaconId, sourceDocument, sourceVersionId, }: {
774
+ did: string;
775
+ patches: PatchOperation[];
776
+ verificationMethodId: string;
777
+ beaconId: string;
778
+ sourceDocument?: Btcr2DidDocument;
779
+ sourceVersionId?: number;
780
+ }): Promise<SignedBTCR2Update>;
781
+ /**
782
+ * Release internal references. After disposal, accessing `btc`, `btcr2`,
783
+ * or calling top-level methods will throw.
784
+ *
785
+ * Note: the underlying {@link BitcoinConnection} does not hold persistent
786
+ * connections, so this is primarily a guard against accidental reuse.
787
+ */
788
+ dispose(): void;
112
789
  }
790
+ /**
791
+ * Create a new {@link DidBtcr2Api} instance with the given configuration.
792
+ * @param config Optional configuration for the API.
793
+ * @returns The created DidBtcr2Api instance.
794
+ * @public
795
+ */
113
796
  export declare function createApi(config?: ApiConfig): DidBtcr2Api;
797
+ //# sourceMappingURL=api.d.ts.map