@canton-network/core-ledger-client 0.20.0 → 0.20.1

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,309 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
- var coreLedgerProto = require('@canton-network/core-ledger-proto');
5
- var grpcTransport = require('@protobuf-ts/grpc-transport');
6
- var grpcJs = require('@grpc/grpc-js');
7
- var fs = require('fs');
8
3
  var coreTokenStandard = require('@canton-network/core-token-standard');
4
+ var coreLedgerProto = require('@canton-network/core-ledger-proto');
9
5
  var BigNumber = require('bignumber.js');
10
6
  var createClient = require('openapi-fetch');
11
7
  var typescriptLruCache = require('typescript-lru-cache');
12
8
 
13
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
10
 
15
- var fs__default = /*#__PURE__*/_interopDefault(fs);
16
11
  var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
17
12
  var createClient__default = /*#__PURE__*/_interopDefault(createClient);
18
13
 
19
14
  var __defProp = Object.defineProperty;
20
15
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
16
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- function prefixedInt(value, bytes) {
23
- const buffer = Buffer.alloc(4 + bytes.length);
24
- buffer.writeUInt32BE(value, 0);
25
- Buffer.from(bytes).copy(buffer, 4);
26
- return buffer;
27
- }
28
- function signingPublicKeyFromEd25519(publicKey) {
29
- return {
30
- format: coreLedgerProto.CryptoKeyFormat.RAW,
31
- publicKey: Buffer.from(publicKey, "base64"),
32
- scheme: coreLedgerProto.SigningKeyScheme.ED25519,
33
- keySpec: coreLedgerProto.SigningKeySpec.EC_CURVE25519,
34
- usage: []
35
- };
36
- }
37
- function computeSha256CantonHash(purpose, bytes) {
38
- const hashInput = prefixedInt(purpose, bytes);
39
- const hash = crypto.createHash("sha256").update(hashInput).digest();
40
- const multiprefix = Buffer.from([18, 32]);
41
- return Buffer.concat([multiprefix, hash]).toString("hex");
42
- }
43
- function createGrpcTransport(options) {
44
- const { useTls = false, tls } = options;
45
- if (useTls) {
46
- const readMaybeFile = (value) => typeof value === "string" ? fs__default.default.readFileSync(value) : value;
47
- const rootCert = readMaybeFile(tls?.rootCert);
48
- const clientCert = readMaybeFile(tls?.clientCert);
49
- const clientKey = readMaybeFile(tls?.clientKey);
50
- if (tls?.mutual) {
51
- if (!clientCert || !clientKey) {
52
- throw new Error(
53
- "mTLS enabled but clientCert or clientKey are missing"
54
- );
55
- }
56
- return grpcJs.ChannelCredentials.createSsl(rootCert, clientKey, clientCert);
57
- } else {
58
- return grpcJs.ChannelCredentials.createSsl(rootCert);
59
- }
60
- } else {
61
- return grpcJs.ChannelCredentials.createInsecure();
62
- }
63
- }
64
- var TopologyWriteService = class _TopologyWriteService {
65
- constructor(synchronizerId, userAdminUrl, ledgerClient, accessToken = "", accessTokenProvider, grpcClientOptions) {
66
- this.synchronizerId = synchronizerId;
67
- __publicField(this, "topologyClient");
68
- __publicField(this, "topologyReadService");
69
- __publicField(this, "ledgerClient");
70
- __publicField(this, "accessTokenProvider");
71
- __publicField(this, "accessToken");
72
- __publicField(this, "storeId", () => coreLedgerProto.StoreId.create({
73
- store: {
74
- oneofKind: "synchronizer",
75
- synchronizer: coreLedgerProto.StoreId_Synchronizer.create({
76
- id: this.synchronizerId
77
- })
78
- }
79
- }));
80
- let transport;
81
- if (grpcClientOptions) {
82
- transport = new grpcTransport.GrpcTransport({
83
- host: userAdminUrl,
84
- channelCredentials: createGrpcTransport(grpcClientOptions)
85
- });
86
- } else {
87
- transport = new grpcTransport.GrpcTransport({
88
- host: userAdminUrl,
89
- channelCredentials: grpcJs.ChannelCredentials.createInsecure()
90
- });
91
- }
92
- this.topologyClient = new coreLedgerProto.TopologyManagerWriteServiceClient(transport);
93
- this.topologyReadService = new coreLedgerProto.TopologyManagerReadServiceClient(
94
- transport
95
- );
96
- this.ledgerClient = ledgerClient;
97
- this.accessTokenProvider = accessTokenProvider;
98
- this.accessToken = accessToken;
99
- }
100
- static combineHashes(hashes) {
101
- const sortedHashes = hashes.sort(
102
- (a, b) => a.toString("hex").localeCompare(b.toString("hex"))
103
- );
104
- const combinedHashes = Buffer.alloc(4);
105
- combinedHashes.writeUInt32BE(sortedHashes.length, 0);
106
- let concatenatedHashes = combinedHashes;
107
- for (const h of sortedHashes) {
108
- const lengthBuffer = Buffer.alloc(4);
109
- lengthBuffer.writeUInt32BE(h.length, 0);
110
- concatenatedHashes = Buffer.concat([
111
- concatenatedHashes,
112
- lengthBuffer,
113
- h
114
- ]);
115
- }
116
- const predefineHashPurpose = computeSha256CantonHash(
117
- 55,
118
- concatenatedHashes
119
- );
120
- return Buffer.from(predefineHashPurpose, "hex").toString("base64");
121
- }
122
- static createFingerprintFromKey(publicKey) {
123
- let key;
124
- if (typeof publicKey === "string") {
125
- key = signingPublicKeyFromEd25519(publicKey);
126
- } else {
127
- key = publicKey;
128
- }
129
- const hashPurpose = 12;
130
- return computeSha256CantonHash(hashPurpose, key.publicKey);
131
- }
132
- /** @deprecated only for grpc/protobuf implementation */
133
- static toSignedTopologyTransaction(txHashes, serializedTransaction, signature, namespace) {
134
- return coreLedgerProto.SignedTopologyTransaction.create({
135
- transaction: serializedTransaction,
136
- proposal: true,
137
- signatures: [],
138
- multiTransactionSignatures: [
139
- coreLedgerProto.MultiTransactionSignatures.create({
140
- transactionHashes: txHashes,
141
- signatures: [
142
- coreLedgerProto.Signature.create({
143
- format: coreLedgerProto.SignatureFormat.RAW,
144
- signature: Buffer.from(signature, "base64"),
145
- signedBy: namespace,
146
- signingAlgorithmSpec: coreLedgerProto.SigningAlgorithmSpec.ED25519
147
- })
148
- ]
149
- })
150
- ]
151
- });
152
- }
153
- /** @deprecated */
154
- generateTransactionsRequest(namespace, partyId, publicKey, confirmingThreshold = 1, hostingParticipantRights) {
155
- const namespaceDelegation = coreLedgerProto.TopologyMapping.create({
156
- mapping: {
157
- oneofKind: "namespaceDelegation",
158
- namespaceDelegation: coreLedgerProto.NamespaceDelegation.create({
159
- namespace,
160
- targetKey: publicKey,
161
- isRootDelegation: true,
162
- restriction: {
163
- oneofKind: void 0
164
- }
165
- })
166
- }
167
- });
168
- const hostingParticipants = [...hostingParticipantRights].map(
169
- ([participantUid, permission]) => coreLedgerProto.PartyToParticipant_HostingParticipant.create({
170
- participantUid,
171
- permission
172
- })
173
- );
174
- const partyToParticipant = coreLedgerProto.TopologyMapping.create({
175
- mapping: {
176
- oneofKind: "partyToParticipant",
177
- partyToParticipant: coreLedgerProto.PartyToParticipant.create({
178
- party: partyId,
179
- threshold: confirmingThreshold,
180
- participants: hostingParticipants
181
- })
182
- }
183
- });
184
- const partyToKeyMapping = coreLedgerProto.TopologyMapping.create({
185
- mapping: {
186
- oneofKind: "partyToKeyMapping",
187
- partyToKeyMapping: coreLedgerProto.PartyToKeyMapping.create({
188
- party: partyId,
189
- threshold: 1,
190
- signingKeys: [publicKey]
191
- })
192
- }
193
- });
194
- return coreLedgerProto.GenerateTransactionsRequest.create({
195
- proposals: [
196
- namespaceDelegation,
197
- partyToParticipant,
198
- partyToKeyMapping
199
- ].map(
200
- (mapping) => coreLedgerProto.GenerateTransactionsRequest_Proposal.create({
201
- mapping,
202
- serial: 1,
203
- store: this.storeId(),
204
- operation: coreLedgerProto.Enums_TopologyChangeOp.ADD_REPLACE
205
- })
206
- )
207
- });
208
- }
209
- /** @deprecated use allocateExternalParty() instead */
210
- async submitExternalPartyTopology(signedTopologyTxs, partyId) {
211
- await this.addTransactions(signedTopologyTxs);
212
- await this.authorizePartyToParticipant(partyId);
213
- }
214
- /** @deprecated use generateTopology() */
215
- async generateTransactions(publicKey, partyId, confirmingThreshold = 1, hostingParticipantRights) {
216
- const signingPublicKey = signingPublicKeyFromEd25519(publicKey);
217
- const namespace = _TopologyWriteService.createFingerprintFromKey(signingPublicKey);
218
- let participantRights = hostingParticipantRights;
219
- if (!participantRights || participantRights.size === 0) {
220
- const { participantId } = await this.ledgerClient.getWithRetry(
221
- "/v2/parties/participant-id"
222
- );
223
- participantRights = /* @__PURE__ */ new Map([
224
- [participantId, coreLedgerProto.Enums_ParticipantPermission.CONFIRMATION]
225
- ]);
226
- }
227
- const req = this.generateTransactionsRequest(
228
- namespace,
229
- partyId,
230
- signingPublicKey,
231
- confirmingThreshold,
232
- participantRights
233
- );
234
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
235
- return this.topologyClient.generateTransactions(req, {
236
- meta: {
237
- Authorization: `Bearer ${adminAccessToken}`
238
- }
239
- }).response;
240
- }
241
- /** @deprecated */
242
- async addTransactions(signedTopologyTxs) {
243
- const request = coreLedgerProto.AddTransactionsRequest.create({
244
- transactions: signedTopologyTxs,
245
- forceChanges: [],
246
- store: this.storeId()
247
- });
248
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
249
- return this.topologyClient.addTransactions(request, {
250
- meta: {
251
- Authorization: `Bearer ${adminAccessToken}`
252
- }
253
- }).response;
254
- }
255
- /** @deprecated */
256
- async waitForPartyToParticipantProposal(partyId) {
257
- let counter = 0;
258
- return new Promise((resolve, reject) => {
259
- const interval = setInterval(async () => {
260
- const result = await this.topologyReadService.listPartyToParticipant(
261
- coreLedgerProto.ListPartyToParticipantRequest.create({
262
- baseQuery: coreLedgerProto.BaseQuery.create({
263
- store: this.storeId(),
264
- proposals: true,
265
- timeQuery: {
266
- oneofKind: "headState",
267
- headState: coreLedgerProto.Empty.create()
268
- }
269
- }),
270
- filterParty: partyId
271
- })
272
- );
273
- if (result.response.results.length > 0) {
274
- clearInterval(interval);
275
- resolve(result.response.results[0].context?.transactionHash);
276
- }
277
- counter += 1;
278
- if (counter > 10) {
279
- clearInterval(interval);
280
- reject("Timeout waiting for party to participant proposal");
281
- }
282
- }, 1e3);
283
- });
284
- }
285
- /** @deprecated */
286
- async authorizePartyToParticipant(partyId) {
287
- const hash = await this.waitForPartyToParticipantProposal(partyId);
288
- if (!hash) {
289
- throw new Error("No topology transaction found for authorization");
290
- }
291
- const request = coreLedgerProto.AuthorizeRequest.create({
292
- type: {
293
- oneofKind: "transactionHash",
294
- transactionHash: Buffer.from(hash).toString("hex")
295
- },
296
- mustFullyAuthorize: false,
297
- store: this.storeId()
298
- });
299
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
300
- return this.topologyClient.authorize(request, {
301
- meta: {
302
- Authorization: `Bearer ${adminAccessToken}`
303
- }
304
- }).response;
305
- }
306
- };
307
17
  function splitInterfaceId(interfaceId) {
308
18
  const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
309
19
  const match = regExp.exec(interfaceId);
@@ -3034,7 +2744,16 @@ var ACSHelper = class _ACSHelper {
3034
2744
  // src/ledger-client.ts
3035
2745
  var supportedVersions = ["3.3", "3.4"];
3036
2746
  var LedgerClient = class {
3037
- constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2747
+ constructor({
2748
+ baseUrl,
2749
+ logger,
2750
+ isAdmin,
2751
+ accessToken,
2752
+ accessTokenProvider,
2753
+ version,
2754
+ acsHelperOptions,
2755
+ ...options
2756
+ }) {
3038
2757
  // privately manage the active connected version and associated client codegen
3039
2758
  __publicField(this, "clients");
3040
2759
  __publicField(this, "clientVersion", "3.4");
@@ -3046,38 +2765,30 @@ var LedgerClient = class {
3046
2765
  __publicField(this, "logger");
3047
2766
  __publicField(this, "synchronizerId");
3048
2767
  __publicField(this, "baseUrl");
3049
- this.logger = _logger.child({ component: "LedgerClient" });
2768
+ this.logger = logger.child({ component: "LedgerClient" });
3050
2769
  this.accessTokenProvider = accessTokenProvider;
2770
+ const baseFetch = options.fetch ?? fetch;
2771
+ const authenticatedFetch = async (url, options2 = {}) => {
2772
+ let token = accessToken;
2773
+ if (this.accessTokenProvider) {
2774
+ token = isAdmin ?? false ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2775
+ }
2776
+ return baseFetch(url, {
2777
+ ...options2,
2778
+ headers: {
2779
+ ...options2.headers || {},
2780
+ ...token && { Authorization: `Bearer ${token}` }
2781
+ }
2782
+ });
2783
+ };
3051
2784
  this.clients = {
3052
2785
  "3.3": createClient__default.default({
3053
2786
  baseUrl: baseUrl.href,
3054
- fetch: async (url, options = {}) => {
3055
- if (this.accessTokenProvider) {
3056
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3057
- }
3058
- return fetch(url, {
3059
- ...options,
3060
- headers: {
3061
- ...options.headers || {},
3062
- Authorization: `Bearer ${accessToken}`
3063
- }
3064
- });
3065
- }
2787
+ fetch: authenticatedFetch
3066
2788
  }),
3067
2789
  "3.4": createClient__default.default({
3068
2790
  baseUrl: baseUrl.href,
3069
- fetch: async (url, options = {}) => {
3070
- if (this.accessTokenProvider) {
3071
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3072
- }
3073
- return fetch(url, {
3074
- ...options,
3075
- headers: {
3076
- ...options.headers || {},
3077
- Authorization: `Bearer ${accessToken}`
3078
- }
3079
- });
3080
- }
2791
+ fetch: authenticatedFetch
3081
2792
  })
3082
2793
  };
3083
2794
  this.clientVersion = version ?? this.clientVersion;
@@ -3085,7 +2796,7 @@ var LedgerClient = class {
3085
2796
  this.baseUrl = baseUrl;
3086
2797
  this.acsHelper = new ACSHelper(
3087
2798
  this,
3088
- _logger,
2799
+ logger,
3089
2800
  acsHelperOptions,
3090
2801
  SharedACSCache
3091
2802
  );
@@ -3212,20 +2923,23 @@ var LedgerClient = class {
3212
2923
  *
3213
2924
  * @param userId The ID of the user to grant rights to.
3214
2925
  * @param partyId The ID of the party to grant rights for.
2926
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
2927
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
3215
2928
  * @returns A promise that resolves when the rights have been granted.
3216
2929
  */
3217
- async waitForPartyAndGrantUserRights(userId, partyId) {
2930
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
3218
2931
  await this.init();
3219
2932
  let partyFound = false;
3220
2933
  let tries = 0;
3221
- const maxTries = 30;
3222
2934
  while (!partyFound && tries < maxTries) {
3223
2935
  partyFound = await this.checkIfPartyExists(partyId);
3224
- await new Promise((resolve) => setTimeout(resolve, 2e3));
2936
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3225
2937
  tries++;
3226
2938
  }
3227
2939
  if (tries >= maxTries) {
3228
- throw new Error("timed out waiting for new party to appear");
2940
+ throw new Error(
2941
+ `timed out waiting for new party to appear after ${maxTries} tries`
2942
+ );
3229
2943
  }
3230
2944
  const result = await this.grantRights(userId, {
3231
2945
  actAs: [partyId]
@@ -3587,7 +3301,6 @@ exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3587
3301
  exports.CoreService = CoreService;
3588
3302
  exports.LedgerClient = LedgerClient;
3589
3303
  exports.TokenStandardService = TokenStandardService;
3590
- exports.TopologyWriteService = TopologyWriteService;
3591
3304
  exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3592
3305
  exports.asJsCantonError = asJsCantonError;
3593
3306
  exports.awaitCompletion = awaitCompletion;