dash-platform-sdk 1.5.2 → 1.6.0-dev.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.
Files changed (89) hide show
  1. package/README.md +15 -15
  2. package/bundle.min.js +1 -1
  3. package/package.json +3 -4
  4. package/proto/generated/platform.client.d.ts +20 -60
  5. package/proto/generated/platform.client.js +41 -69
  6. package/proto/generated/platform.d.ts +2330 -1650
  7. package/proto/generated/platform.js +4992 -3467
  8. package/src/DashPlatformSDK.d.ts +0 -8
  9. package/src/DashPlatformSDK.js +0 -10
  10. package/src/constants.d.ts +1 -1
  11. package/src/constants.js +1 -1
  12. package/src/contestedResources/getContestedResourceVoteState.js +1 -1
  13. package/src/dataContracts/getDataContractByIdentifier.js +1 -1
  14. package/src/documents/createStateTransition.d.ts +2 -2
  15. package/src/documents/createStateTransition.js +6 -6
  16. package/src/documents/getActionFeeAgreement.d.ts +4 -0
  17. package/src/documents/getActionFeeAgreement.js +21 -0
  18. package/src/documents/index.d.ts +97 -3
  19. package/src/documents/index.js +114 -1
  20. package/src/documents/query.js +13 -52
  21. package/src/documents/queryAggregate.d.ts +4 -0
  22. package/src/documents/queryAggregate.js +32 -0
  23. package/src/documents/queryJoined.d.ts +16 -0
  24. package/src/documents/queryJoined.js +44 -0
  25. package/src/documents/queryRanked.d.ts +12 -0
  26. package/src/documents/queryRanked.js +37 -0
  27. package/src/documents/v1.d.ts +33 -0
  28. package/src/documents/v1.js +233 -0
  29. package/src/grpcConnectionPool.d.ts +3 -6
  30. package/src/grpcConnectionPool.js +141 -47
  31. package/src/identities/getIdentityBalance.js +1 -1
  32. package/src/identities/getIdentityByIdentifier.js +1 -1
  33. package/src/identities/getIdentityByNonUniquePublicKeyHash.js +7 -11
  34. package/src/identities/getIdentityByPublicKeyHash.js +1 -1
  35. package/src/identities/getIdentityContractNonce.js +1 -1
  36. package/src/identities/getIdentityNonce.js +1 -1
  37. package/src/identities/getIdentityPublicKeys.js +1 -1
  38. package/src/node/epochInfos.js +1 -1
  39. package/src/node/finalizedEpochInfos.js +1 -1
  40. package/src/node/getCurrentQuorumsInfo.js +1 -1
  41. package/src/node/status.js +1 -1
  42. package/src/node/totalCredits.js +1 -1
  43. package/src/platformAddresses/getAddressInfo.js +1 -1
  44. package/src/platformAddresses/getAddressesBranchState.js +1 -1
  45. package/src/platformAddresses/getAddressesInfos.js +1 -1
  46. package/src/platformAddresses/getAddressesTrunkState.js +1 -1
  47. package/src/platformAddresses/getRecentAddressBalanceChanges.js +1 -1
  48. package/src/platformAddresses/getRecentCompactedAddressBalanceChanges.js +1 -1
  49. package/src/shielded/getMostRecentShieldedAnchor.d.ts +2 -1
  50. package/src/shielded/getMostRecentShieldedAnchor.js +7 -5
  51. package/src/shielded/getShieldedAnchors.d.ts +2 -1
  52. package/src/shielded/getShieldedAnchors.js +7 -5
  53. package/src/shielded/getShieldedEncryptedNotes.d.ts +2 -1
  54. package/src/shielded/getShieldedEncryptedNotes.js +7 -5
  55. package/src/shielded/getShieldedNotesCount.d.ts +2 -1
  56. package/src/shielded/getShieldedNotesCount.js +7 -5
  57. package/src/shielded/getShieldedNullifiers.d.ts +2 -1
  58. package/src/shielded/getShieldedNullifiers.js +7 -5
  59. package/src/shielded/getShieldedPoolState.d.ts +2 -1
  60. package/src/shielded/getShieldedPoolState.js +7 -5
  61. package/src/shielded/index.d.ts +17 -7
  62. package/src/shielded/index.js +22 -12
  63. package/src/stateTransitions/broadcast.js +1 -1
  64. package/src/stateTransitions/index.d.ts +6 -2
  65. package/src/stateTransitions/index.js +5 -1
  66. package/src/stateTransitions/waitForStateTransitionResult.d.ts +1 -1
  67. package/src/stateTransitions/waitForStateTransitionResult.js +5 -3
  68. package/src/tokens/getIdentitiesTokenBalances.js +1 -1
  69. package/src/tokens/getIdentityTokensBalances.js +1 -1
  70. package/src/tokens/getTokenContractInfo.js +1 -1
  71. package/src/tokens/getTokenDirectPurchasePrices.js +1 -1
  72. package/src/tokens/getTokenTotalSupply.js +1 -1
  73. package/src/utils/verifyTenderdashProof.js +1 -1
  74. package/test/unit/ContestedResources.spec.js +0 -1
  75. package/test/unit/DataContract.spec.js +2 -2
  76. package/test/unit/Document.spec.js +0 -1
  77. package/test/unit/DocumentActionFees.spec.d.ts +1 -0
  78. package/test/unit/DocumentActionFees.spec.js +99 -0
  79. package/test/unit/DocumentQueries.spec.d.ts +1 -0
  80. package/test/unit/DocumentQueries.spec.js +178 -0
  81. package/test/unit/DocumentsV1.spec.d.ts +1 -0
  82. package/test/unit/DocumentsV1.spec.js +75 -0
  83. package/test/unit/Identity.spec.js +0 -1
  84. package/test/unit/Names.spec.js +0 -1
  85. package/test/unit/Node.spec.js +0 -1
  86. package/test/unit/PlatformAddress.spec.js +0 -1
  87. package/test/unit/Shielded.spec.js +0 -1
  88. package/test/unit/Tokens.spec.js +0 -1
  89. package/types.d.ts +20 -1
@@ -0,0 +1,37 @@
1
+ import { IdentifierWASM, verifyHavingDocumentsProof, verifyRankedDocumentsProof } from 'pshenmic-dpp';
2
+ import { LATEST_PLATFORM_VERSION } from '../constants.js';
3
+ import getDataContractByIdentifier from '../dataContracts/getDataContractByIdentifier.js';
4
+ import { getDocumentsV1Proof, toHavingClauses, toOrderClauses, toSelect, toWhereClauses, verifyDocumentsV1Signature } from './v1.js';
5
+ async function getRankedProof(grpcPool, dataContractId, query, having) {
6
+ return await getDocumentsV1Proof(grpcPool, {
7
+ dataContractId: (new IdentifierWASM(dataContractId)).bytes(),
8
+ documentType: query.documentTypeName,
9
+ whereClauses: toWhereClauses(query.where),
10
+ orderBy: toOrderClauses(query.orderBy),
11
+ limit: query.limit,
12
+ offset: query.offset,
13
+ selects: toSelect(query.select),
14
+ groupBy: query.groupBy,
15
+ having: toHavingClauses(having)
16
+ });
17
+ }
18
+ /**
19
+ * Top-K query: groups of `groupBy` ranked by the selected aggregate in the order `orderBy` names
20
+ */
21
+ export async function queryRanked(grpcPool, dataContractId, query) {
22
+ const dataContract = await getDataContractByIdentifier(grpcPool, dataContractId);
23
+ const { proof, metadata } = await getRankedProof(grpcPool, dataContractId, query, []);
24
+ const { rootHash, value } = verifyRankedDocumentsProof(proof.grovedbProof, dataContract, query, LATEST_PLATFORM_VERSION, BigInt(metadata.timeMs));
25
+ await verifyDocumentsV1Signature(grpcPool, proof, metadata, rootHash);
26
+ return value;
27
+ }
28
+ /**
29
+ * Having query: groups of `groupBy` whose aggregate falls within the `having` bounds
30
+ */
31
+ export async function queryHaving(grpcPool, dataContractId, query) {
32
+ const dataContract = await getDataContractByIdentifier(grpcPool, dataContractId);
33
+ const { proof, metadata } = await getRankedProof(grpcPool, dataContractId, query, query.having);
34
+ const { rootHash, value } = verifyHavingDocumentsProof(proof.grovedbProof, dataContract, query, LATEST_PLATFORM_VERSION, BigInt(metadata.timeMs));
35
+ await verifyDocumentsV1Signature(grpcPool, proof, metadata, rootHash);
36
+ return value;
37
+ }
@@ -0,0 +1,33 @@
1
+ import { GetDocumentsRequest_DocumentFieldValue, GetDocumentsRequest_GetDocumentsRequestV1, GetDocumentsRequest_GetDocumentsRequestV1_SubQuery, GetDocumentsRequest_HavingClause, GetDocumentsRequest_OrderClause, GetDocumentsRequest_WhereClause, Proof, ResponseMetadata } from '../../proto/generated/platform.js';
2
+ import { AggregateSelect, CompositeSubQuery, HavingClause, IdentifierLike, IdentifierWASM, WhereClause } from 'pshenmic-dpp';
3
+ import { GRPCPool } from '../grpcConnectionPool.js';
4
+ type DocumentFieldValue = GetDocumentsRequest_DocumentFieldValue;
5
+ /**
6
+ * Converts a JS value of a where / having clause into a typed v1 document field value
7
+ */
8
+ export declare function toFieldValue(value: unknown): DocumentFieldValue;
9
+ /**
10
+ * Converts `[field, operator, value]` where clauses into typed v1 where clauses
11
+ */
12
+ export declare function toWhereClauses(where?: WhereClause[] | null): GetDocumentsRequest_WhereClause[];
13
+ /**
14
+ * Converts `[field, 'asc' | 'desc']` order by clauses into typed v1 order clauses.
15
+ * For ranked queries the selected aggregate is ordered by its field, or by `$count` for `count`
16
+ */
17
+ export declare function toOrderClauses(orderBy?: string[][] | null): GetDocumentsRequest_OrderClause[];
18
+ export declare function toSelect(select: AggregateSelect): GetDocumentsRequest_GetDocumentsRequestV1['selects'];
19
+ export declare function toHavingClauses(having: HavingClause[]): GetDocumentsRequest_HavingClause[];
20
+ export declare function toSubQueries(subQueries: CompositeSubQuery[], dataContractId: IdentifierWASM): GetDocumentsRequest_GetDocumentsRequestV1_SubQuery[];
21
+ export declare function toStart(startAt?: IdentifierLike | null, startAtIncluded?: boolean): GetDocumentsRequest_GetDocumentsRequestV1['start'];
22
+ /**
23
+ * Sends a v1 getDocuments request with a proof and returns the proof with the response metadata
24
+ */
25
+ export declare function getDocumentsV1Proof(grpcPool: GRPCPool, v1: Partial<GetDocumentsRequest_GetDocumentsRequestV1>): Promise<{
26
+ proof: Proof;
27
+ metadata: ResponseMetadata;
28
+ }>;
29
+ /**
30
+ * Verifies the quorum signature of a proof whose GroveDB part produced the given root hash
31
+ */
32
+ export declare function verifyDocumentsV1Signature(grpcPool: GRPCPool, proof: Proof, metadata: ResponseMetadata, rootHash: Uint8Array): Promise<void>;
33
+ export {};
@@ -0,0 +1,233 @@
1
+ import { GetDocumentsRequest, GetDocumentsRequest_GetDocumentsRequestV1, GetDocumentsRequest_GetDocumentsRequestV1_Select_Function, GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind, GetDocumentsRequest_HavingAggregate_Function, GetDocumentsRequest_HavingClause_Operator, GetDocumentsRequest_IntegerRangeSelection, GetDocumentsRequest_TimeRangeSelection, GetDocumentsRequest_TimeRangeSelection_Selector, GetDocumentsRequest_WhereClause, GetDocumentsRequest_WhereOperator } from '../../proto/generated/platform.js';
2
+ import { IdentifierWASM } from 'pshenmic-dpp';
3
+ import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
4
+ import bytesToHex from '../utils/bytesToHex.js';
5
+ import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
6
+ const WHERE_OPERATORS = {
7
+ '=': GetDocumentsRequest_WhereOperator.EQUAL,
8
+ '==': GetDocumentsRequest_WhereOperator.EQUAL,
9
+ '>': GetDocumentsRequest_WhereOperator.GREATER_THAN,
10
+ '>=': GetDocumentsRequest_WhereOperator.GREATER_THAN_OR_EQUALS,
11
+ '<': GetDocumentsRequest_WhereOperator.LESS_THAN,
12
+ '<=': GetDocumentsRequest_WhereOperator.LESS_THAN_OR_EQUALS,
13
+ between: GetDocumentsRequest_WhereOperator.BETWEEN,
14
+ betweenexcludebounds: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_BOUNDS,
15
+ betweenexcludeleft: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_LEFT,
16
+ betweenexcluderight: GetDocumentsRequest_WhereOperator.BETWEEN_EXCLUDE_RIGHT,
17
+ in: GetDocumentsRequest_WhereOperator.IN,
18
+ startswith: GetDocumentsRequest_WhereOperator.STARTS_WITH,
19
+ contains: GetDocumentsRequest_WhereOperator.CONTAINS,
20
+ containsany: GetDocumentsRequest_WhereOperator.CONTAINS_ANY,
21
+ intimerange: GetDocumentsRequest_WhereOperator.IN_TIME_RANGE,
22
+ inintegerrange: GetDocumentsRequest_WhereOperator.IN_INTEGER_RANGE
23
+ };
24
+ const HAVING_OPERATORS = {
25
+ '=': GetDocumentsRequest_HavingClause_Operator.EQUAL,
26
+ '!=': GetDocumentsRequest_HavingClause_Operator.NOT_EQUAL,
27
+ '>': GetDocumentsRequest_HavingClause_Operator.GREATER_THAN,
28
+ '>=': GetDocumentsRequest_HavingClause_Operator.GREATER_THAN_OR_EQUALS,
29
+ '<': GetDocumentsRequest_HavingClause_Operator.LESS_THAN,
30
+ '<=': GetDocumentsRequest_HavingClause_Operator.LESS_THAN_OR_EQUALS,
31
+ between: GetDocumentsRequest_HavingClause_Operator.BETWEEN,
32
+ betweenexcludebounds: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_BOUNDS,
33
+ betweenexcludeleft: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_LEFT,
34
+ betweenexcluderight: GetDocumentsRequest_HavingClause_Operator.BETWEEN_EXCLUDE_RIGHT,
35
+ in: GetDocumentsRequest_HavingClause_Operator.IN
36
+ };
37
+ const SELECT_FUNCTIONS = {
38
+ count: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.COUNT,
39
+ sum: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.SUM,
40
+ avg: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.AVG,
41
+ min: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.MIN,
42
+ max: GetDocumentsRequest_GetDocumentsRequestV1_Select_Function.MAX
43
+ };
44
+ const HAVING_FUNCTIONS = {
45
+ count: GetDocumentsRequest_HavingAggregate_Function.COUNT,
46
+ sum: GetDocumentsRequest_HavingAggregate_Function.SUM,
47
+ avg: GetDocumentsRequest_HavingAggregate_Function.AVG
48
+ };
49
+ function normalizeOperator(operator) {
50
+ return operator.toLowerCase().replace(/_/g, '');
51
+ }
52
+ /**
53
+ * Converts a JS value of a where / having clause into a typed v1 document field value
54
+ */
55
+ export function toFieldValue(value) {
56
+ if (value == null) {
57
+ return { variant: { oneofKind: 'nullValue', nullValue: true } };
58
+ }
59
+ if (typeof value === 'boolean') {
60
+ return { variant: { oneofKind: 'boolValue', boolValue: value } };
61
+ }
62
+ if (typeof value === 'bigint' || (typeof value === 'number' && Number.isInteger(value))) {
63
+ return value < 0
64
+ ? { variant: { oneofKind: 'int64Value', int64Value: value.toString() } }
65
+ : { variant: { oneofKind: 'uint64Value', uint64Value: value.toString() } };
66
+ }
67
+ if (typeof value === 'number') {
68
+ return { variant: { oneofKind: 'doubleValue', doubleValue: value } };
69
+ }
70
+ if (typeof value === 'string') {
71
+ return { variant: { oneofKind: 'text', text: value } };
72
+ }
73
+ if (value instanceof Uint8Array) {
74
+ return { variant: { oneofKind: 'bytesValue', bytesValue: value } };
75
+ }
76
+ if (Array.isArray(value)) {
77
+ return { variant: { oneofKind: 'list', list: { values: value.map(toFieldValue) } } };
78
+ }
79
+ throw new Error(`Unsupported where clause value: ${String(value)}`);
80
+ }
81
+ function toTimeRangeSelection(selection) {
82
+ if (selection === 'newest' || selection === 'oldest') {
83
+ return GetDocumentsRequest_TimeRangeSelection.create({
84
+ selector: selection === 'newest'
85
+ ? GetDocumentsRequest_TimeRangeSelection_Selector.NEWEST
86
+ : GetDocumentsRequest_TimeRangeSelection_Selector.OLDEST
87
+ });
88
+ }
89
+ if (typeof selection === 'bigint') {
90
+ return GetDocumentsRequest_TimeRangeSelection.create({
91
+ selector: GetDocumentsRequest_TimeRangeSelection_Selector.BY_START,
92
+ startMs: selection.toString()
93
+ });
94
+ }
95
+ const selectors = {
96
+ newest: GetDocumentsRequest_TimeRangeSelection_Selector.NEWEST,
97
+ oldest: GetDocumentsRequest_TimeRangeSelection_Selector.OLDEST,
98
+ byStart: GetDocumentsRequest_TimeRangeSelection_Selector.BY_START
99
+ };
100
+ return GetDocumentsRequest_TimeRangeSelection.create({
101
+ selector: selectors[selection.selector ?? 'byStart'],
102
+ startMs: selection.startMs?.toString(),
103
+ grid: selection.grid != null
104
+ ? {
105
+ range: selection.grid.rangeSeconds.toString(),
106
+ step: selection.grid.stepSeconds.toString(),
107
+ phase: (selection.grid.phaseSeconds ?? 0).toString()
108
+ }
109
+ : undefined
110
+ });
111
+ }
112
+ function toIntegerRangeSelection(selection) {
113
+ if (typeof selection === 'bigint' || typeof selection === 'number') {
114
+ return GetDocumentsRequest_IntegerRangeSelection.create({ start: toFieldValue(selection) });
115
+ }
116
+ return GetDocumentsRequest_IntegerRangeSelection.create({
117
+ start: toFieldValue(selection.start),
118
+ grid: selection.grid != null
119
+ ? {
120
+ range: selection.grid.range.toString(),
121
+ step: selection.grid.step.toString(),
122
+ phase: (selection.grid.phase ?? 0).toString()
123
+ }
124
+ : undefined
125
+ });
126
+ }
127
+ /**
128
+ * Converts `[field, operator, value]` where clauses into typed v1 where clauses
129
+ */
130
+ export function toWhereClauses(where) {
131
+ return (where ?? []).map(([field, operator, value]) => {
132
+ const op = WHERE_OPERATORS[normalizeOperator(operator)];
133
+ if (op == null) {
134
+ throw new Error(`Unsupported where clause operator: ${operator}`);
135
+ }
136
+ if (op === GetDocumentsRequest_WhereOperator.IN_TIME_RANGE) {
137
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, timeRange: toTimeRangeSelection(value) });
138
+ }
139
+ if (op === GetDocumentsRequest_WhereOperator.IN_INTEGER_RANGE) {
140
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, integerRange: toIntegerRangeSelection(value) });
141
+ }
142
+ return GetDocumentsRequest_WhereClause.create({ field, operator: op, value: toFieldValue(value) });
143
+ });
144
+ }
145
+ /**
146
+ * Converts `[field, 'asc' | 'desc']` order by clauses into typed v1 order clauses.
147
+ * For ranked queries the selected aggregate is ordered by its field, or by `$count` for `count`
148
+ */
149
+ export function toOrderClauses(orderBy) {
150
+ return (orderBy ?? []).map(([field, direction]) => ({
151
+ target: { oneofKind: 'field', field },
152
+ ascending: direction?.toLowerCase() !== 'desc'
153
+ }));
154
+ }
155
+ export function toSelect(select) {
156
+ return [{ function: SELECT_FUNCTIONS[select.function], field: select.field ?? '' }];
157
+ }
158
+ export function toHavingClauses(having) {
159
+ return having.map(clause => {
160
+ const operator = HAVING_OPERATORS[normalizeOperator(clause.operator)];
161
+ if (operator == null) {
162
+ throw new Error(`Unsupported having clause operator: ${clause.operator}`);
163
+ }
164
+ return {
165
+ aggregate: { function: HAVING_FUNCTIONS[clause.function], field: clause.field ?? '' },
166
+ operator,
167
+ right: { oneofKind: 'value', value: toFieldValue(clause.value) }
168
+ };
169
+ });
170
+ }
171
+ export function toSubQueries(subQueries, dataContractId) {
172
+ return subQueries.map(subQuery => ({
173
+ dataContractId: (subQuery.dataContract?.id ?? dataContractId).bytes(),
174
+ documentType: subQuery.documentTypeName,
175
+ whereClauses: toWhereClauses(subQuery.where),
176
+ orderBy: toOrderClauses(subQuery.orderBy),
177
+ limit: subQuery.limit,
178
+ kind: subQuery.kind === 'count'
179
+ ? GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind.COUNT
180
+ : GetDocumentsRequest_GetDocumentsRequestV1_SubQuery_Kind.DOCUMENTS,
181
+ // on the wire `0` is the page and `n` is `subQueries[n - 1]`
182
+ bind: subQuery.binding != null
183
+ ? {
184
+ source: subQuery.binding.source === 'page' ? 0 : subQuery.binding.source + 1,
185
+ sourceProperty: subQuery.binding.sourceProperty,
186
+ field: subQuery.binding.field
187
+ }
188
+ : undefined
189
+ }));
190
+ }
191
+ export function toStart(startAt, startAtIncluded) {
192
+ if (startAt == null) {
193
+ return { oneofKind: undefined };
194
+ }
195
+ const bytes = new IdentifierWASM(startAt).bytes();
196
+ return startAtIncluded === false
197
+ ? { oneofKind: 'startAfter', startAfter: bytes }
198
+ : { oneofKind: 'startAt', startAt: bytes };
199
+ }
200
+ /**
201
+ * Sends a v1 getDocuments request with a proof and returns the proof with the response metadata
202
+ */
203
+ export async function getDocumentsV1Proof(grpcPool, v1) {
204
+ const getDocumentsRequest = GetDocumentsRequest.create({
205
+ version: {
206
+ oneofKind: 'v1',
207
+ v1: GetDocumentsRequest_GetDocumentsRequestV1.create({ ...v1, prove: true })
208
+ }
209
+ });
210
+ const { response } = await (await grpcPool.getClient()).getDocuments(getDocumentsRequest);
211
+ const { version } = response;
212
+ if (version.oneofKind !== 'v1') {
213
+ throw new Error('Unexpected oneOf type returned from DAPI (must be v1)');
214
+ }
215
+ const { v1: { result, metadata } } = version;
216
+ if (result.oneofKind !== 'proof') {
217
+ throw new Error('Unexpected oneOf type returned from DAPI (must be proof)');
218
+ }
219
+ if (metadata == null) {
220
+ throw new Error('Metadata not found');
221
+ }
222
+ return { proof: result.proof, metadata };
223
+ }
224
+ /**
225
+ * Verifies the quorum signature of a proof whose GroveDB part produced the given root hash
226
+ */
227
+ export async function verifyDocumentsV1Signature(grpcPool, proof, metadata, rootHash) {
228
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
229
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
230
+ if (!verify) {
231
+ throw new Error('Failed to verify query');
232
+ }
233
+ }
@@ -1,6 +1,5 @@
1
1
  import { PlatformClient } from '../proto/generated/platform.client.js';
2
2
  import { Network } from '../types.js';
3
- export type MasternodeList = Record<string, MasternodeInfo>;
4
3
  export interface GRPCOptions {
5
4
  poolLimit?: number;
6
5
  dapiUrl?: string | string[];
@@ -13,8 +12,7 @@ export interface GRPCOptions {
13
12
  */
14
13
  export interface GRPCPool {
15
14
  network: Network;
16
- getClient: (abortController?: AbortController) => PlatformClient;
17
- waitForInit?: () => Promise<void>;
15
+ getClient: (abortController?: AbortController) => PlatformClient | Promise<PlatformClient>;
18
16
  }
19
17
  export interface MasternodeInfo {
20
18
  proTxHash: string;
@@ -42,8 +40,7 @@ export default class GRPCConnectionPool implements GRPCPool {
42
40
  constructor(network: Network, grpcOptions?: GRPCOptions);
43
41
  _initialize(network: Network, poolLimit: number, dapiUrl?: string | string[]): Promise<void>;
44
42
  /**
45
- * Resolves when the pool initialization (seed nodes check and evonodes discovery) is finished
43
+ * Waits for the pool initialization and returns a client connected to a random healthy node
46
44
  */
47
- waitForInit(): Promise<void>;
48
- getClient(abortController?: AbortController): PlatformClient;
45
+ getClient(abortController?: AbortController): Promise<PlatformClient>;
49
46
  }
@@ -4,31 +4,47 @@ import { GetStatusRequest } from '../proto/generated/platform.js';
4
4
  import getCurrentQuorumsInfo from './node/getCurrentQuorumsInfo.js';
5
5
  import getRandomArrayItem from './utils/getRandomArrayItem.js';
6
6
  import { fetchWithDetails } from './utils/fetchWithDetails.js';
7
- const GRPC_DEFAULT_POOL_LIMIT = 5;
7
+ import { LATEST_PLATFORM_VERSION } from './constants.js';
8
+ const GRPC_DEFAULT_POOL_LIMIT = 15;
8
9
  const seedNodes = {
9
10
  testnet: [
10
11
  // seed-1.pshenmic.dev
11
- 'https://158.160.14.115:1443',
12
- 'https://62.84.119.150:1443',
13
- // validator
14
- 'https://68.67.122.26:1443'
12
+ 'https://153.80.206.232:1443',
13
+ // DCG seed
14
+ 'https://34.209.12.72:1443',
15
+ // Testnet validators (hp-masternode-1 -> hp-masternode-15)
16
+ 'https://68.67.122.1:1443',
17
+ 'https://68.67.122.2:1443',
18
+ 'https://68.67.122.3:1443',
19
+ 'https://68.67.122.4:1443',
20
+ 'https://68.67.122.5:1443',
21
+ 'https://68.67.122.6:1443',
22
+ 'https://68.67.122.7:1443',
23
+ 'https://68.67.122.8:1443',
24
+ 'https://68.67.122.9:1443',
25
+ 'https://68.67.122.10:1443',
26
+ 'https://68.67.122.11:1443',
27
+ 'https://68.67.122.12:1443',
28
+ 'https://68.67.122.13:1443',
29
+ 'https://68.67.122.14:1443',
30
+ 'https://68.67.122.15:1443'
15
31
  ],
16
32
  mainnet: [
17
33
  // seed-1.pshenmic.dev
18
- 'https://158.160.14.115:443',
19
- 'https://62.84.119.150:443',
34
+ 'https://153.80.206.97:443',
35
+ // DCG seed
36
+ 'https://34.211.174.194:443',
20
37
  // validator
21
- 'https://95.216.146.18:443',
22
- // mainnet dcg seeds
23
- // 'https://158.160.14.115',
24
- // 'https://3.0.60.103',
25
- // 'https://34.211.174.194'
38
+ 'https://95.216.146.18:443'
26
39
  ]
27
40
  };
28
41
  const DAPI_PORTS = {
29
42
  testnet: 1443,
30
43
  mainnet: 443
31
44
  };
45
+ const HEALTHCHECK_TIMEOUT_MS = 5000;
46
+ // platform produces empty blocks every 3 minutes, so a healthy chain is never older than that
47
+ const HEALTHCHECK_MAX_BLOCK_AGE_MS = 10 * 60 * 1000;
32
48
  export const createClient = (url, abortController) => {
33
49
  return new PlatformClient(new GrpcWebFetchTransport({
34
50
  baseUrl: url,
@@ -36,14 +52,73 @@ export const createClient = (url, abortController) => {
36
52
  fetch: fetchWithDetails
37
53
  }));
38
54
  };
55
+ /**
56
+ * Runs a request with an AbortController that is aborted after the given timeout
57
+ */
58
+ const withTimeout = async (request, timeoutMs = HEALTHCHECK_TIMEOUT_MS) => {
59
+ const abortController = new AbortController();
60
+ const timeout = setTimeout(() => abortController.abort(), timeoutMs);
61
+ try {
62
+ return await request(abortController);
63
+ }
64
+ finally {
65
+ clearTimeout(timeout);
66
+ }
67
+ };
68
+ const isNodeHealthy = async (url) => {
69
+ try {
70
+ const response = await withTimeout(async (abortController) => {
71
+ const { response } = await createClient(url, abortController).getStatus(GetStatusRequest.create({}));
72
+ return response;
73
+ });
74
+ if (response.version.oneofKind !== 'v0') {
75
+ return false;
76
+ }
77
+ const { version, chain, time } = response.version.v0;
78
+ // node is still syncing
79
+ if (chain == null || Boolean(chain.catchingUp)) {
80
+ return false;
81
+ }
82
+ // node runs a protocol version that is not supported by the SDK
83
+ // (e.g. newer software with incompatible proofs / responses)
84
+ const protocol = version?.protocol?.drive;
85
+ if (protocol == null || protocol.current !== Number(LATEST_PLATFORM_VERSION) || protocol?.latest !== Number(LATEST_PLATFORM_VERSION)) {
86
+ return false;
87
+ }
88
+ // chain is stalled, last block is too old relative to the node's own clock
89
+ // (local time is in seconds, block time is in milliseconds)
90
+ if (time?.block == null || Number(time.local) * 1000 - Number(time.block) > HEALTHCHECK_MAX_BLOCK_AGE_MS) {
91
+ return false;
92
+ }
93
+ return true;
94
+ }
95
+ catch (e) {
96
+ return false;
97
+ }
98
+ };
99
+ // Fisher–Yates shuffle
100
+ // Randomly shuffles the elements inside of array, having previously cloned it.
101
+ const shuffle = (array) => {
102
+ const result = [...array];
103
+ for (let i = result.length - 1; i > 0; i--) {
104
+ const j = Math.floor(Math.random() * (i + 1));
105
+ [result[i], result[j]] = [result[j], result[i]];
106
+ }
107
+ return result;
108
+ };
39
109
  export default class GRPCConnectionPool {
40
- dapiUrls;
110
+ dapiUrls = [];
41
111
  network;
112
+ #poolLimit;
113
+ #dapiUrl;
42
114
  #initialization;
43
115
  constructor(network, grpcOptions) {
44
- const grpcPoolLimit = grpcOptions?.poolLimit ?? GRPC_DEFAULT_POOL_LIMIT;
45
116
  this.network = network;
46
- this.#initialization = this._initialize(network, grpcPoolLimit, grpcOptions?.dapiUrl).catch(console.error);
117
+ this.#poolLimit = grpcOptions?.poolLimit ?? GRPC_DEFAULT_POOL_LIMIT;
118
+ this.#dapiUrl = grpcOptions?.dapiUrl;
119
+ // start initialization in the background, failures are reported on the first request
120
+ this.#initialization = this._initialize(network, this.#poolLimit, this.#dapiUrl);
121
+ this.#initialization.catch(() => { });
47
122
  }
48
123
  async _initialize(network, poolLimit, dapiUrl) {
49
124
  if (typeof dapiUrl === 'string') {
@@ -51,56 +126,75 @@ export default class GRPCConnectionPool {
51
126
  return;
52
127
  }
53
128
  if (Array.isArray(dapiUrl)) {
54
- this.dapiUrls = dapiUrl;
129
+ this.dapiUrls = [...new Set(dapiUrl)];
130
+ if (this.dapiUrls.length === 0) {
131
+ throw new Error('DAPI URL list is empty');
132
+ }
55
133
  return;
56
134
  }
57
135
  if (dapiUrl != null) {
58
136
  throw new Error('Unrecognized DAPI URL');
59
137
  }
60
- // Add default seed nodes
61
- this.dapiUrls = [...seedNodes[network]];
62
- // retrieve evonodes from current validator sets through the first responding seed node,
63
- // seed nodes that failed to respond are removed from the pool
64
- const seedRequests = seedNodes[network].map(async (seed) => {
138
+ let quorumsInfo;
139
+ const errors = [];
140
+ for (const seed of seedNodes[network]) {
65
141
  try {
66
- return await getCurrentQuorumsInfo({ network, getClient: () => createClient(seed) });
142
+ quorumsInfo = await withTimeout(async (abortController) => await getCurrentQuorumsInfo({ network, getClient: () => createClient(seed, abortController) }));
143
+ break;
67
144
  }
68
145
  catch (e) {
69
- this.dapiUrls = this.dapiUrls.filter(url => url !== seed);
70
- throw e;
146
+ errors.push(e);
71
147
  }
72
- });
73
- const { validatorSets } = await Promise.any(seedRequests);
148
+ }
149
+ if (quorumsInfo == null) {
150
+ throw new AggregateError(errors, `None of the ${network} seed nodes are available: ${errors.map(String).join('; ')}`);
151
+ }
74
152
  // map it to array of dapiUrls
75
- const networkDAPIUrls = [...new Set(validatorSets
153
+ const networkDAPIUrls = shuffle([...new Set(quorumsInfo.validatorSets
76
154
  .flatMap(validatorSet => validatorSet.members)
77
155
  .filter(member => !member.isBanned)
78
- .map(member => `https://${member.nodeIp}:${DAPI_PORTS[network]}`))];
79
- // healthcheck nodes
80
- for (const url of networkDAPIUrls) {
81
- if (this.dapiUrls.length > poolLimit) {
82
- break;
83
- }
84
- try {
85
- const client = createClient(url);
86
- const { response } = await client.getStatus(GetStatusRequest.create({}));
87
- if (response.version.oneofKind === 'v0' && response.version.v0.chain != null) {
88
- this.dapiUrls.push(url);
156
+ .map(member => `https://${member.nodeIp}:${DAPI_PORTS[network]}`))])
157
+ .filter(url => !this.dapiUrls.includes(url));
158
+ // 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);
89
164
  }
90
- }
91
- catch (e) {
92
- }
165
+ }));
166
+ }
167
+ // fail the initialization, so it is retried on the next request
168
+ if (this.dapiUrls.length === 0) {
169
+ 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)})`);
93
171
  }
94
- // wait until every seed node responded or failed, so dead ones are removed from the pool
95
- await Promise.allSettled(seedRequests);
96
172
  }
97
173
  /**
98
- * Resolves when the pool initialization (seed nodes check and evonodes discovery) is finished
174
+ * Adds a node to the pool, unless it is already there or the pool is full
99
175
  */
100
- async waitForInit() {
101
- await this.#initialization;
176
+ #addNode(url, poolLimit) {
177
+ if (!this.dapiUrls.includes(url) && this.dapiUrls.length < poolLimit) {
178
+ this.dapiUrls.push(url);
179
+ }
102
180
  }
103
- getClient(abortController) {
181
+ /**
182
+ * Waits for the pool initialization and returns a client connected to a random healthy node
183
+ */
184
+ async getClient(abortController) {
185
+ // retry initialization if the previous attempt failed
186
+ this.#initialization ??= this._initialize(this.network, this.#poolLimit, this.#dapiUrl);
187
+ const initialization = this.#initialization;
188
+ try {
189
+ await initialization;
190
+ }
191
+ catch (e) {
192
+ // other callers may have already started a new attempt
193
+ if (this.#initialization === initialization) {
194
+ this.#initialization = undefined;
195
+ }
196
+ throw e;
197
+ }
104
198
  const dapiUrl = getRandomArrayItem(this.dapiUrls);
105
199
  return createClient(dapiUrl, abortController);
106
200
  }
@@ -15,7 +15,7 @@ export default async function getIdentityBalance(grpcPool, identifier) {
15
15
  }
16
16
  }
17
17
  });
18
- const { response } = await grpcPool.getClient().getIdentityBalance(getIdentityBalanceRequest);
18
+ const { response } = await (await grpcPool.getClient()).getIdentityBalance(getIdentityBalanceRequest);
19
19
  const { version } = response;
20
20
  if (version.oneofKind !== 'v0') {
21
21
  throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
@@ -15,7 +15,7 @@ export default async function getIdentityByIdentifier(grpcPool, identifier) {
15
15
  }
16
16
  }
17
17
  });
18
- const { response } = await grpcPool.getClient().getIdentity(getIdentityRequest);
18
+ const { response } = await (await grpcPool.getClient()).getIdentity(getIdentityRequest);
19
19
  const { version } = response;
20
20
  if (version.oneofKind !== 'v0') {
21
21
  throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
@@ -1,10 +1,9 @@
1
1
  import { GetIdentityByNonUniquePublicKeyHashRequest } from '../../proto/generated/platform.js';
2
- import { verifyIdentifierByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
2
+ import { verifyFullIdentityByNonUniquePublicKeyHashProof } from 'pshenmic-dpp';
3
3
  import hexToBytes from '../utils/hexToBytes.js';
4
4
  import { getQuorumPublicKey } from '../utils/getQuorumPublicKey.js';
5
5
  import bytesToHex from '../utils/bytesToHex.js';
6
6
  import verifyTenderdashProof from '../utils/verifyTenderdashProof.js';
7
- import getIdentityByIdentifier from './getIdentityByIdentifier.js';
8
7
  import { LATEST_PLATFORM_VERSION } from '../constants.js';
9
8
  export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex) {
10
9
  const getIdentityByNonUniquePublicKeyHashRequest = GetIdentityByNonUniquePublicKeyHashRequest.create({
@@ -16,7 +15,7 @@ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex)
16
15
  }
17
16
  }
18
17
  });
19
- const { response } = await grpcPool.getClient().getIdentityByNonUniquePublicKeyHash(getIdentityByNonUniquePublicKeyHashRequest);
18
+ const { response } = await (await grpcPool.getClient()).getIdentityByNonUniquePublicKeyHash(getIdentityByNonUniquePublicKeyHashRequest);
20
19
  const { version } = response;
21
20
  if (version.oneofKind !== 'v0') {
22
21
  throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');
@@ -29,17 +28,14 @@ export default async function getIdentityByNonUniquePublicKeyHash(grpcPool, hex)
29
28
  if (metadata == null) {
30
29
  throw new Error('Metadata not found');
31
30
  }
32
- if (proof.grovedbIdentityPublicKeyHashProof == null) {
33
- throw new Error('GroveDB proof not found for identity by non unique public key request');
34
- }
35
- const { rootHash, identifier } = verifyIdentifierByNonUniquePublicKeyHashProof(proof.grovedbIdentityPublicKeyHashProof.grovedbProof, false, hexToBytes(hex), undefined, LATEST_PLATFORM_VERSION);
36
- if (identifier == null) {
31
+ const { rootHash, identity } = verifyFullIdentityByNonUniquePublicKeyHashProof(proof.grovedbProof, hexToBytes(hex), undefined, metadata.protocolVersion, LATEST_PLATFORM_VERSION);
32
+ if (identity == null) {
37
33
  throw new Error(`Identity with non unique public key hash ${hex} not found`);
38
34
  }
39
- const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.grovedbIdentityPublicKeyHashProof.quorumType, bytesToHex(proof.grovedbIdentityPublicKeyHashProof.quorumHash));
40
- const verify = await verifyTenderdashProof(proof.grovedbIdentityPublicKeyHashProof, metadata, rootHash, quorumPublicKey);
35
+ const quorumPublicKey = await getQuorumPublicKey(grpcPool.network, proof.quorumType, bytesToHex(proof.quorumHash));
36
+ const verify = await verifyTenderdashProof(proof, metadata, rootHash, quorumPublicKey);
41
37
  if (!verify) {
42
38
  throw new Error('Failed to verify query');
43
39
  }
44
- return await getIdentityByIdentifier(grpcPool, identifier);
40
+ return identity;
45
41
  }
@@ -15,7 +15,7 @@ export default async function getIdentityByPublicKeyHash(grpcPool, hex) {
15
15
  }
16
16
  }
17
17
  });
18
- const { response } = await grpcPool.getClient().getIdentityByPublicKeyHash(getIdentityByPublicKeyHashRequest);
18
+ const { response } = await (await grpcPool.getClient()).getIdentityByPublicKeyHash(getIdentityByPublicKeyHashRequest);
19
19
  const { version } = response;
20
20
  if (version.oneofKind !== 'v0') {
21
21
  throw new Error('Unexpected oneOf type returned from DAPI (must be v0)');