@canton-network/core-signing-dfns 0.9.0 → 0.11.0

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.
package/dist/index.cjs CHANGED
@@ -1,462 +1,463 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var coreSigningLib = require('@canton-network/core-signing-lib');
6
- var sdk = require('@dfns/sdk');
7
- var sdkKeysigner = require('@dfns/sdk-keysigner');
8
- var pino = require('pino');
9
- var _ = require('lodash');
10
- var zod = require('zod');
11
-
12
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
-
14
- var ___default = /*#__PURE__*/_interopDefault(_);
15
-
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
16
7
  var __defProp = Object.defineProperty;
17
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
19
- var logger = pino.pino({ name: "dfns-handler", level: "debug" });
20
- var DFNS_LIST_PAGE_SIZE = 50;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let _canton_network_core_signing_lib = require("@canton-network/core-signing-lib");
28
+ let _dfns_sdk = require("@dfns/sdk");
29
+ let _dfns_sdk_keysigner = require("@dfns/sdk-keysigner");
30
+ let pino = require("pino");
31
+ let lodash = require("lodash");
32
+ lodash = __toESM(lodash, 1);
33
+ let zod = require("zod");
34
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
35
+ function _typeof(o) {
36
+ "@babel/helpers - typeof";
37
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
38
+ return typeof o;
39
+ } : function(o) {
40
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
41
+ }, _typeof(o);
42
+ }
43
+ //#endregion
44
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
45
+ function toPrimitive(t, r) {
46
+ if ("object" != _typeof(t) || !t) return t;
47
+ var e = t[Symbol.toPrimitive];
48
+ if (void 0 !== e) {
49
+ var i = e.call(t, r || "default");
50
+ if ("object" != _typeof(i)) return i;
51
+ throw new TypeError("@@toPrimitive must return a primitive value.");
52
+ }
53
+ return ("string" === r ? String : Number)(t);
54
+ }
55
+ //#endregion
56
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
57
+ function toPropertyKey(t) {
58
+ var i = toPrimitive(t, "string");
59
+ return "symbol" == _typeof(i) ? i : i + "";
60
+ }
61
+ //#endregion
62
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
63
+ function _defineProperty(e, r, t) {
64
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
65
+ value: t,
66
+ enumerable: !0,
67
+ configurable: !0,
68
+ writable: !0
69
+ }) : e[r] = t, e;
70
+ }
71
+ //#endregion
72
+ //#region src/dfns.ts
73
+ const logger = (0, pino.pino)({
74
+ name: "dfns-handler",
75
+ level: "debug"
76
+ });
77
+ const DFNS_LIST_PAGE_SIZE = 50;
21
78
  function stripHexPrefix(hex) {
22
- return hex.startsWith("0x") ? hex.slice(2) : hex;
79
+ return hex.startsWith("0x") ? hex.slice(2) : hex;
23
80
  }
24
81
  function hexToBase64(hex) {
25
- return Buffer.from(stripHexPrefix(hex), "hex").toString("base64");
82
+ return Buffer.from(stripHexPrefix(hex), "hex").toString("base64");
26
83
  }
27
84
  function base64ToHex(base64) {
28
- return Buffer.from(base64, "base64").toString("hex");
85
+ return Buffer.from(base64, "base64").toString("hex");
29
86
  }
30
87
  function isCantonKey(scheme, curve) {
31
- return scheme === "EdDSA" && curve === "ed25519";
88
+ return scheme === "EdDSA" && curve === "ed25519";
32
89
  }
33
90
  var DfnsHandler = class {
34
- constructor(orgId, baseUrl, credentials) {
35
- __publicField(this, "client");
36
- __publicField(this, "orgId");
37
- __publicField(this, "baseUrl");
38
- // Tracks the key that produced each signature so getSignature can look it
39
- // up directly. `listKeys` (used by `iterateKeys`) is eventually-consistent
40
- // — a key created moments ago may not yet appear in the list, so iterating
41
- // would 404 even though the signature exists under the just-used key.
42
- __publicField(this, "signatureKey", /* @__PURE__ */ new Map());
43
- this.orgId = orgId;
44
- this.baseUrl = baseUrl;
45
- this.client = this.createClient(credentials);
46
- }
47
- createClient(credentials) {
48
- const signer = new sdkKeysigner.AsymmetricKeySigner({
49
- credId: credentials.credId,
50
- privateKey: credentials.privateKey
51
- });
52
- return new sdk.DfnsApiClient({
53
- orgId: this.orgId,
54
- authToken: credentials.authToken,
55
- baseUrl: this.baseUrl,
56
- signer
57
- });
58
- }
59
- /**
60
- * Create a raw ed25519 key in Dfns suitable for signing Canton topology
61
- * and ledger transactions. The key is not bound to a network — chain
62
- * activation happens on the gateway against its configured validator.
63
- */
64
- async createKey(name) {
65
- try {
66
- const key = await this.client.keys.createKey({
67
- body: {
68
- scheme: "EdDSA",
69
- curve: "ed25519",
70
- name
71
- }
72
- });
73
- return {
74
- id: key.id,
75
- name: key.name || key.id,
76
- publicKey: hexToBase64(key.publicKey)
77
- };
78
- } catch (error) {
79
- logger.error(error, "Error creating Dfns key");
80
- throw error;
81
- }
82
- }
83
- async *iterateKeys() {
84
- let paginationToken;
85
- do {
86
- const response = await this.client.keys.listKeys({
87
- query: {
88
- limit: DFNS_LIST_PAGE_SIZE,
89
- ...paginationToken ? { paginationToken } : {}
90
- }
91
- });
92
- for (const key of response.items) {
93
- if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
94
- continue;
95
- }
96
- yield {
97
- id: key.id,
98
- name: key.name || key.id,
99
- publicKey: hexToBase64(key.publicKey)
100
- };
101
- }
102
- paginationToken = response.nextPageToken;
103
- } while (paginationToken);
104
- }
105
- async listKeys() {
106
- const keys = [];
107
- try {
108
- for await (const key of this.iterateKeys()) {
109
- keys.push(key);
110
- }
111
- } catch (error) {
112
- logger.error(error, "Error listing Dfns keys");
113
- throw error;
114
- }
115
- return keys;
116
- }
117
- async getKey(keyId) {
118
- try {
119
- const key = await this.client.keys.getKey({ keyId });
120
- if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) {
121
- return void 0;
122
- }
123
- return {
124
- id: key.id,
125
- name: key.name || key.id,
126
- publicKey: hexToBase64(key.publicKey)
127
- };
128
- } catch (error) {
129
- logger.debug(error, `Key ${keyId} not found`);
130
- return void 0;
131
- }
132
- }
133
- /**
134
- * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —
135
- * acceptable for first iteration since most deployments hold a single
136
- * Canton key per credential.
137
- */
138
- async findKeyByPublicKey(publicKeyBase64) {
139
- for await (const key of this.iterateKeys()) {
140
- if (key.publicKey === publicKeyBase64) {
141
- return key;
142
- }
143
- }
144
- return void 0;
145
- }
146
- /**
147
- * Sign a Canton hash (raw or multihash-framed) by handing the bytes to
148
- * Dfns's `Message` kind, which signs the supplied hex with raw ed25519 —
149
- * the same shape Fireblocks's `RAW` operation produces.
150
- *
151
- * `kind: 'Hash'` would be the natural fit but its regex caps at 32 bytes,
152
- * forcing us to strip the multihash prefix; Canton then rejects the
153
- * resulting signature because it verifies over the full 34-byte
154
- * multihash, not the digest. Every Canton-tagged kind (Hash/Message/
155
- * Transaction + `blockchainKind: 'Canton'`) is server-rejected, so we
156
- * use plain `Message` (no `blockchainKind`) and pass the raw bytes.
157
- */
158
- async signHash(keyId, hashBase64, externalId) {
159
- const messageHex = base64ToHex(hashBase64);
160
- const body = {
161
- kind: "Message",
162
- message: messageHex,
163
- ...externalId ? { externalId } : {}
164
- };
165
- return this.submitSignatureRequest(keyId, body);
166
- }
167
- async submitSignatureRequest(keyId, body) {
168
- try {
169
- const result = await this.client.keys.generateSignature({
170
- keyId,
171
- body
172
- });
173
- const mapped = this.mapStatus(result.status);
174
- if (mapped === "failed" || mapped === "rejected") {
175
- logger.error(
176
- { keyId, result },
177
- `Dfns signing returned ${result.status}`
178
- );
179
- }
180
- this.signatureKey.set(result.id, keyId);
181
- return {
182
- id: result.id,
183
- keyId,
184
- status: mapped,
185
- signature: this.extractSignature(result.signature)
186
- };
187
- } catch (error) {
188
- logger.error(
189
- { keyId, err: error },
190
- "Error generating Dfns signature"
191
- );
192
- throw error;
193
- }
194
- }
195
- async getSignature(keyId, signatureId) {
196
- try {
197
- const result = await this.client.keys.getSignature({
198
- keyId,
199
- signatureId
200
- });
201
- return {
202
- id: result.id,
203
- keyId,
204
- status: this.mapStatus(result.status),
205
- signature: this.extractSignature(result.signature)
206
- };
207
- } catch (error) {
208
- logger.debug(error, `Signature ${signatureId} not found`);
209
- return void 0;
210
- }
211
- }
212
- /**
213
- * Locate a signature by id. Prefers the cached key from the originating
214
- * sign call — `listKeys` is eventually-consistent, so iterating right
215
- * after creating a key would miss the signature. Falls back to iteration
216
- * when the cache misses (e.g. across a gateway restart).
217
- */
218
- async findSignature(signatureId) {
219
- const cachedKeyId = this.signatureKey.get(signatureId);
220
- if (cachedKeyId) {
221
- const sig = await this.getSignature(cachedKeyId, signatureId);
222
- if (sig) return sig;
223
- }
224
- for await (const key of this.iterateKeys()) {
225
- if (key.id === cachedKeyId) continue;
226
- const sig = await this.getSignature(key.id, signatureId);
227
- if (sig) return sig;
228
- }
229
- return void 0;
230
- }
231
- async *listSignatures(keyId) {
232
- let paginationToken;
233
- do {
234
- const response = await this.client.keys.listSignatures({
235
- keyId,
236
- query: {
237
- limit: DFNS_LIST_PAGE_SIZE,
238
- ...paginationToken ? { paginationToken } : {}
239
- }
240
- });
241
- for (const sig of response.items) {
242
- yield {
243
- id: sig.id,
244
- keyId,
245
- status: this.mapStatus(sig.status),
246
- signature: this.extractSignature(sig.signature)
247
- };
248
- }
249
- paginationToken = response.nextPageToken;
250
- } while (paginationToken);
251
- }
252
- extractSignature(signature) {
253
- if (!signature) return void 0;
254
- const hex = signature.encoded ? stripHexPrefix(signature.encoded) : `${stripHexPrefix(signature.r)}${stripHexPrefix(signature.s)}`;
255
- return hexToBase64(hex);
256
- }
257
- mapStatus(dfnsStatus) {
258
- switch (dfnsStatus) {
259
- case "Signed":
260
- case "Confirmed":
261
- return "signed";
262
- case "Pending":
263
- case "Executing":
264
- return "pending";
265
- case "Rejected":
266
- return "rejected";
267
- case "Failed":
268
- return "failed";
269
- default:
270
- logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`);
271
- return "pending";
272
- }
273
- }
91
+ constructor(orgId, baseUrl, credentials) {
92
+ _defineProperty(this, "client", void 0);
93
+ _defineProperty(this, "orgId", void 0);
94
+ _defineProperty(this, "baseUrl", void 0);
95
+ _defineProperty(this, "signatureKey", /* @__PURE__ */ new Map());
96
+ this.orgId = orgId;
97
+ this.baseUrl = baseUrl;
98
+ this.client = this.createClient(credentials);
99
+ }
100
+ createClient(credentials) {
101
+ const signer = new _dfns_sdk_keysigner.AsymmetricKeySigner({
102
+ credId: credentials.credId,
103
+ privateKey: credentials.privateKey
104
+ });
105
+ return new _dfns_sdk.DfnsApiClient({
106
+ orgId: this.orgId,
107
+ authToken: credentials.authToken,
108
+ baseUrl: this.baseUrl,
109
+ signer
110
+ });
111
+ }
112
+ /**
113
+ * Create a raw ed25519 key in Dfns suitable for signing Canton topology
114
+ * and ledger transactions. The key is not bound to a network — chain
115
+ * activation happens on the gateway against its configured validator.
116
+ */
117
+ async createKey(name) {
118
+ try {
119
+ const key = await this.client.keys.createKey({ body: {
120
+ scheme: "EdDSA",
121
+ curve: "ed25519",
122
+ name
123
+ } });
124
+ return {
125
+ id: key.id,
126
+ name: key.name || key.id,
127
+ publicKey: hexToBase64(key.publicKey)
128
+ };
129
+ } catch (error) {
130
+ logger.error(error, "Error creating Dfns key");
131
+ throw error;
132
+ }
133
+ }
134
+ async *iterateKeys() {
135
+ let paginationToken;
136
+ do {
137
+ const response = await this.client.keys.listKeys({ query: {
138
+ limit: DFNS_LIST_PAGE_SIZE,
139
+ ...paginationToken ? { paginationToken } : {}
140
+ } });
141
+ for (const key of response.items) {
142
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) continue;
143
+ yield {
144
+ id: key.id,
145
+ name: key.name || key.id,
146
+ publicKey: hexToBase64(key.publicKey)
147
+ };
148
+ }
149
+ paginationToken = response.nextPageToken;
150
+ } while (paginationToken);
151
+ }
152
+ async listKeys() {
153
+ const keys = [];
154
+ try {
155
+ for await (const key of this.iterateKeys()) keys.push(key);
156
+ } catch (error) {
157
+ logger.error(error, "Error listing Dfns keys");
158
+ throw error;
159
+ }
160
+ return keys;
161
+ }
162
+ async getKey(keyId) {
163
+ try {
164
+ const key = await this.client.keys.getKey({ keyId });
165
+ if (key.status !== "Active" || !isCantonKey(key.scheme, key.curve)) return;
166
+ return {
167
+ id: key.id,
168
+ name: key.name || key.id,
169
+ publicKey: hexToBase64(key.publicKey)
170
+ };
171
+ } catch (error) {
172
+ logger.debug(error, `Key ${keyId} not found`);
173
+ return;
174
+ }
175
+ }
176
+ /**
177
+ * Resolve a key by base64 ed25519 public key. Iterates Dfns keys —
178
+ * acceptable for first iteration since most deployments hold a single
179
+ * Canton key per credential.
180
+ */
181
+ async findKeyByPublicKey(publicKeyBase64) {
182
+ for await (const key of this.iterateKeys()) if (key.publicKey === publicKeyBase64) return key;
183
+ }
184
+ /**
185
+ * Sign a Canton hash (raw or multihash-framed) by handing the bytes to
186
+ * Dfns's `Message` kind, which signs the supplied hex with raw ed25519 —
187
+ * the same shape Fireblocks's `RAW` operation produces.
188
+ *
189
+ * `kind: 'Hash'` would be the natural fit but its regex caps at 32 bytes,
190
+ * forcing us to strip the multihash prefix; Canton then rejects the
191
+ * resulting signature because it verifies over the full 34-byte
192
+ * multihash, not the digest. Every Canton-tagged kind (Hash/Message/
193
+ * Transaction + `blockchainKind: 'Canton'`) is server-rejected, so we
194
+ * use plain `Message` (no `blockchainKind`) and pass the raw bytes.
195
+ */
196
+ async signHash(keyId, hashBase64, externalId) {
197
+ const body = {
198
+ kind: "Message",
199
+ message: base64ToHex(hashBase64),
200
+ ...externalId ? { externalId } : {}
201
+ };
202
+ return this.submitSignatureRequest(keyId, body);
203
+ }
204
+ async submitSignatureRequest(keyId, body) {
205
+ try {
206
+ const result = await this.client.keys.generateSignature({
207
+ keyId,
208
+ body
209
+ });
210
+ const mapped = this.mapStatus(result.status);
211
+ if (mapped === "failed" || mapped === "rejected") logger.error({
212
+ keyId,
213
+ result
214
+ }, `Dfns signing returned ${result.status}`);
215
+ this.signatureKey.set(result.id, keyId);
216
+ return {
217
+ id: result.id,
218
+ keyId,
219
+ status: mapped,
220
+ signature: this.extractSignature(result.signature)
221
+ };
222
+ } catch (error) {
223
+ logger.error({
224
+ keyId,
225
+ err: error
226
+ }, "Error generating Dfns signature");
227
+ throw error;
228
+ }
229
+ }
230
+ async getSignature(keyId, signatureId) {
231
+ try {
232
+ const result = await this.client.keys.getSignature({
233
+ keyId,
234
+ signatureId
235
+ });
236
+ return {
237
+ id: result.id,
238
+ keyId,
239
+ status: this.mapStatus(result.status),
240
+ signature: this.extractSignature(result.signature)
241
+ };
242
+ } catch (error) {
243
+ logger.debug(error, `Signature ${signatureId} not found`);
244
+ return;
245
+ }
246
+ }
247
+ /**
248
+ * Locate a signature by id. Prefers the cached key from the originating
249
+ * sign call — `listKeys` is eventually-consistent, so iterating right
250
+ * after creating a key would miss the signature. Falls back to iteration
251
+ * when the cache misses (e.g. across a gateway restart).
252
+ */
253
+ async findSignature(signatureId) {
254
+ const cachedKeyId = this.signatureKey.get(signatureId);
255
+ if (cachedKeyId) {
256
+ const sig = await this.getSignature(cachedKeyId, signatureId);
257
+ if (sig) return sig;
258
+ }
259
+ for await (const key of this.iterateKeys()) {
260
+ if (key.id === cachedKeyId) continue;
261
+ const sig = await this.getSignature(key.id, signatureId);
262
+ if (sig) return sig;
263
+ }
264
+ }
265
+ async *listSignatures(keyId) {
266
+ let paginationToken;
267
+ do {
268
+ const response = await this.client.keys.listSignatures({
269
+ keyId,
270
+ query: {
271
+ limit: DFNS_LIST_PAGE_SIZE,
272
+ ...paginationToken ? { paginationToken } : {}
273
+ }
274
+ });
275
+ for (const sig of response.items) yield {
276
+ id: sig.id,
277
+ keyId,
278
+ status: this.mapStatus(sig.status),
279
+ signature: this.extractSignature(sig.signature)
280
+ };
281
+ paginationToken = response.nextPageToken;
282
+ } while (paginationToken);
283
+ }
284
+ extractSignature(signature) {
285
+ if (!signature) return void 0;
286
+ return hexToBase64(signature.encoded ? stripHexPrefix(signature.encoded) : `${stripHexPrefix(signature.r)}${stripHexPrefix(signature.s)}`);
287
+ }
288
+ mapStatus(dfnsStatus) {
289
+ switch (dfnsStatus) {
290
+ case "Signed":
291
+ case "Confirmed": return "signed";
292
+ case "Pending":
293
+ case "Executing": return "pending";
294
+ case "Rejected": return "rejected";
295
+ case "Failed": return "failed";
296
+ default:
297
+ logger.warn(`Unknown Dfns signature status: ${dfnsStatus}`);
298
+ return "pending";
299
+ }
300
+ }
274
301
  };
275
- var DfnsCredentialsSchema = zod.z.object({
276
- credId: zod.z.string().min(1),
277
- privateKey: zod.z.string().min(1),
278
- authToken: zod.z.string().min(1)
302
+ //#endregion
303
+ //#region src/index.ts
304
+ const DfnsCredentialsSchema = zod.z.object({
305
+ credId: zod.z.string().min(1),
306
+ privateKey: zod.z.string().min(1),
307
+ authToken: zod.z.string().min(1)
279
308
  });
280
- var DfnsConfigSchema = zod.z.object({
281
- orgId: zod.z.string().min(1),
282
- baseUrl: zod.z.string().url(),
283
- credentials: DfnsCredentialsSchema
309
+ const DfnsConfigSchema = zod.z.object({
310
+ orgId: zod.z.string().min(1),
311
+ baseUrl: zod.z.string().url(),
312
+ credentials: DfnsCredentialsSchema
284
313
  });
285
- var createDfnsHandler = (config) => new DfnsHandler(config.orgId, config.baseUrl, config.credentials);
314
+ const createDfnsHandler = (config) => new DfnsHandler(config.orgId, config.baseUrl, config.credentials);
286
315
  function toTransaction(sig, publicKey) {
287
- const tx = {
288
- txId: sig.id,
289
- status: sig.status
290
- };
291
- if (sig.signature) tx.signature = sig.signature;
292
- if (publicKey) tx.publicKey = publicKey;
293
- return tx;
316
+ const tx = {
317
+ txId: sig.id,
318
+ status: sig.status
319
+ };
320
+ if (sig.signature) tx.signature = sig.signature;
321
+ if (publicKey) tx.publicKey = publicKey;
322
+ return tx;
294
323
  }
295
324
  var DfnsSigningDriver = class {
296
- constructor(config) {
297
- __publicField(this, "dfns");
298
- __publicField(this, "config");
299
- __publicField(this, "partyMode", coreSigningLib.PartyMode.EXTERNAL);
300
- __publicField(this, "signingProvider", coreSigningLib.SigningProvider.DFNS);
301
- __publicField(this, "controller", (_userId) => coreSigningLib.buildController({
302
- signTransaction: async (params) => {
303
- try {
304
- const keyId = await this.resolveKeyId(params.keyIdentifier);
305
- if (!keyId) {
306
- return {
307
- error: "key_not_found",
308
- error_description: "No Dfns key found for the provided key identifier."
309
- };
310
- }
311
- if (!params.txHash) {
312
- return {
313
- error: "bad_arguments",
314
- error_description: "txHash is required to sign with Dfns."
315
- };
316
- }
317
- const sig = await this.dfns.signHash(
318
- keyId,
319
- params.txHash,
320
- params.internalTxId
321
- );
322
- return toTransaction(sig, params.keyIdentifier.publicKey);
323
- } catch (error) {
324
- return {
325
- error: "signing_error",
326
- error_description: error.message
327
- };
328
- }
329
- },
330
- getTransaction: async (params) => {
331
- try {
332
- const sig = await this.dfns.findSignature(params.txId);
333
- if (!sig) {
334
- return {
335
- error: "transaction_not_found",
336
- error_description: "The requested signature does not exist."
337
- };
338
- }
339
- const key = await this.dfns.getKey(sig.keyId);
340
- return toTransaction(sig, key?.publicKey);
341
- } catch (error) {
342
- return {
343
- error: "fetch_error",
344
- error_description: error.message
345
- };
346
- }
347
- },
348
- getTransactions: async (params) => {
349
- if (!params.publicKeys && !params.txIds) {
350
- return {
351
- error: "bad_arguments",
352
- error_description: "Either publicKeys or txIds must be provided."
353
- };
354
- }
355
- try {
356
- const txIds = new Set(params.txIds || []);
357
- const publicKeys = new Set(params.publicKeys || []);
358
- const transactions = [];
359
- for await (const key of this.dfns.iterateKeys()) {
360
- if (params.publicKeys && !publicKeys.has(key.publicKey)) {
361
- continue;
362
- }
363
- for await (const sig of this.dfns.listSignatures(
364
- key.id
365
- )) {
366
- if (params.txIds && !txIds.has(sig.id)) continue;
367
- transactions.push(toTransaction(sig, key.publicKey));
368
- if (params.txIds && !params.publicKeys && transactions.length === txIds.size) {
369
- return { transactions };
370
- }
371
- }
372
- }
373
- return { transactions };
374
- } catch (error) {
375
- return {
376
- error: "fetch_error",
377
- error_description: error.message
378
- };
379
- }
380
- },
381
- getKeys: async () => {
382
- try {
383
- const keys = await this.dfns.listKeys();
384
- return {
385
- keys: keys.map((k) => ({
386
- id: k.id,
387
- name: k.name,
388
- publicKey: k.publicKey
389
- }))
390
- };
391
- } catch (error) {
392
- return {
393
- error: "fetch_error",
394
- error_description: error.message
395
- };
396
- }
397
- },
398
- createKey: async (params) => {
399
- try {
400
- const key = await this.dfns.createKey(params.name);
401
- return {
402
- id: key.id,
403
- name: key.name,
404
- publicKey: key.publicKey
405
- };
406
- } catch (error) {
407
- return {
408
- error: "creation_error",
409
- error_description: error.message
410
- };
411
- }
412
- },
413
- getConfiguration: async () => ({
414
- orgId: this.config.orgId,
415
- baseUrl: this.config.baseUrl,
416
- credentials: this.config.credentials
417
- }),
418
- setConfiguration: async (params) => {
419
- const validated = DfnsConfigSchema.safeParse(params);
420
- if (!validated.success) {
421
- return {
422
- error: "bad_arguments",
423
- error_description: validated.error.message
424
- };
425
- }
426
- const newConfig = {
427
- orgId: validated.data.orgId,
428
- baseUrl: validated.data.baseUrl,
429
- credentials: validated.data.credentials
430
- };
431
- if (!___default.default.isEqual(newConfig, this.config)) {
432
- this.config = newConfig;
433
- this.dfns = createDfnsHandler(this.config);
434
- }
435
- return params;
436
- },
437
- // TODO remove comment below and write a test once / if ever implemented
438
- // v8 ignore next -- @preserve
439
- subscribeTransactions: async (_params) => {
440
- return Promise.resolve({});
441
- },
442
- // TODO remove comment below and write a test once implemented
443
- // v8 ignore next -- @preserve
444
- signMessage: function() {
445
- throw new Error("Function not implemented.");
446
- }
447
- }));
448
- this.config = config;
449
- this.dfns = createDfnsHandler(config);
450
- }
451
- async resolveKeyId(keyIdentifier) {
452
- if (keyIdentifier.id) return keyIdentifier.id;
453
- if (!keyIdentifier.publicKey) return void 0;
454
- const key = await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey);
455
- return key?.id;
456
- }
325
+ constructor(config) {
326
+ _defineProperty(this, "dfns", void 0);
327
+ _defineProperty(this, "config", void 0);
328
+ _defineProperty(this, "partyMode", _canton_network_core_signing_lib.PartyMode.EXTERNAL);
329
+ _defineProperty(this, "signingProvider", _canton_network_core_signing_lib.SigningProvider.DFNS);
330
+ _defineProperty(this, "controller", (_userId) => (0, _canton_network_core_signing_lib.buildController)({
331
+ signTransaction: async (params) => {
332
+ try {
333
+ const keyId = await this.resolveKeyId(params.keyIdentifier);
334
+ if (!keyId) return {
335
+ error: "key_not_found",
336
+ error_description: "No Dfns key found for the provided key identifier."
337
+ };
338
+ if (!params.txHash) return {
339
+ error: "bad_arguments",
340
+ error_description: "txHash is required to sign with Dfns."
341
+ };
342
+ return toTransaction(await this.dfns.signHash(keyId, params.txHash, params.internalTxId), params.keyIdentifier.publicKey);
343
+ } catch (error) {
344
+ return {
345
+ error: "signing_error",
346
+ error_description: error.message
347
+ };
348
+ }
349
+ },
350
+ getTransaction: async (params) => {
351
+ try {
352
+ const sig = await this.dfns.findSignature(params.txId);
353
+ if (!sig) return {
354
+ error: "transaction_not_found",
355
+ error_description: "The requested signature does not exist."
356
+ };
357
+ return toTransaction(sig, (await this.dfns.getKey(sig.keyId))?.publicKey);
358
+ } catch (error) {
359
+ return {
360
+ error: "fetch_error",
361
+ error_description: error.message
362
+ };
363
+ }
364
+ },
365
+ getTransactions: async (params) => {
366
+ if (!params.publicKeys && !params.txIds) return {
367
+ error: "bad_arguments",
368
+ error_description: "Either publicKeys or txIds must be provided."
369
+ };
370
+ try {
371
+ const txIds = new Set(params.txIds || []);
372
+ const publicKeys = new Set(params.publicKeys || []);
373
+ const transactions = [];
374
+ for await (const key of this.dfns.iterateKeys()) {
375
+ if (params.publicKeys && !publicKeys.has(key.publicKey)) continue;
376
+ for await (const sig of this.dfns.listSignatures(key.id)) {
377
+ if (params.txIds && !txIds.has(sig.id)) continue;
378
+ transactions.push(toTransaction(sig, key.publicKey));
379
+ if (params.txIds && !params.publicKeys && transactions.length === txIds.size) return { transactions };
380
+ }
381
+ }
382
+ return { transactions };
383
+ } catch (error) {
384
+ return {
385
+ error: "fetch_error",
386
+ error_description: error.message
387
+ };
388
+ }
389
+ },
390
+ getKeys: async () => {
391
+ try {
392
+ return { keys: (await this.dfns.listKeys()).map((k) => ({
393
+ id: k.id,
394
+ name: k.name,
395
+ publicKey: k.publicKey
396
+ })) };
397
+ } catch (error) {
398
+ return {
399
+ error: "fetch_error",
400
+ error_description: error.message
401
+ };
402
+ }
403
+ },
404
+ createKey: async (params) => {
405
+ try {
406
+ const key = await this.dfns.createKey(params.name);
407
+ return {
408
+ id: key.id,
409
+ name: key.name,
410
+ publicKey: key.publicKey
411
+ };
412
+ } catch (error) {
413
+ return {
414
+ error: "creation_error",
415
+ error_description: error.message
416
+ };
417
+ }
418
+ },
419
+ getConfiguration: async () => ({
420
+ orgId: this.config.orgId,
421
+ baseUrl: this.config.baseUrl,
422
+ credentials: this.config.credentials
423
+ }),
424
+ setConfiguration: async (params) => {
425
+ const validated = DfnsConfigSchema.safeParse(params);
426
+ if (!validated.success) return {
427
+ error: "bad_arguments",
428
+ error_description: validated.error.message
429
+ };
430
+ const newConfig = {
431
+ orgId: validated.data.orgId,
432
+ baseUrl: validated.data.baseUrl,
433
+ credentials: validated.data.credentials
434
+ };
435
+ if (!lodash.default.isEqual(newConfig, this.config)) {
436
+ this.config = newConfig;
437
+ this.dfns = createDfnsHandler(this.config);
438
+ }
439
+ return params;
440
+ },
441
+ // v8 ignore next -- @preserve
442
+ subscribeTransactions: async (_params) => {
443
+ return Promise.resolve({});
444
+ },
445
+ // v8 ignore next -- @preserve
446
+ signMessage: function() {
447
+ throw new Error("Function not implemented.");
448
+ }
449
+ }));
450
+ this.config = config;
451
+ this.dfns = createDfnsHandler(config);
452
+ }
453
+ async resolveKeyId(keyIdentifier) {
454
+ if (keyIdentifier.id) return keyIdentifier.id;
455
+ if (!keyIdentifier.publicKey) return void 0;
456
+ return (await this.dfns.findKeyByPublicKey(keyIdentifier.publicKey))?.id;
457
+ }
457
458
  };
458
-
459
+ //#endregion
459
460
  exports.DfnsHandler = DfnsHandler;
460
461
  exports.default = DfnsSigningDriver;
461
- //# sourceMappingURL=index.cjs.map
462
+
462
463
  //# sourceMappingURL=index.cjs.map