dash-platform-sdk 1.6.0-dev.2 → 1.6.0-dev.4

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.
Files changed (125) hide show
  1. package/README.md +33 -15
  2. package/bundle.min.js +1 -1
  3. package/index.d.ts +3 -1
  4. package/index.js +2 -1
  5. package/package.json +2 -2
  6. package/proto/generated/platform.client.d.ts +10 -0
  7. package/proto/generated/platform.client.js +27 -20
  8. package/proto/generated/platform.d.ts +350 -2
  9. package/proto/generated/platform.js +737 -8
  10. package/src/DashPlatformSDK.d.ts +19 -1
  11. package/src/DashPlatformSDK.js +28 -10
  12. package/src/QueryExecutor.d.ts +122 -0
  13. package/src/QueryExecutor.js +205 -0
  14. package/src/constants.d.ts +6 -0
  15. package/src/constants.js +6 -0
  16. package/src/contestedResources/getContestedResourceVoteState.d.ts +2 -1
  17. package/src/contestedResources/getContestedResourceVoteState.js +69 -49
  18. package/src/contestedResources/getVotePollsByEndDate.d.ts +4 -0
  19. package/src/contestedResources/getVotePollsByEndDate.js +39 -0
  20. package/src/contestedResources/index.d.ts +16 -2
  21. package/src/contestedResources/index.js +19 -2
  22. package/src/dataContracts/getDataContractByIdentifier.d.ts +2 -1
  23. package/src/dataContracts/getDataContractByIdentifier.js +15 -27
  24. package/src/dataContracts/index.d.ts +4 -1
  25. package/src/dataContracts/index.js +5 -2
  26. package/src/documents/getActionFeeAgreement.d.ts +2 -1
  27. package/src/documents/getActionFeeAgreement.js +3 -3
  28. package/src/documents/index.d.ts +12 -8
  29. package/src/documents/index.js +16 -13
  30. package/src/documents/query.d.ts +2 -1
  31. package/src/documents/query.js +16 -8
  32. package/src/documents/queryAggregate.d.ts +8 -1
  33. package/src/documents/queryAggregate.js +49 -15
  34. package/src/documents/queryJoined.d.ts +3 -2
  35. package/src/documents/queryJoined.js +54 -13
  36. package/src/documents/queryRanked.d.ts +3 -2
  37. package/src/documents/queryRanked.js +49 -15
  38. package/src/documents/v1.d.ts +25 -8
  39. package/src/documents/v1.js +50 -14
  40. package/src/grpcConnectionPool.d.ts +30 -4
  41. package/src/grpcConnectionPool.js +169 -39
  42. package/src/identities/getIdentityBalance.d.ts +2 -1
  43. package/src/identities/getIdentityBalance.js +13 -27
  44. package/src/identities/getIdentityByIdentifier.d.ts +2 -1
  45. package/src/identities/getIdentityByIdentifier.js +14 -28
  46. package/src/identities/getIdentityByNonUniquePublicKeyHash.d.ts +2 -1
  47. package/src/identities/getIdentityByNonUniquePublicKeyHash.js +49 -28
  48. package/src/identities/getIdentityByPublicKeyHash.d.ts +2 -1
  49. package/src/identities/getIdentityByPublicKeyHash.js +14 -28
  50. package/src/identities/getIdentityContractNonce.d.ts +2 -1
  51. package/src/identities/getIdentityContractNonce.js +10 -27
  52. package/src/identities/getIdentityNonce.d.ts +2 -1
  53. package/src/identities/getIdentityNonce.js +10 -27
  54. package/src/identities/getIdentityPublicKeys.d.ts +2 -1
  55. package/src/identities/getIdentityPublicKeys.js +16 -29
  56. package/src/identities/index.d.ts +4 -1
  57. package/src/identities/index.js +11 -8
  58. package/src/names/index.d.ts +4 -1
  59. package/src/names/index.js +8 -5
  60. package/src/names/registerName.d.ts +2 -1
  61. package/src/names/registerName.js +4 -4
  62. package/src/names/searchByIdentity.d.ts +2 -1
  63. package/src/names/searchByIdentity.js +2 -2
  64. package/src/names/searchByName.d.ts +2 -1
  65. package/src/names/searchByName.js +2 -2
  66. package/src/node/epochInfos.d.ts +2 -1
  67. package/src/node/epochInfos.js +27 -31
  68. package/src/node/finalizedEpochInfos.d.ts +4 -3
  69. package/src/node/finalizedEpochInfos.js +45 -39
  70. package/src/node/index.d.ts +4 -1
  71. package/src/node/index.js +7 -4
  72. package/src/node/totalCredits.d.ts +2 -1
  73. package/src/node/totalCredits.js +10 -25
  74. package/src/platformAddresses/getAddressInfo.d.ts +2 -1
  75. package/src/platformAddresses/getAddressInfo.js +17 -31
  76. package/src/platformAddresses/getAddressesBranchState.d.ts +2 -1
  77. package/src/platformAddresses/getAddressesBranchState.js +22 -8
  78. package/src/platformAddresses/getAddressesInfos.d.ts +2 -1
  79. package/src/platformAddresses/getAddressesInfos.js +18 -29
  80. package/src/platformAddresses/getAddressesTrunkState.d.ts +2 -1
  81. package/src/platformAddresses/getAddressesTrunkState.js +25 -23
  82. package/src/platformAddresses/getRecentAddressBalanceChanges.d.ts +2 -1
  83. package/src/platformAddresses/getRecentAddressBalanceChanges.js +26 -26
  84. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.d.ts +2 -1
  85. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.js +30 -26
  86. package/src/platformAddresses/index.d.ts +4 -1
  87. package/src/platformAddresses/index.js +10 -7
  88. package/src/quorumKeyProvider.d.ts +23 -0
  89. package/src/quorumKeyProvider.js +28 -0
  90. package/src/shielded/getMostRecentShieldedAnchor.d.ts +2 -1
  91. package/src/shielded/getMostRecentShieldedAnchor.js +8 -25
  92. package/src/shielded/getShieldedAnchors.d.ts +2 -1
  93. package/src/shielded/getShieldedAnchors.js +8 -25
  94. package/src/shielded/getShieldedEncryptedNotes.d.ts +2 -1
  95. package/src/shielded/getShieldedEncryptedNotes.js +16 -30
  96. package/src/shielded/getShieldedNotesCount.d.ts +2 -1
  97. package/src/shielded/getShieldedNotesCount.js +8 -25
  98. package/src/shielded/getShieldedNullifiers.d.ts +2 -1
  99. package/src/shielded/getShieldedNullifiers.js +14 -28
  100. package/src/shielded/getShieldedPoolState.d.ts +2 -1
  101. package/src/shielded/getShieldedPoolState.js +8 -25
  102. package/src/shielded/index.d.ts +4 -1
  103. package/src/shielded/index.js +10 -7
  104. package/src/stateTransitions/index.d.ts +4 -1
  105. package/src/stateTransitions/index.js +5 -2
  106. package/src/stateTransitions/waitForStateTransitionResult.d.ts +2 -1
  107. package/src/stateTransitions/waitForStateTransitionResult.js +42 -44
  108. package/src/tokens/getIdentitiesTokenBalances.d.ts +2 -1
  109. package/src/tokens/getIdentitiesTokenBalances.js +17 -28
  110. package/src/tokens/getIdentityTokensBalances.d.ts +2 -1
  111. package/src/tokens/getIdentityTokensBalances.js +17 -28
  112. package/src/tokens/getTokenContractInfo.d.ts +2 -1
  113. package/src/tokens/getTokenContractInfo.js +16 -30
  114. package/src/tokens/getTokenDirectPurchasePrices.d.ts +2 -1
  115. package/src/tokens/getTokenDirectPurchasePrices.js +26 -28
  116. package/src/tokens/getTokenTotalSupply.d.ts +2 -1
  117. package/src/tokens/getTokenTotalSupply.js +16 -28
  118. package/src/tokens/index.d.ts +4 -1
  119. package/src/tokens/index.js +11 -8
  120. package/src/utils/ProofError.d.ts +9 -0
  121. package/src/utils/ProofError.js +10 -0
  122. package/src/utils/verifyTenderdashProof.js +2 -1
  123. package/test/unit/SDK.spec.js +42 -0
  124. package/src/utils/getQuorumPublicKey.d.ts +0 -1
  125. package/src/utils/getQuorumPublicKey.js +0 -19
@@ -2,10 +2,14 @@ import { GrpcWebFetchTransport } from '@protobuf-ts/grpcweb-transport';
2
2
  import { PlatformClient } from '../proto/generated/platform.client.js';
3
3
  import { GetStatusRequest } from '../proto/generated/platform.js';
4
4
  import getCurrentQuorumsInfo from './node/getCurrentQuorumsInfo.js';
5
- import getRandomArrayItem from './utils/getRandomArrayItem.js';
6
5
  import { fetchWithDetails } from './utils/fetchWithDetails.js';
7
6
  import { LATEST_PLATFORM_VERSION } from './constants.js';
7
+ import sleep from './utils/sleep.js';
8
8
  const GRPC_DEFAULT_POOL_LIMIT = 15;
9
+ const GRPC_DEFAULT_CONNECT_RETRIES = 5;
10
+ // first ban lasts 60 seconds, every next ban without a successful request in between lasts e times longer
11
+ const NODE_BASE_BAN_PERIOD_MS = 60 * 1000;
12
+ const RETRY_DELAY_MS = 10;
9
13
  const seedNodes = {
10
14
  testnet: [
11
15
  // seed-1.pshenmic.dev
@@ -45,11 +49,28 @@ const DAPI_PORTS = {
45
49
  const HEALTHCHECK_TIMEOUT_MS = 5000;
46
50
  // platform produces empty blocks every 3 minutes, so a healthy chain is never older than that
47
51
  const HEALTHCHECK_MAX_BLOCK_AGE_MS = 10 * 60 * 1000;
48
- export const createClient = (url, abortController) => {
52
+ const isAbortError = (error) => error instanceof Error && error.name === 'AbortError';
53
+ // errors raised before the request is sent to the node, so it is always safe to send it to another node
54
+ const CONNECT_ERROR_CODES = ['UND_ERR_CONNECT_TIMEOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EHOSTDOWN', 'ENETDOWN'];
55
+ /**
56
+ * Checks if the error (or one of its causes) means that the connection to the node could not be established
57
+ */
58
+ const isConnectError = (error) => {
59
+ if (!(error instanceof Error)) {
60
+ return false;
61
+ }
62
+ const { code } = error;
63
+ // ECONNRESET is a connect error only if the connection was reset during the TLS handshake,
64
+ // otherwise it may happen after the request was sent
65
+ return CONNECT_ERROR_CODES.includes(String(code)) ||
66
+ (code === 'ECONNRESET' && error.message.includes('before secure TLS connection was established')) ||
67
+ isConnectError(error.cause);
68
+ };
69
+ export const createClient = (url, abortController, fetch = fetchWithDetails) => {
49
70
  return new PlatformClient(new GrpcWebFetchTransport({
50
71
  baseUrl: url,
51
72
  abort: abortController?.signal,
52
- fetch: fetchWithDetails
73
+ fetch
53
74
  }));
54
75
  };
55
76
  /**
@@ -65,7 +86,7 @@ const withTimeout = async (request, timeoutMs = HEALTHCHECK_TIMEOUT_MS) => {
65
86
  clearTimeout(timeout);
66
87
  }
67
88
  };
68
- const isNodeHealthy = async (url) => {
89
+ const isNodeHealthy = async (url, minProtocolVersion) => {
69
90
  try {
70
91
  const response = await withTimeout(async (abortController) => {
71
92
  const { response } = await createClient(url, abortController).getStatus(GetStatusRequest.create({}));
@@ -82,7 +103,15 @@ const isNodeHealthy = async (url) => {
82
103
  // node runs a protocol version that is not supported by the SDK
83
104
  // (e.g. newer software with incompatible proofs / responses)
84
105
  const protocol = version?.protocol?.drive;
85
- if (protocol == null || protocol.current !== Number(LATEST_PLATFORM_VERSION) || protocol?.latest !== Number(LATEST_PLATFORM_VERSION)) {
106
+ if (protocol == null) {
107
+ return false;
108
+ }
109
+ if (minProtocolVersion == null) {
110
+ if (protocol.current !== Number(LATEST_PLATFORM_VERSION) || protocol.latest !== Number(LATEST_PLATFORM_VERSION)) {
111
+ return false;
112
+ }
113
+ }
114
+ else if (protocol.current < minProtocolVersion || protocol.current > Number(LATEST_PLATFORM_VERSION)) {
86
115
  return false;
87
116
  }
88
117
  // chain is stalled, last block is too old relative to the node's own clock
@@ -111,30 +140,46 @@ export default class GRPCConnectionPool {
111
140
  network;
112
141
  #poolLimit;
113
142
  #dapiUrl;
143
+ #minProtocolVersion;
144
+ retries;
145
+ proofs;
146
+ #nodeIndex = 0;
114
147
  #initialization;
148
+ // ban state of nodes that failed with a retryable error, banned nodes are skipped on node selection
149
+ #bans = new Map();
150
+ // node that served (or is serving) the request of the client
151
+ #clientNodes = new WeakMap();
115
152
  constructor(network, grpcOptions) {
153
+ const retries = grpcOptions?.retries ?? GRPC_DEFAULT_CONNECT_RETRIES;
154
+ if (!Number.isInteger(retries) || retries < 0) {
155
+ throw new Error(`GRPC retries must be a non-negative integer, got ${String(retries)}`);
156
+ }
157
+ const minProtocolVersion = grpcOptions?.minProtocolVersion;
158
+ if (minProtocolVersion != null && (!Number.isInteger(minProtocolVersion) || minProtocolVersion < 1 || minProtocolVersion > Number(LATEST_PLATFORM_VERSION))) {
159
+ throw new Error(`GRPC minProtocolVersion must be an integer from 1 to ${Number(LATEST_PLATFORM_VERSION)}, got ${String(minProtocolVersion)}`);
160
+ }
161
+ this.#minProtocolVersion = minProtocolVersion;
116
162
  this.network = network;
117
163
  this.#poolLimit = grpcOptions?.poolLimit ?? GRPC_DEFAULT_POOL_LIMIT;
118
164
  this.#dapiUrl = grpcOptions?.dapiUrl;
165
+ this.retries = retries;
119
166
  // start initialization in the background, failures are reported on the first request
120
- this.#initialization = this._initialize(network, this.#poolLimit, this.#dapiUrl);
167
+ this.#initialization = this.#initializePool();
121
168
  this.#initialization.catch(() => { });
122
169
  }
123
- async _initialize(network, poolLimit, dapiUrl) {
124
- if (typeof dapiUrl === 'string') {
125
- this.dapiUrls = [dapiUrl];
126
- return;
127
- }
128
- if (Array.isArray(dapiUrl)) {
129
- this.dapiUrls = [...new Set(dapiUrl)];
170
+ async #initializePool() {
171
+ const { network } = this;
172
+ if (this.#dapiUrl != null) {
173
+ if (typeof this.#dapiUrl !== 'string' && !Array.isArray(this.#dapiUrl)) {
174
+ throw new Error('Unrecognized DAPI URL');
175
+ }
176
+ // trailing slash is removed, so the GRPC method path can be appended to the url
177
+ this.dapiUrls = [...new Set([this.#dapiUrl].flat().map(url => url.replace(/\/+$/, '')))];
130
178
  if (this.dapiUrls.length === 0) {
131
179
  throw new Error('DAPI URL list is empty');
132
180
  }
133
181
  return;
134
182
  }
135
- if (dapiUrl != null) {
136
- throw new Error('Unrecognized DAPI URL');
137
- }
138
183
  let quorumsInfo;
139
184
  const errors = [];
140
185
  for (const seed of seedNodes[network]) {
@@ -153,37 +198,27 @@ export default class GRPCConnectionPool {
153
198
  const networkDAPIUrls = shuffle([...new Set(quorumsInfo.validatorSets
154
199
  .flatMap(validatorSet => validatorSet.members)
155
200
  .filter(member => !member.isBanned)
156
- .map(member => `https://${member.nodeIp}:${DAPI_PORTS[network]}`))])
157
- .filter(url => !this.dapiUrls.includes(url));
201
+ .map(member => `https://${member.nodeIp}:${DAPI_PORTS[network]}`))]);
158
202
  // healthcheck nodes in parallel batches until the pool is full
159
- for (let i = 0; i < networkDAPIUrls.length && this.dapiUrls.length < poolLimit; i += poolLimit) {
160
- const batch = networkDAPIUrls.slice(i, i + poolLimit);
161
- await Promise.all(batch.map(async (url) => {
162
- if (await isNodeHealthy(url)) {
163
- this.#addNode(url, poolLimit);
164
- }
165
- }));
203
+ const dapiUrls = [];
204
+ for (let i = 0; i < networkDAPIUrls.length && dapiUrls.length < this.#poolLimit; i += this.#poolLimit) {
205
+ const batch = networkDAPIUrls.slice(i, i + this.#poolLimit);
206
+ const healthy = await Promise.all(batch.map(async (url) => await isNodeHealthy(url, this.#minProtocolVersion)));
207
+ dapiUrls.push(...batch.filter((_, j) => healthy[j]));
166
208
  }
167
209
  // fail the initialization, so it is retried on the next request
168
- if (this.dapiUrls.length === 0) {
210
+ if (dapiUrls.length === 0) {
169
211
  throw new Error(`None of the ${network} evonodes are available (${networkDAPIUrls.length} checked, ` +
170
- `nodes must be synced and run protocol version ${Number(LATEST_PLATFORM_VERSION)})`);
171
- }
172
- }
173
- /**
174
- * Adds a node to the pool, unless it is already there or the pool is full
175
- */
176
- #addNode(url, poolLimit) {
177
- if (!this.dapiUrls.includes(url) && this.dapiUrls.length < poolLimit) {
178
- this.dapiUrls.push(url);
212
+ `nodes must be synced and run protocol version ${this.#minProtocolVersion != null ? `${this.#minProtocolVersion}-` : ''}${Number(LATEST_PLATFORM_VERSION)})`);
179
213
  }
214
+ this.dapiUrls = dapiUrls.slice(0, this.#poolLimit);
180
215
  }
181
216
  /**
182
- * Waits for the pool initialization and returns a client connected to a random healthy node
217
+ * Waits for the pool initialization and returns a client connected to the next healthy node (round-robin)
183
218
  */
184
219
  async getClient(abortController) {
185
220
  // retry initialization if the previous attempt failed
186
- this.#initialization ??= this._initialize(this.network, this.#poolLimit, this.#dapiUrl);
221
+ this.#initialization ??= this.#initializePool();
187
222
  const initialization = this.#initialization;
188
223
  try {
189
224
  await initialization;
@@ -195,7 +230,102 @@ export default class GRPCConnectionPool {
195
230
  }
196
231
  throw e;
197
232
  }
198
- const dapiUrl = getRandomArrayItem(this.dapiUrls);
199
- return createClient(dapiUrl, abortController);
233
+ if (this.dapiUrls.length === 0) {
234
+ throw new Error('DAPI URL list is empty');
235
+ }
236
+ const dapiUrl = this.#nextNode();
237
+ if (dapiUrl == null) {
238
+ throw new Error(`All ${this.dapiUrls.length} DAPI nodes are temporarily banned, no available nodes to send the request to`);
239
+ }
240
+ const client = createClient(dapiUrl, abortController, this.#createFetchWithRetry(dapiUrl, url => this.#clientNodes.set(client, url)));
241
+ this.#clientNodes.set(client, dapiUrl);
242
+ return client;
243
+ }
244
+ /**
245
+ * Bans the node that served the request of the client, e.g. when it returned an invalid proof.
246
+ * The first ban lasts 60 seconds, every next ban lasts e times longer, until the node is unbanned
247
+ */
248
+ banNode(client) {
249
+ const url = this.#clientNodes.get(client);
250
+ if (url != null) {
251
+ this.#ban(url);
252
+ }
253
+ }
254
+ /**
255
+ * Unbans the node that served the request of the client and resets its ban period,
256
+ * should be called once the response of the node was successfully verified
257
+ */
258
+ unbanNode(client) {
259
+ const url = this.#clientNodes.get(client);
260
+ if (url != null) {
261
+ this.#bans.delete(url);
262
+ }
263
+ }
264
+ #ban(url) {
265
+ // a single node is never banned, otherwise the pool would have no nodes to send requests to
266
+ if (this.dapiUrls.length <= 1) {
267
+ return;
268
+ }
269
+ const bannedTimes = this.#bans.get(url)?.bannedTimes ?? 0;
270
+ this.#bans.set(url, {
271
+ bannedTimes: bannedTimes + 1,
272
+ bannedUntil: Date.now() + NODE_BASE_BAN_PERIOD_MS * Math.exp(bannedTimes)
273
+ });
274
+ }
275
+ #isBanned(url) {
276
+ const ban = this.#bans.get(url);
277
+ return ban != null && ban.bannedUntil > Date.now();
278
+ }
279
+ /**
280
+ * Returns the next node from the pool in round-robin order, skipping the excluded and banned nodes.
281
+ * Every request and every retry moves to the next node, so the load is spread evenly
282
+ */
283
+ #nextNode(exclude = []) {
284
+ for (let i = 0; i < this.dapiUrls.length; i++) {
285
+ // index+1 and drop to 0 when #nodeIndex == this.dapiUrls.length
286
+ const url = this.dapiUrls[this.#nodeIndex++ % this.dapiUrls.length];
287
+ if (!exclude.includes(url) && !this.#isBanned(url)) {
288
+ return url;
289
+ }
290
+ }
291
+ return undefined;
292
+ }
293
+ /**
294
+ * Creates a fetch for the client of the given node, that retries the request
295
+ * on other nodes from the pool if it failed with a network error.
296
+ * The failed node is banned, `onNodeChange` is called with the node the request is retried on
297
+ */
298
+ #createFetchWithRetry(dapiUrl, onNodeChange) {
299
+ return async (input, init) => {
300
+ // transport always requests `${dapiUrl}/${service}/${method}`
301
+ const methodPath = String(input).slice(dapiUrl.length);
302
+ const triedUrls = [dapiUrl];
303
+ let nodeUrl = dapiUrl;
304
+ for (let retry = 0;; retry++) {
305
+ try {
306
+ return await fetchWithDetails(`${nodeUrl}${methodPath}`, init);
307
+ }
308
+ catch (e) {
309
+ // state transition could already be received by the node,
310
+ // so broadcast is retried only if the connection was not established
311
+ const isRetryable = methodPath.includes('broadcast') ? isConnectError(e) : !isAbortError(e);
312
+ if (!isRetryable || init?.signal?.aborted === true) {
313
+ throw e;
314
+ }
315
+ this.#ban(nodeUrl);
316
+ if (retry >= this.retries) {
317
+ throw e;
318
+ }
319
+ await sleep(RETRY_DELAY_MS);
320
+ const nextUrl = init?.signal?.aborted !== true ? this.#nextNode(triedUrls) : undefined;
321
+ if (nextUrl == null) {
322
+ throw e;
323
+ }
324
+ triedUrls.push(nextUrl);
325
+ nodeUrl = nextUrl;
326
+ onNodeChange(nextUrl);
327
+ }
328
+ }
329
+ };
200
330
  }
201
331
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentifierLike } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityBalance(grpcPool: GRPCPool, identifier: IdentifierLike): Promise<bigint>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityBalance(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, identifier: IdentifierLike): Promise<bigint>;
@@ -1,10 +1,8 @@
1
1
  import { GetIdentityBalanceRequest } from '../../proto/generated/platform.js';
2
2
  import { IdentifierWASM, verifyIdentityBalanceProof } from 'pshenmic-dpp';
3
- import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
4
- import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
5
- import bytesToHex from '../utils/bytesToHex.js';
3
+ import QueryExecutor from '../QueryExecutor.js';
6
4
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
7
- export default async function getIdentityBalance(grpcPool, identifier) {
5
+ export default async function getIdentityBalance(grpcPool, quorumKeyProvider, identifier) {
8
6
  const id = new IdentifierWASM(identifier);
9
7
  const getIdentityBalanceRequest = GetIdentityBalanceRequest.create({
10
8
  version: {
@@ -15,27 +13,15 @@ export default async function getIdentityBalance(grpcPool, identifier) {
15
13
  }
16
14
  }
17
15
  });
18
- const { response } = await (await grpcPool.getClient()).getIdentityBalance(getIdentityBalanceRequest);
19
- const { version } = response;
20
- if (version.oneofKind !== 'v0') {
21
- throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
- }
23
- const { v0 } = version;
24
- if (v0.result.oneofKind !== 'proof') {
25
- throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
- }
27
- const { result: { proof }, metadata } = v0;
28
- if (metadata == null) {
29
- throw new Error('Metadata not found');
30
- }
31
- const { rootHash, balance } = verifyIdentityBalanceProof(proof.grovedbProof, id.bytes(), true, LATEST_PLATFORM_VERSION);
32
- if (balance == null) {
33
- throw new Error(`Failed to fetch balance for identifier ${id.base58()}`);
34
- }
35
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
- const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
37
- if (!verify) {
38
- throw new Error('Failed to verify query');
39
- }
40
- return BigInt(balance);
16
+ return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
+ .setGrpcRequest('getIdentityBalance', getIdentityBalanceRequest)
18
+ .setProofVerifier(verifyIdentityBalanceProof, id.bytes(), true, LATEST_PLATFORM_VERSION)
19
+ .mapResponse(data => {
20
+ const balance = data.proved ? data.verified.balance : BigInt(data.result.balance);
21
+ if (balance == null) {
22
+ throw new Error(`Failed to fetch balance for identifier ${id.base58()}`);
23
+ }
24
+ return balance;
25
+ })
26
+ .execute();
41
27
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentifierLike, IdentityWASM } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityByIdentifier(grpcPool: GRPCPool, identifier: IdentifierLike): Promise<IdentityWASM>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityByIdentifier(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, identifier: IdentifierLike): Promise<IdentityWASM>;
@@ -1,10 +1,8 @@
1
1
  import { GetIdentityRequest } from '../../proto/generated/platform.js';
2
- import { IdentifierWASM, verifyIdentityByIdentifierProof } from 'pshenmic-dpp';
3
- import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
4
- import bytesToHex from '../utils/bytesToHex.js';
5
- import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
2
+ import { IdentifierWASM, IdentityWASM, verifyIdentityByIdentifierProof } from 'pshenmic-dpp';
3
+ import QueryExecutor from '../QueryExecutor.js';
6
4
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
7
- export default async function getIdentityByIdentifier(grpcPool, identifier) {
5
+ export default async function getIdentityByIdentifier(grpcPool, quorumKeyProvider, identifier) {
8
6
  const id = new IdentifierWASM(identifier);
9
7
  const getIdentityRequest = GetIdentityRequest.create({
10
8
  version: {
@@ -15,27 +13,15 @@ export default async function getIdentityByIdentifier(grpcPool, identifier) {
15
13
  }
16
14
  }
17
15
  });
18
- const { response } = await (await grpcPool.getClient()).getIdentity(getIdentityRequest);
19
- const { version } = response;
20
- if (version.oneofKind !== 'v0') {
21
- throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
- }
23
- const { v0 } = version;
24
- if (v0.result.oneofKind !== 'proof') {
25
- throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
- }
27
- const { result: { proof }, metadata } = v0;
28
- if (metadata == null) {
29
- throw new Error('Metadata not found');
30
- }
31
- const { rootHash, identity } = verifyIdentityByIdentifierProof(proof.grovedbProof, id, true, LATEST_PLATFORM_VERSION);
32
- if (identity == null) {
33
- throw new Error(`Identity with identifier ${id.base58()} not found`);
34
- }
35
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
- const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
37
- if (!verify) {
38
- throw new Error('Failed to verify query');
39
- }
40
- return identity;
16
+ return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
+ .setGrpcRequest('getIdentity', getIdentityRequest)
18
+ .setProofVerifier(verifyIdentityByIdentifierProof, id, true, LATEST_PLATFORM_VERSION)
19
+ .mapResponse(data => {
20
+ const identity = data.proved ? data.verified.identity : IdentityWASM.fromBytes(data.result.identity);
21
+ if (identity == null) {
22
+ throw new Error(`Identity with identifier ${id.base58()} not found`);
23
+ }
24
+ return identity;
25
+ })
26
+ .execute();
41
27
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentityWASM } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityByNonUniquePublicKeyHash(grpcPool: GRPCPool, hex: string): Promise<IdentityWASM>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityByNonUniquePublicKeyHash(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, hex: string): Promise<IdentityWASM>;
@@ -1,13 +1,34 @@
1
1
  import { GetIdentityByNonUniquePublicKeyHashRequest } from '../../proto/generated/platform.js';
2
- import { verifyFullIdentityByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
2
+ import { IdentityWASM, verifyFullIdentityByNonUniquePublicKeyHashProof, verifyFullIdentityByNonUniquePublicKeyHashTwoProofs } from 'pshenmic-dpp';
3
3
  import hexToBytes from '../utils/hexToBytes.js';
4
- import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
5
- import bytesToHex from '../utils/bytesToHex.js';
6
- import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
4
+ import QueryExecutor from '../QueryExecutor.js';
7
5
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
8
- export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex) {
6
+ function getNonUniquePublicKeyHashProof({ version }) {
7
+ if (version.oneofKind !== 'v0') {
8
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
9
+ }
10
+ const { result, metadata } = version.v0;
11
+ if (metadata == null) {
12
+ throw new Error('Metadata not found');
13
+ }
14
+ if (result.oneofKind === 'legacyProof') {
15
+ return { proof: result.legacyProof, metadata, twoProofs: false };
16
+ }
17
+ if (result.oneofKind !== 'proof' || result.proof.grovedbIdentityPublicKeyHashProof == null) {
18
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
19
+ }
20
+ // the quorum signature is carried by the index proof
21
+ return { proof: result.proof.grovedbIdentityPublicKeyHashProof, metadata, identityProof: result.proof.identityProofBytes, twoProofs: true };
22
+ }
23
+ function verifyNonUniquePublicKeyHashProof(proof, identityProof, twoProofs, publicKeyHash, queryPlatformVersion, platformVersion) {
24
+ return twoProofs
25
+ ? verifyFullIdentityByNonUniquePublicKeyHashTwoProofs(proof, identityProof, publicKeyHash, undefined, queryPlatformVersion, platformVersion)
26
+ : verifyFullIdentityByNonUniquePublicKeyHashProof(proof, publicKeyHash, undefined, queryPlatformVersion, platformVersion);
27
+ }
28
+ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, quorumKeyProvider, hex) {
9
29
  const getIdentityByNonUniquePublicKeyHashRequest = GetIdentityByNonUniquePublicKeyHashRequest.create({
10
30
  version: {
31
+ // v0 is supported by all nodes, v1 only since platform v5.0.0-rc.8
11
32
  oneofKind: 'v0',
12
33
  v0: {
13
34
  publicKeyHash: hexToBytes(hex),
@@ -15,27 +36,27 @@ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex)
15
36
  }
16
37
  }
17
38
  });
18
- const { response } = await (await grpcPool.getClient()).getIdentityByNonUniquePublicKeyHash(getIdentityByNonUniquePublicKeyHashRequest);
19
- const { version } = response;
20
- if (version.oneofKind !== 'v0') {
21
- throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
- }
23
- const { v0 } = version;
24
- if (v0.result.oneofKind !== 'proof') {
25
- throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
- }
27
- const { result: { proof }, metadata } = v0;
28
- if (metadata == null) {
29
- throw new Error('Metadata not found');
30
- }
31
- const { rootHash, identity } = verifyFullIdentityByNonUniquePublicKeyHashProof(proof.grovedbProof, hexToBytes(hex), undefined, metadata.protocolVersion, LATEST_PLATFORM_VERSION);
32
- if (identity == null) {
33
- throw new Error(`Identity with non unique public key hash ${hex} not found`);
34
- }
35
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
- const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
37
- if (!verify) {
38
- throw new Error('Failed to verify query');
39
- }
40
- return identity;
39
+ return await QueryExecutor.build(grpcPool, quorumKeyProvider)
40
+ .setGrpcRequest('getIdentityByNonUniquePublicKeyHash', getIdentityByNonUniquePublicKeyHashRequest)
41
+ .mapProof(getNonUniquePublicKeyHashProof)
42
+ .setProofVerifier(verifyNonUniquePublicKeyHashProof, ({ metadata, identityProof, twoProofs }) => [
43
+ identityProof,
44
+ twoProofs,
45
+ hexToBytes(hex),
46
+ metadata.protocolVersion,
47
+ LATEST_PLATFORM_VERSION
48
+ ])
49
+ .mapResponse(data => {
50
+ if (data.proved) {
51
+ if (data.verified.identity == null) {
52
+ throw new Error(`Identity with non unique public key hash ${hex} not found`);
53
+ }
54
+ return data.verified.identity;
55
+ }
56
+ if (data.result.oneofKind !== 'identity' || data.result.identity.identity == null) {
57
+ throw new Error(`Identity with non unique public key hash ${hex} not found`);
58
+ }
59
+ return IdentityWASM.fromBytes(data.result.identity.identity);
60
+ })
61
+ .execute();
41
62
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentityWASM } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityByPublicKeyHash(grpcPool: GRPCPool, hex: string): Promise<IdentityWASM>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityByPublicKeyHash(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, hex: string): Promise<IdentityWASM>;
@@ -1,11 +1,9 @@
1
1
  import { GetIdentityByPublicKeyHashRequest } from '../../proto/generated/platform.js';
2
- import { verifyIdentityByUniqueKeyHashProof } from 'pshenmic-dpp';
2
+ import { IdentityWASM, verifyIdentityByUniqueKeyHashProof } from 'pshenmic-dpp';
3
3
  import hexToBytes from '../utils/hexToBytes.js';
4
- import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
5
- import bytesToHex from '../utils/bytesToHex.js';
6
- import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
4
+ import QueryExecutor from '../QueryExecutor.js';
7
5
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
8
- export default async function getIdentityByPublicKeyHash(grpcPool, hex) {
6
+ export default async function getIdentityByPublicKeyHash(grpcPool, quorumKeyProvider, hex) {
9
7
  const getIdentityByPublicKeyHashRequest = GetIdentityByPublicKeyHashRequest.create({
10
8
  version: {
11
9
  oneofKind: 'v0',
@@ -15,27 +13,15 @@ export default async function getIdentityByPublicKeyHash(grpcPool, hex) {
15
13
  }
16
14
  }
17
15
  });
18
- const { response } = await (await grpcPool.getClient()).getIdentityByPublicKeyHash(getIdentityByPublicKeyHashRequest);
19
- const { version } = response;
20
- if (version.oneofKind !== 'v0') {
21
- throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
22
- }
23
- const { v0 } = version;
24
- if (v0.result.oneofKind !== 'proof') {
25
- throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
26
- }
27
- const { result: { proof }, metadata } = v0;
28
- if (metadata == null) {
29
- throw new Error('Metadata not found');
30
- }
31
- const { rootHash, identity } = verifyIdentityByUniqueKeyHashProof(proof.grovedbProof, hexToBytes(hex), LATEST_PLATFORM_VERSION);
32
- if (identity == null) {
33
- throw new Error(`Identity with public key hash ${hex} not found`);
34
- }
35
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
- const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
37
- if (!verify) {
38
- throw new Error('Failed to verify query');
39
- }
40
- return identity;
16
+ return await QueryExecutor.build(grpcPool, quorumKeyProvider)
17
+ .setGrpcRequest('getIdentityByPublicKeyHash', getIdentityByPublicKeyHashRequest)
18
+ .setProofVerifier(verifyIdentityByUniqueKeyHashProof, hexToBytes(hex), LATEST_PLATFORM_VERSION)
19
+ .mapResponse(data => {
20
+ const identity = data.proved ? data.verified.identity : IdentityWASM.fromBytes(data.result.identity);
21
+ if (identity == null) {
22
+ throw new Error(`Identity with public key hash ${hex} not found`);
23
+ }
24
+ return identity;
25
+ })
26
+ .execute();
41
27
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentifierLike } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityContractNonce(grpcPool: GRPCPool, identity: IdentifierLike, dataContract: IdentifierLike): Promise<bigint>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityContractNonce(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, identity: IdentifierLike, dataContract: IdentifierLike): Promise<bigint>;
@@ -1,11 +1,9 @@
1
1
  import { GetIdentityContractNonceRequest } from '../../proto/generated/platform.js';
2
2
  import { IdentifierWASM, verifyIdentityContractNonceProof } from 'pshenmic-dpp';
3
- import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
4
- import bytesToHex from '../utils/bytesToHex.js';
5
- import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
3
+ import QueryExecutor from '../QueryExecutor.js';
6
4
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
7
5
  const IDENTITY_CONTRACT_NONCE_VALUE_FILTER = BigInt(0xFFFFFFFFFF);
8
- export default async function getIdentityContractNonce(grpcPool, identity, dataContract) {
6
+ export default async function getIdentityContractNonce(grpcPool, quorumKeyProvider, identity, dataContract) {
9
7
  const identityIdentifier = new IdentifierWASM(identity);
10
8
  const dataContractIdentifier = new IdentifierWASM(dataContract);
11
9
  const getIdentityContractNonceRequest = GetIdentityContractNonceRequest.create({
@@ -18,27 +16,12 @@ export default async function getIdentityContractNonce(grpcPool, identity, dataC
18
16
  }
19
17
  }
20
18
  });
21
- const { response } = await (await grpcPool.getClient()).getIdentityContractNonce(getIdentityContractNonceRequest);
22
- const { version } = response;
23
- if (version.oneofKind !== 'v0') {
24
- throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
25
- }
26
- const { v0 } = version;
27
- if (v0.result.oneofKind !== 'proof') {
28
- throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
29
- }
30
- const { result: { proof }, metadata } = v0;
31
- if (metadata == null) {
32
- throw new Error('Metadata not found');
33
- }
34
- const { rootHash, contractNonce } = verifyIdentityContractNonceProof(proof.grovedbProof, identityIdentifier.bytes(), dataContractIdentifier.bytes(), true, LATEST_PLATFORM_VERSION);
35
- if (contractNonce == null) {
36
- return BigInt(0);
37
- }
38
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
39
- const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
40
- if (!verify) {
41
- throw new Error('Failed to verify query');
42
- }
43
- return BigInt(contractNonce) & IDENTITY_CONTRACT_NONCE_VALUE_FILTER;
19
+ return await QueryExecutor.build(grpcPool, quorumKeyProvider)
20
+ .setGrpcRequest('getIdentityContractNonce', getIdentityContractNonceRequest)
21
+ .setProofVerifier(verifyIdentityContractNonceProof, identityIdentifier.bytes(), dataContractIdentifier.bytes(), true, LATEST_PLATFORM_VERSION)
22
+ .mapResponse(data => {
23
+ const contractNonce = data.proved ? data.verified.contractNonce : BigInt(data.result.identityContractNonce);
24
+ return contractNonce != null ? contractNonce & IDENTITY_CONTRACT_NONCE_VALUE_FILTER : BigInt(0);
25
+ })
26
+ .execute();
44
27
  }
@@ -1,3 +1,4 @@
1
1
  import { IdentifierLike } from 'pshenmic-dpp';
2
2
  import { GRPCPool } from '../grpcConnectionPool.js';
3
- export default function getIdentityNonce(grpcPool: GRPCPool, identifier: IdentifierLike): Promise<bigint>;
3
+ import { QuorumKeyProvider } from '../quorumKeyProvider.js';
4
+ export default function getIdentityNonce(grpcPool: GRPCPool, quorumKeyProvider: QuorumKeyProvider, identifier: IdentifierLike): Promise<bigint>;