@keetanetwork/keetanet-client 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/client/builder.d.ts +8 -3
  2. package/client/index-browser.d.ts +1 -1
  3. package/client/index-browser.js +1805 -1716
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js +217 -148
  6. package/docs/assets/hierarchy.js +1 -1
  7. package/docs/assets/navigation.js +1 -1
  8. package/docs/assets/search.js +1 -1
  9. package/docs/classes/KeetaNetSDK.Client.html +4 -4
  10. package/docs/classes/KeetaNetSDK.Referenced.BaseSet.html +1 -1
  11. package/docs/classes/KeetaNetSDK.Referenced.BaseVoteBuilder.html +1 -1
  12. package/docs/classes/KeetaNetSDK.Referenced.BlockHash.html +1 -1
  13. package/docs/classes/KeetaNetSDK.Referenced.BlockOperation.html +1 -1
  14. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationCREATE_IDENTIFIER.html +1 -1
  15. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMANAGE_CERTIFICATE.html +1 -1
  16. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMODIFY_PERMISSIONS.html +1 -1
  17. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationRECEIVE.html +1 -1
  18. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSEND.html +1 -1
  19. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_INFO.html +1 -1
  20. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_REP.html +1 -1
  21. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_MODIFY_BALANCE.html +1 -1
  22. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_SUPPLY.html +1 -1
  23. package/docs/classes/KeetaNetSDK.Referenced.ECDSAKeyPair.html +1 -1
  24. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1KeyPair.html +1 -1
  25. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PrivateKey.html +1 -1
  26. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PublicKey.html +1 -1
  27. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1Signature.html +1 -1
  28. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1KeyPair.html +1 -1
  29. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PrivateKey.html +1 -1
  30. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PublicKey.html +1 -1
  31. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1Signature.html +1 -1
  32. package/docs/classes/KeetaNetSDK.Referenced.ED25519KeyPair.html +1 -1
  33. package/docs/classes/KeetaNetSDK.Referenced.ED25519PrivateKey.html +1 -1
  34. package/docs/classes/KeetaNetSDK.Referenced.ED25519PublicKey.html +1 -1
  35. package/docs/classes/KeetaNetSDK.Referenced.ED25519Signature.html +1 -1
  36. package/docs/classes/KeetaNetSDK.Referenced.ExternalKeyPair.html +1 -1
  37. package/docs/classes/KeetaNetSDK.Referenced.ExternalSet.html +1 -1
  38. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKey.html +1 -1
  39. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKeyPair.html +1 -1
  40. package/docs/classes/KeetaNetSDK.Referenced.KeyInterface.html +1 -1
  41. package/docs/classes/KeetaNetSDK.Referenced.KeyStorage.html +1 -1
  42. package/docs/classes/KeetaNetSDK.Referenced.Ledger.html +1 -1
  43. package/docs/classes/KeetaNetSDK.Referenced.LedgerAtomicInterface.html +1 -1
  44. package/docs/classes/KeetaNetSDK.Referenced.LedgerStorageTransactionBase.html +8 -0
  45. package/docs/classes/KeetaNetSDK.Referenced.PermissionSetHolder.html +1 -1
  46. package/docs/classes/KeetaNetSDK.Referenced.PossiblyExpiredVote.html +1 -1
  47. package/docs/classes/KeetaNetSDK.Referenced.SignatureStorage.html +1 -1
  48. package/docs/classes/KeetaNetSDK.Referenced.Stats.html +10 -4
  49. package/docs/classes/KeetaNetSDK.Referenced.StatsPending.html +10 -0
  50. package/docs/classes/KeetaNetSDK.Referenced.UserClientBuilder.html +2 -2
  51. package/docs/classes/KeetaNetSDK.Referenced.Vote.html +1 -1
  52. package/docs/classes/KeetaNetSDK.Referenced.VoteBlockBundle.html +1 -1
  53. package/docs/classes/KeetaNetSDK.Referenced.VoteBuilder.html +1 -1
  54. package/docs/classes/KeetaNetSDK.Referenced.VoteHash.html +1 -1
  55. package/docs/classes/KeetaNetSDK.Referenced.VoteLikeBase.html +1 -1
  56. package/docs/classes/KeetaNetSDK.Referenced.VoteQuote.html +1 -1
  57. package/docs/classes/KeetaNetSDK.Referenced.VoteQuoteBuilder.html +1 -1
  58. package/docs/classes/KeetaNetSDK.Referenced.VoteStaple.html +1 -1
  59. package/docs/classes/KeetaNetSDK.Referenced.VoteStapleHash.html +1 -1
  60. package/docs/classes/KeetaNetSDK.Referenced.src_lib_utils_buffer.BufferStorage.html +1 -1
  61. package/docs/classes/KeetaNetSDK.UserClient.html +2 -2
  62. package/docs/hierarchy.html +1 -1
  63. package/docs/interfaces/KeetaNetSDK.Referenced.ACLEntry.html +1 -1
  64. package/docs/interfaces/KeetaNetSDK.Referenced.ACLUpdate.html +1 -1
  65. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ExplicitContextTag.html +1 -1
  66. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ImplicitContextTag.html +1 -1
  67. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1Object.html +1 -1
  68. package/docs/interfaces/KeetaNetSDK.Referenced.BaseExternalKeyPairFunctions.html +1 -1
  69. package/docs/interfaces/KeetaNetSDK.Referenced.BaseGenerationConfig.html +1 -1
  70. package/docs/interfaces/KeetaNetSDK.Referenced.BaseIdentifierCreateArguments.html +1 -1
  71. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperation.html +1 -1
  72. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationCREATE_IDENTIFIER.html +1 -1
  73. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATE.html +1 -1
  74. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATESerializable.html +1 -1
  75. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMODIFY_PERMISSIONS.html +1 -1
  76. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationRECEIVE.html +1 -1
  77. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSEND.html +1 -1
  78. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_INFO.html +1 -1
  79. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_REP.html +1 -1
  80. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_MODIFY_BALANCE.html +1 -1
  81. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_SUPPLY.html +1 -1
  82. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV1Canonical.html +1 -1
  83. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV2Canonical.html +1 -1
  84. package/docs/interfaces/KeetaNetSDK.Referenced.BuilderBlockOptions.html +3 -0
  85. package/docs/interfaces/KeetaNetSDK.Referenced.Constructor.html +1 -1
  86. package/docs/interfaces/KeetaNetSDK.Referenced.DisposableTimingHandle.html +1 -1
  87. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsNoEncryption.html +1 -1
  88. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsSupportsEncryption.html +1 -1
  89. package/docs/interfaces/KeetaNetSDK.Referenced.InitialConfigSupply.html +1 -1
  90. package/docs/interfaces/KeetaNetSDK.Referenced.InstanceSet.html +1 -1
  91. package/docs/interfaces/KeetaNetSDK.Referenced.KVGenericOptionsType.html +1 -1
  92. package/docs/interfaces/KeetaNetSDK.Referenced.KVSetOptionsType.html +1 -1
  93. package/docs/interfaces/KeetaNetSDK.Referenced.LedgerStorageAPI.html +2 -2
  94. package/docs/interfaces/KeetaNetSDK.Referenced.LedgerStorageTransactionBaseOptions.html +6 -0
  95. package/docs/interfaces/KeetaNetSDK.Referenced.ModifyTokenBalanceEntry.html +1 -1
  96. package/docs/interfaces/KeetaNetSDK.Referenced.MultiSigIdentifierCreateArguments.html +1 -1
  97. package/docs/interfaces/KeetaNetSDK.Referenced.MultisigConfig.html +1 -1
  98. package/docs/interfaces/KeetaNetSDK.Referenced.NumericValueEntry.html +1 -1
  99. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerBase.html +1 -1
  100. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerListener.html +1 -1
  101. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerRepBase.html +1 -1
  102. package/docs/interfaces/KeetaNetSDK.Referenced.PublicKeyStorage.html +1 -1
  103. package/docs/interfaces/{KeetaNetSDK.PublishOptions.html → KeetaNetSDK.Referenced.PublishOptions.html} +1 -1
  104. package/docs/interfaces/KeetaNetSDK.Referenced.RequestTokenReceiveEntry.html +1 -1
  105. package/docs/interfaces/KeetaNetSDK.Referenced.TokenNumericEntry.html +1 -1
  106. package/docs/interfaces/KeetaNetSDK.Referenced.WithIsInstance.html +1 -1
  107. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1BitString.html +1 -1
  108. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Date.html +1 -1
  109. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1OID.html +1 -1
  110. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Set.html +1 -1
  111. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1String.html +1 -1
  112. package/docs/modules/KeetaNetSDK.Referenced.html +1 -1
  113. package/docs/modules/KeetaNetSDK.Referenced.src_lib_utils_asn1.html +1 -1
  114. package/docs/modules/KeetaNetSDK.html +2 -2
  115. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_asn1.ValidateASN1.SchemaMap.html +1 -1
  116. package/docs/variables/KeetaNetSDK.Referenced.BlockErrorCodes-1.html +1 -1
  117. package/docs/variables/KeetaNetSDK.Referenced.LedgerErrorCodes.html +1 -1
  118. package/docs/variables/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1CheckUtilities.html +1 -0
  119. package/lib/error/certificate.d.ts +1 -1
  120. package/lib/error/ledger.d.ts +1 -1
  121. package/lib/ledger/db_dynamodb.d.ts +5 -9
  122. package/lib/ledger/db_postgres.d.ts +11 -3
  123. package/lib/ledger/db_spanner.d.ts +5 -12
  124. package/lib/ledger/db_spanner_helper.d.ts +1 -1
  125. package/lib/ledger/db_sqlite.d.ts +11 -3
  126. package/lib/ledger/index.d.ts +11 -2
  127. package/lib/stats.d.ts +22 -3
  128. package/lib/utils/asn1.d.ts +18 -1
  129. package/lib/utils/static-types.d.ts +11 -0
  130. package/package.json +1 -1
  131. package/version.d.ts +1 -1
  132. package/benchmarking/test.d.ts +0 -4
  133. package/docs/interfaces/KeetaNetSDK.Referenced.LedgerStorageTransactionBase.html +0 -6
@@ -101264,6 +101264,7 @@ var client_utils_asn1_namespaceObject = {};
101264
101264
  __webpack_require__.r(client_utils_asn1_namespaceObject);
101265
101265
  __webpack_require__.d(client_utils_asn1_namespaceObject, {
101266
101266
  ASN1BigIntToBuffer: () => (client_ASN1BigIntToBuffer),
101267
+ ASN1CheckUtilities: () => (client_ASN1CheckUtilities),
101267
101268
  ASN1IntegerToBigInt: () => (client_ASN1IntegerToBigInt),
101268
101269
  ASN1toJS: () => (client_ASN1toJS),
101269
101270
  BufferStorageASN1: () => (client_BufferStorageASN1),
@@ -113180,7 +113181,16 @@ function client_isASN1Set(input) {
113180
113181
  }
113181
113182
  return true;
113182
113183
  }
113183
- function client_isASN1ContextTag(input) {
113184
+ function client_isASN1ContextTagKind(input) {
113185
+ if (typeof input !== 'string') {
113186
+ return false;
113187
+ }
113188
+ if (!['explicit', 'implicit'].includes(input)) {
113189
+ return false;
113190
+ }
113191
+ return true;
113192
+ }
113193
+ function client_isASN1ContextTag(input, tagKind) {
113184
113194
  if (!client_isASN1Object(input)) {
113185
113195
  return false;
113186
113196
  }
@@ -113193,6 +113203,12 @@ function client_isASN1ContextTag(input) {
113193
113203
  if (!('contains' in input) || input.contains === undefined) {
113194
113204
  return false;
113195
113205
  }
113206
+ if (!('kind' in input) || !client_isASN1ContextTagKind(input.kind)) {
113207
+ return false;
113208
+ }
113209
+ if (tagKind !== undefined && input.kind !== tagKind) {
113210
+ return false;
113211
+ }
113196
113212
  return true;
113197
113213
  }
113198
113214
  function client_isASN1BitString(input) {
@@ -113249,6 +113265,15 @@ function client_isStringValidForKind(input, kind) {
113249
113265
  }
113250
113266
  return false;
113251
113267
  }
113268
+ const client_ASN1CheckUtilities = {
113269
+ isASN1Object: client_isASN1Object,
113270
+ isASN1OID: client_isASN1OID,
113271
+ isASN1String: client_isASN1String,
113272
+ isASN1Set: client_isASN1Set,
113273
+ isASN1ContextTag: client_isASN1ContextTag,
113274
+ isASN1BitString: client_isASN1BitString,
113275
+ isASN1Date: client_isASN1Date
113276
+ };
113252
113277
 
113253
113278
  /**
113254
113279
  * Validation function for {@link isValidSequenceSchema}
@@ -115300,7 +115325,7 @@ function client_certificate_toPrimitive(t, r) { if ("object" != typeof t || !t)
115300
115325
 
115301
115326
 
115302
115327
  const client_CertificateErrorType = 'CERTIFICATE';
115303
- const client_certificate_BlockErrorCodes = ['DUPLICATE_INCLUDED', 'ORPHAN_FOUND', 'CYCLE_FOUND', 'SECONDARY_GRAPH'];
115328
+ const client_certificate_BlockErrorCodes = ['DUPLICATE_INCLUDED', 'ORPHAN_FOUND', 'CYCLE_FOUND', 'SECONDARY_GRAPH', 'MISSING_FIELD', 'SIGNATURE_ALGORITHM_MISMATCH', 'SELF_SIGNED_VALIDATION_FAILED', 'CHAIN_VERIFICATION_FAILED', 'DUPLICATE_EXTENSION', 'EXTENSION_NOT_PROCESSED', 'INVALID_SIGNATURE_ALGORITHM', 'INVALID_GRAPH_COUNT', 'MOMENT_INVALID', 'INVALID_VERSION'];
115304
115329
  class src_client_KeetaNetCertificateError extends src_client_KeetaNetError {
115305
115330
  constructor(code, message) {
115306
115331
  super(code, message, {
@@ -115473,7 +115498,7 @@ class client_CertificateBuilder {
115473
115498
  case 'sha3-256':
115474
115499
  return hashLib.name;
115475
115500
  default:
115476
- throw new Error(`Unsupported hash algorithm "${hashLib.name}"`);
115501
+ throw new Error(`internal error: Unsupported hash algorithm "${hashLib.name}"`);
115477
115502
  }
115478
115503
  }
115479
115504
  const hashName = (_params$hashParams$de = (_params$hashParams = params.hashParams) === null || _params$hashParams === void 0 || (_params$hashParams = _params$hashParams.defaults) === null || _params$hashParams === void 0 ? void 0 : _params$hashParams[purpose]) !== null && _params$hashParams$de !== void 0 ? _params$hashParams$de : client_defaultHashName;
@@ -115496,7 +115521,7 @@ class client_CertificateBuilder {
115496
115521
  const hashName = this.hashName(params, purpose);
115497
115522
  const hashFunction = (_params$hashParams$fu = params.hashParams.functions) === null || _params$hashParams$fu === void 0 ? void 0 : _params$hashParams$fu[hashName];
115498
115523
  if (hashFunction === undefined) {
115499
- throw new Error(`Hash function "${hashName}" not found for purpose "${purpose}"`);
115524
+ throw new Error(`internal error: Hash function "${hashName}" not found for purpose "${purpose}"`);
115500
115525
  }
115501
115526
  return hashFunction(...data);
115502
115527
  }
@@ -115604,28 +115629,28 @@ class client_CertificateBuilder {
115604
115629
  /* Validate that required parameters are set */
115605
115630
  const issuer = finalParams.issuer;
115606
115631
  if (issuer === undefined) {
115607
- throw new Error('"issuer" not set');
115632
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"issuer" not set');
115608
115633
  }
115609
115634
  const subjectPublicKey = finalParams.subjectPublicKey;
115610
115635
  if (subjectPublicKey === undefined) {
115611
- throw new Error('"subject" not set');
115636
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"subject" not set');
115612
115637
  }
115613
115638
  const validFrom = finalParams.validFrom;
115614
115639
  if (validFrom === undefined) {
115615
- throw new Error('"validFrom" not set');
115640
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"validFrom" not set');
115616
115641
  }
115617
115642
  const validTo = finalParams.validTo;
115618
115643
  if (validTo === undefined) {
115619
- throw new Error('"validTo" not set');
115644
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"validTo" not set');
115620
115645
  }
115621
115646
  const serial = finalParams.serial;
115622
115647
  if (serial === undefined) {
115623
- throw new Error('"serialNumber" not set');
115648
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"serialNumber" not set');
115624
115649
  }
115625
115650
  const hashLib = finalParams.hashLib;
115626
115651
  const hashParams = finalParams.hashParams;
115627
115652
  if (hashParams === undefined) {
115628
- throw new Error('"hashParams" not set');
115653
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MISSING_FIELD', '"hashParams" not set');
115629
115654
  }
115630
115655
  return {
115631
115656
  ...finalParams,
@@ -115967,7 +115992,7 @@ class src_client_Certificate {
115967
115992
  const tbsCertificate = parts[0];
115968
115993
  const [version, serialNumber, signatureAlgorithmSigned, _issuer, [notBefore, notAfter], subject, subjectPublicKey, _extensions] = tbsCertificate;
115969
115994
  if (version.contains !== 2n) {
115970
- throw new Error('Only X509v3 certificates are supported');
115995
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_INVALID_VERSION', 'Only X509v3 certificates are supported');
115971
115996
  }
115972
115997
  const signatureAlgorithm = parts[1];
115973
115998
 
@@ -116012,7 +116037,7 @@ class src_client_Certificate {
116012
116037
  const signatureAlgorithmSignedBuffer = new client_BufferStorageASN1(signatureAlgorithmSigned).getDERBuffer();
116013
116038
  const signatureAlgorithmBuffer = new client_BufferStorageASN1(signatureAlgorithm).getDERBuffer();
116014
116039
  if (!signatureAlgorithmSignedBuffer.equals(signatureAlgorithmBuffer)) {
116015
- throw new Error('Signature algorithm mismatch');
116040
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_SIGNATURE_ALGORITHM_MISMATCH', 'Signature algorithm mismatch between signature and certificate');
116016
116041
  }
116017
116042
 
116018
116043
  /*
@@ -116044,7 +116069,7 @@ class src_client_Certificate {
116044
116069
  }
116045
116070
  });
116046
116071
  if (!found) {
116047
- throw new Error('Self-signed certificate is not a root CA in the Root CA store');
116072
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_SELF_SIGNED_VALIDATION_FAILED', 'Self-signed certificate is not a root CA in the Root CA store');
116048
116073
  }
116049
116074
  this.chain = [this];
116050
116075
  }
@@ -116053,7 +116078,7 @@ class src_client_Certificate {
116053
116078
  this.chain = [this];
116054
116079
  }
116055
116080
  if (!this.verify(this)) {
116056
- throw new Error('Self-signed certificate signature verification failed');
116081
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_SELF_SIGNED_VALIDATION_FAILED', 'Self-signed certificate signature verification failed');
116057
116082
  }
116058
116083
  } else {
116059
116084
  /*
@@ -116062,7 +116087,7 @@ class src_client_Certificate {
116062
116087
  if ((options === null || options === void 0 ? void 0 : options.store) !== undefined) {
116063
116088
  const chain = this.verifyChain(options.store);
116064
116089
  if (chain === null || chain.length === 0) {
116065
- throw new Error('Certificate chain verification failed');
116090
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_CHAIN_VERIFICATION_FAILED', 'Certificate chain verification failed');
116066
116091
  }
116067
116092
  this.chain = chain;
116068
116093
  }
@@ -116130,7 +116155,7 @@ class src_client_Certificate {
116130
116155
  compatibleKeyTypes = [client_lib_account.AccountKeyAlgorithm.ED25519];
116131
116156
  break;
116132
116157
  default:
116133
- throw new Error(`Unsupported signature algorithm ${signatureAlgorithm}`);
116158
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_INVALID_SIGNATURE_ALGORITHM', `Unsupported signature algorithm ${signatureAlgorithm}`);
116134
116159
  }
116135
116160
  let hashAlgorithm;
116136
116161
  switch (signatureAlgorithm) {
@@ -116144,7 +116169,7 @@ class src_client_Certificate {
116144
116169
  hashAlgorithm = null;
116145
116170
  break;
116146
116171
  default:
116147
- throw new Error(`Unsupported signature algorithm ${signatureAlgorithm}`);
116172
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_INVALID_SIGNATURE_ALGORITHM', `Unsupported signature algorithm ${signatureAlgorithm}`);
116148
116173
  }
116149
116174
  let accountIsCompatible = false;
116150
116175
  for (const checkCompatibleKeyType of compatibleKeyTypes) {
@@ -116154,7 +116179,7 @@ class src_client_Certificate {
116154
116179
  }
116155
116180
  }
116156
116181
  if (!accountIsCompatible) {
116157
- throw new Error(`Account does not have a compatible key type for signature algorithm ${signatureAlgorithm}`);
116182
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_INVALID_SIGNATURE_ALGORITHM', `Account does not have a compatible key type for signature algorithm ${signatureAlgorithm}`);
116158
116183
  }
116159
116184
  let dataToVerify;
116160
116185
  if (hashAlgorithm !== null) {
@@ -116181,7 +116206,7 @@ class src_client_Certificate {
116181
116206
  return true;
116182
116207
  }
116183
116208
  if (certificates.size > 10) {
116184
- throw new Error('Cannot currently handle more than 10 certificates in a graph');
116209
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_INVALID_GRAPH_COUNT', 'Cannot currently handle more than 10 certificates in a graph');
116185
116210
  }
116186
116211
  const issuersFrom = [];
116187
116212
  const issuersTo = [];
@@ -116302,7 +116327,7 @@ class src_client_Certificate {
116302
116327
  assertValid(moment) {
116303
116328
  const valid = this.checkValid(moment, true);
116304
116329
  if (!valid.valid) {
116305
- throw new Error(`Certificate is not valid: ${valid.reason}`);
116330
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_MOMENT_INVALID', `Certificate is not valid: ${valid.reason}`);
116306
116331
  }
116307
116332
  }
116308
116333
 
@@ -116376,7 +116401,7 @@ class src_client_Certificate {
116376
116401
  }
116377
116402
  assertConstructed() {
116378
116403
  if (!client_certificate_classPrivateFieldGet(client_finalizeConstructionCalled, this)) {
116379
- throw new Error('finalizeConstruction not called');
116404
+ throw new Error('internal error: finalizeConstruction not called');
116380
116405
  }
116381
116406
  }
116382
116407
 
@@ -116519,7 +116544,7 @@ function client_processBaseExtensions(extensionsObject) {
116519
116544
  for (const extension of extensions) {
116520
116545
  const id = extension[0].oid;
116521
116546
  if (seenExtensions.has(id)) {
116522
- throw new Error(`Duplicate extension ${id}`);
116547
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_DUPLICATE_EXTENSION', `Duplicate extension ${id}`);
116523
116548
  }
116524
116549
  seenExtensions.add(id);
116525
116550
  }
@@ -116590,7 +116615,7 @@ function client_assertAllCriticalExtensionsProcessed() {
116590
116615
  [id] = extension;
116591
116616
  }
116592
116617
  if (critical && !client_certificate_classPrivateFieldGet(client_extensionsProcessed, this).has(id.oid)) {
116593
- throw new Error(`Critical extension ${id.oid} not processed`);
116618
+ throw new src_client_KeetaNetCertificateError('CERTIFICATE_EXTENSION_NOT_PROCESSED', `Critical extension ${id.oid} not processed`);
116594
116619
  }
116595
116620
  }
116596
116621
  }
@@ -116718,7 +116743,7 @@ function client_ledger_toPrimitive(t, r) { if ("object" != typeof t || !t) retur
116718
116743
 
116719
116744
 
116720
116745
  const client_LedgerErrorType = 'LEDGER';
116721
- const client_LedgerErrorCodes = ['TRANSACTION_ABORTED', 'INVALID_CHAIN', 'INVALID_NETWORK', 'INVALID_SUBNET', 'NOT_EMPTY', 'NOT_OPENING', 'NOT_SUCCESSOR', 'INVALID_PERMISSIONS', 'INVALID_OWNER_COUNT', 'INVALID_BALANCE', 'PREVIOUS_ALREADY_USED', 'PREVIOUS_NOT_SEEN', 'SUCCESSOR_VOTE_EXISTS', 'INSUFFICIENT_VOTING_WEIGHT', 'INVALID_ACCOUNT_INFO_KEY', 'RECEIVE_NOT_MET', 'DUPLICATE_VOTE_FOUND', 'CANNOT_EXCHANGE_PERM_VOTE', 'BLOCKS_DIFFER_FROM_VOTED_ON', 'NO_PERM_WITHOUT_SELF_TEMP', 'DUPLICATE_VOTE_ISSUER_FOUND', 'OTHER', 'MISSING_BLOCKS',
116746
+ const client_LedgerErrorCodes = ['BLOCK_ALREADY_EXISTS', 'TRANSACTION_ABORTED', 'INVALID_CHAIN', 'INVALID_NETWORK', 'INVALID_SUBNET', 'NOT_EMPTY', 'NOT_OPENING', 'NOT_SUCCESSOR', 'INVALID_PERMISSIONS', 'INVALID_OWNER_COUNT', 'INVALID_BALANCE', 'PREVIOUS_ALREADY_USED', 'PREVIOUS_NOT_SEEN', 'SUCCESSOR_VOTE_EXISTS', 'INSUFFICIENT_VOTING_WEIGHT', 'INVALID_ACCOUNT_INFO_KEY', 'RECEIVE_NOT_MET', 'DUPLICATE_VOTE_FOUND', 'CANNOT_EXCHANGE_PERM_VOTE', 'BLOCKS_DIFFER_FROM_VOTED_ON', 'NO_PERM_WITHOUT_SELF_TEMP', 'DUPLICATE_VOTE_ISSUER_FOUND', 'OTHER', 'MISSING_BLOCKS',
116722
116747
  // Fee Errors
116723
116748
  'FEE_AMOUNT_MISMATCH', 'FEE_TOKEN_MISMATCH', 'FEE_MISSING', 'MISSING_REQUIRED_FEE_BLOCK', 'PERM_VOTE_WITH_QUOTE', 'QUOTE_MISMATCH', 'REQUIRED_FEE_MISMATCH'];
116724
116749
  class client_ledger_KeetaNetLedgerError extends src_client_KeetaNetError {
@@ -117261,6 +117286,20 @@ class client_LedgerStorageBase {
117261
117286
  async preAdjust(input) {
117262
117287
  let mayDefer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
117263
117288
  let transaction = arguments.length > 2 ? arguments[2] : undefined;
117289
+ const allBlockHeightsToFetch = input.blocks.map(block => {
117290
+ return {
117291
+ blockHash: block.hash,
117292
+ account: block.account
117293
+ };
117294
+ });
117295
+ const allBlockHeights = await this.getBlockHeights(transaction, allBlockHeightsToFetch);
117296
+
117297
+ // Check if any blocks already exist on the ledger that would cause this staple to fail and exit early
117298
+ for (const [blockHash, blockHeight] of Object.entries(allBlockHeights)) {
117299
+ if (blockHeight !== null) {
117300
+ throw new KeetaNetLedgerError('LEDGER_BLOCK_ALREADY_EXISTS', `Block Already Exists: ${blockHash.toString()}`);
117301
+ }
117302
+ }
117264
117303
  const seenBlockHashes = new BlockHash.Set();
117265
117304
  const blockHeights = {};
117266
117305
  const toFetch = [];
@@ -118688,37 +118727,18 @@ function client_ExportBlockOperations(operations) {
118688
118727
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
118689
118728
  return container;
118690
118729
  }
118691
- function client_assertExplicitContextValueLike(input) {
118692
- if (typeof input !== 'object' || input === null) {
118693
- throw new Error(`Found entry which is not a context ${String(input)}`);
118694
- }
118695
- if (!('type' in input) || input.type !== 'context') {
118696
- throw new Error(`Found entry which is not a context ${String(input)}`);
118697
- }
118698
- if (!('kind' in input) || input.kind !== 'explicit') {
118699
- throw new Error(`Found entry which is not an explicit context ${String(input)}`);
118700
- }
118701
- if (!('value' in input)) {
118702
- throw new Error(`Found entry which is not a numeric explicit context ${String(input)}`);
118703
- }
118704
- const typeInput = input.value;
118705
- if (typeof typeInput !== 'number') {
118706
- throw new Error(`Found entry which is not a numeric explicit context ${String(input)}`);
118707
- }
118708
- if (!('contains' in input)) {
118709
- throw new Error(`Found entry which which lacks contains ${JSON.stringify(input)}`);
118710
- }
118711
- if (!Array.isArray(input.contains)) {
118712
- throw new Error(`Found entry which is not a Sequence ${input.contains}`);
118713
- }
118714
- }
118715
118730
  function client_ImportOperationsASN1(input, network) {
118716
118731
  const retval = [];
118717
118732
  for (const entryWrapper of input) {
118718
118733
  const operation = {};
118719
- client_assertExplicitContextValueLike(entryWrapper);
118734
+ if (!client_ASN1CheckUtilities.isASN1ContextTag(entryWrapper, 'explicit')) {
118735
+ throw new Error('Invalid createArgs type for CREATE_IDENTIFIER operation');
118736
+ }
118720
118737
  const type = client_assertOperationType(entryWrapper.value);
118721
118738
  const entry = entryWrapper.contains;
118739
+ if (!Array.isArray(entry)) {
118740
+ throw new Error(`Found entry which is not a Sequence ${typeof entry}`);
118741
+ }
118722
118742
  const typeStr = client_operationTypeToString(type);
118723
118743
  const operationSchema = client_BlockOperationASN1SchemaBase[typeStr];
118724
118744
  if (!operationSchema) {
@@ -118747,16 +118767,24 @@ function client_ImportOperationsASN1(input, network) {
118747
118767
  newKeyValue.validate(network);
118748
118768
  keyValueOut = newKeyValue;
118749
118769
  } else if (key === 'createArguments' && typeStr === 'CREATE_IDENTIFIER') {
118750
- client_assertExplicitContextValueLike(keyValueIn);
118770
+ if (!client_ASN1CheckUtilities.isASN1ContextTag(keyValueIn, 'explicit')) {
118771
+ throw new Error('Invalid createArgs type for CREATE_IDENTIFIER operation');
118772
+ }
118751
118773
  if (keyValueIn.value !== client_AccountKeyAlgorithm.MULTISIG) {
118752
118774
  throw new Error('unrecognized type for multisig create arguments');
118753
118775
  }
118754
- if (keyValueIn.contains.length !== 2 || !Array.isArray(keyValueIn.contains[0])) {
118776
+ if (!Array.isArray(keyValueIn.contains) || keyValueIn.contains.length !== 2) {
118777
+ throw new Error('Invalid createArgs container');
118778
+ }
118779
+ if (!Array.isArray(keyValueIn.contains[0])) {
118755
118780
  throw new Error('Invalid createArgs container');
118756
118781
  }
118757
118782
  keyValueOut = {
118758
118783
  type: keyValueIn.value,
118759
118784
  signers: keyValueIn.contains[0].map(function (value) {
118785
+ if (!client_operations_Buffer.isBuffer(value)) {
118786
+ throw new Error(`Invalid signer value, expected Buffer, got ${typeof value}`);
118787
+ }
118760
118788
  return client_lib_account.fromPublicKeyAndType(value);
118761
118789
  }),
118762
118790
  quorum: keyValueIn.contains[1]
@@ -125017,1855 +125045,1897 @@ class client_RequestTiming {
125017
125045
  }
125018
125046
  client_timing_defineProperty(client_RequestTiming, "defaultLogger", console);
125019
125047
  /* harmony default export */ const src_client_timing = (client_RequestTiming);
125020
- ;// ./src/lib/ledger/index.ts
125021
- var client_Ledger;
125022
- function client_usingCtx2() { var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) { var n = Error(); return n.name = "SuppressedError", n.error = r, n.suppressed = e, n; }, e = {}, n = []; function using(r, e) { if (null != e) { if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (r) var o = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; if (void 0 === o && (o = e[Symbol.dispose || Symbol.for("Symbol.dispose")], r)) var t = o; if ("function" != typeof o) throw new TypeError("Object is not disposable."); t && (o = function () { try { t.call(e); } catch (r) { return Promise.reject(r); } }), n.push({ v: e, d: o, a: r }); } else r && n.push({ d: e, a: r }); return e; } return { e: e, u: using.bind(null, !1), a: using.bind(null, !0), d: function () { var o, t = this.e, s = 0; function next() { for (; o = n.pop();) try { if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next); if (o.d) { var r = o.d.call(o.v); if (o.a) return s |= 2, Promise.resolve(r).then(next, err); } else s |= 1; } catch (r) { return err(r); } if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve(); if (t !== e) throw t; } function err(n) { return t = t !== e ? new r(n, t) : n, next(); } return next(); } }; }
125023
- function client_lib_ledger_defineProperty(e, r, t) { return (r = client_lib_ledger_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
125024
- function client_lib_ledger_toPropertyKey(t) { var i = client_lib_ledger_toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
125025
- function client_lib_ledger_toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
125026
- function client_ledger_classPrivateMethodInitSpec(e, a) { client_ledger_checkPrivateRedeclaration(e, a), a.add(e); }
125027
- function client_ledger_classPrivateFieldInitSpec(e, t, a) { client_ledger_checkPrivateRedeclaration(e, t), t.set(e, a); }
125028
- function client_ledger_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
125029
- function client_ledger_classPrivateFieldGet(s, a) { return s.get(client_ledger_assertClassBrand(s, a)); }
125030
- function client_ledger_classPrivateFieldSet(s, a, r) { return s.set(client_ledger_assertClassBrand(s, a), r), r; }
125031
- function client_ledger_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
125032
-
125033
-
125034
-
125035
-
125036
-
125037
-
125038
-
125039
-
125040
-
125041
-
125042
-
125043
-
125044
-
125045
- /**
125046
- * Kind of ledger
125047
- */
125048
- let client_LedgerKind = /*#__PURE__*/function (LedgerKind) {
125049
- LedgerKind[LedgerKind["REPRESENTATIVE"] = 0] = "REPRESENTATIVE";
125050
- LedgerKind[LedgerKind["ACCOUNT"] = 1] = "ACCOUNT";
125051
- return LedgerKind;
125052
- }({});
125053
-
125054
- /**
125055
- * Ledger configuration
125056
- */
125057
-
125058
- /**
125059
- * Which ledger to store this data in
125060
- */
125061
-
125062
- /**
125063
- * Which ledger(s) to pull the data from
125064
- */
125065
-
125066
- /**
125067
- * A set of votes and a pointer to the next set/page
125068
- */
125069
-
125070
- /**
125071
- * Options for "getVotesAfter"
125072
- */
125073
-
125074
- /**
125075
- * Each transaction can contain the node object making the request to access things like timing information
125076
- */
125077
-
125078
- /**
125079
- * Each Ledger Storage backend must implement this interface
125080
- */
125081
- var client_network = /*#__PURE__*/new WeakMap();
125082
- var client_subnet = /*#__PURE__*/new WeakMap();
125083
- var client_kind = /*#__PURE__*/new WeakMap();
125084
- var client_ledger_privateKey = /*#__PURE__*/new WeakMap();
125085
- var client_computeFeeFromBlocks = /*#__PURE__*/new WeakMap();
125086
- var client_ledger_storage = /*#__PURE__*/new WeakMap();
125087
- var src_client_ledger = /*#__PURE__*/new WeakMap();
125088
- var src_client_cache = /*#__PURE__*/new WeakMap();
125089
- var client_transaction = /*#__PURE__*/new WeakMap();
125090
- var client_LedgerAtomicInterface_brand = /*#__PURE__*/new WeakSet();
125091
- /**
125092
- * Atomic transactional interface to a storage backend
125093
- */
125094
- class client_LedgerAtomicInterface {
125095
- constructor(_transaction2, storage, config, ledger) {
125096
- client_ledger_classPrivateMethodInitSpec(this, client_LedgerAtomicInterface_brand);
125097
- client_ledger_classPrivateFieldInitSpec(this, client_network, void 0);
125098
- client_ledger_classPrivateFieldInitSpec(this, client_subnet, void 0);
125099
- client_ledger_classPrivateFieldInitSpec(this, client_kind, void 0);
125100
- client_ledger_classPrivateFieldInitSpec(this, client_ledger_privateKey, void 0);
125101
- client_ledger_classPrivateFieldInitSpec(this, client_computeFeeFromBlocks, void 0);
125102
- client_ledger_classPrivateFieldInitSpec(this, client_ledger_storage, void 0);
125103
- client_ledger_classPrivateFieldInitSpec(this, src_client_ledger, void 0);
125104
- client_ledger_classPrivateFieldInitSpec(this, src_client_cache, void 0);
125105
- client_ledger_classPrivateFieldInitSpec(this, client_transaction, void 0);
125106
- client_ledger_classPrivateFieldSet(client_network, this, config.network);
125107
- client_ledger_classPrivateFieldSet(client_subnet, this, config.subnet);
125108
- client_ledger_classPrivateFieldSet(client_kind, this, config.kind);
125109
- client_ledger_classPrivateFieldSet(client_ledger_privateKey, this, config.privateKey);
125110
- client_ledger_classPrivateFieldSet(client_computeFeeFromBlocks, this, config.computeFeeFromBlocks);
125111
- client_ledger_classPrivateFieldSet(src_client_ledger, this, ledger);
125112
- client_ledger_classPrivateFieldSet(client_ledger_storage, this, storage);
125113
- client_ledger_classPrivateFieldSet(client_transaction, this, _transaction2);
125048
+ ;// ./src/lib/kv/index.ts
125049
+ function client_kv_defineProperty(e, r, t) { return (r = client_kv_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
125050
+ function client_kv_toPropertyKey(t) { var i = client_kv_toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
125051
+ function client_kv_toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
125114
125052
 
125115
- /**
125116
- * Link the storage driver's cache to the transaction cache
125117
- */
125118
- let existingCache;
125119
- if ('cache' in storage && storage.cache !== undefined) {
125120
- existingCache = storage.cache(_transaction2);
125121
- }
125122
- if (existingCache !== undefined) {
125123
- client_ledger_classPrivateFieldSet(src_client_cache, this, existingCache);
125124
- } else {
125125
- client_ledger_classPrivateFieldSet(src_client_cache, this, new client_cache());
125053
+ class client_KVStorageProviderBase {
125054
+ constructor() {
125055
+ client_kv_defineProperty(this, "id", (0,client_lib_crypto.randomUUID)());
125056
+ }
125057
+ async xor(_ignored_arena, key, _ignored_change, _ignored_options) {
125058
+ if (key.startsWith('@buffer:')) {
125059
+ return;
125126
125060
  }
125061
+ throw new Error('Key provided for XOR must begin with "@buffer"');
125127
125062
  }
125128
- async commit() {
125129
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125130
- client_ledger_classPrivateFieldSet(client_transaction, this, null);
125131
- await client_ledger_classPrivateFieldGet(client_ledger_storage, this).commitTransaction(transaction);
125063
+ }
125064
+ ;// ./src/lib/kv/kv_memory.ts
125065
+ function client_kv_memory_classPrivateMethodInitSpec(e, a) { client_kv_memory_checkPrivateRedeclaration(e, a), a.add(e); }
125066
+ function client_kv_memory_classPrivateFieldInitSpec(e, t, a) { client_kv_memory_checkPrivateRedeclaration(e, t), t.set(e, a); }
125067
+ function client_kv_memory_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
125068
+ function client_kv_memory_classPrivateFieldGet(s, a) { return s.get(client_kv_memory_assertClassBrand(s, a)); }
125069
+ function client_kv_memory_classPrivateFieldSet(s, a, r) { return s.set(client_kv_memory_assertClassBrand(s, a), r), r; }
125070
+ function client_kv_memory_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
125071
+
125072
+
125073
+ const client_nullArena = 'null:43c98976-2282-44c2-819a-769732ceb847';
125074
+ function client_deserialize(value) {
125075
+ if (src_client_BufferStorage.isInstance(value)) {
125076
+ value = value.toString('hex');
125132
125077
  }
125133
- async abort() {
125134
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125135
- client_ledger_classPrivateFieldSet(client_transaction, this, null);
125136
- await client_ledger_classPrivateFieldGet(client_ledger_storage, this).abortTransaction(transaction);
125078
+ return value;
125079
+ }
125080
+ var client_db = /*#__PURE__*/new WeakMap();
125081
+ var client_KVStorageProviderMemory_brand = /*#__PURE__*/new WeakSet();
125082
+ class client_KVStorageProviderMemory extends client_KVStorageProviderBase {
125083
+ constructor() {
125084
+ super();
125085
+ client_kv_memory_classPrivateMethodInitSpec(this, client_KVStorageProviderMemory_brand);
125086
+ client_kv_memory_classPrivateFieldInitSpec(this, client_db, void 0);
125087
+ client_kv_memory_classPrivateFieldSet(client_db, this, {});
125137
125088
  }
125138
- async vote(blocks, otherVotes, quote) {
125139
- if (blocks.length === 0) {
125140
- throw new client_ledger('LEDGER_MISSING_BLOCKS', 'At least one block is required to issue a vote');
125089
+ async set(arena, key, value, options) {
125090
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
125091
+ if (value !== undefined) {
125092
+ if (options !== null && options !== void 0 && options.exclusiveCreate) {
125093
+ if (storeArena[key] !== undefined) {
125094
+ throw new Error('unable to exclusively create this item, already exists');
125095
+ }
125096
+ }
125141
125097
  }
125142
- if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
125143
- throw new Error('Cannot vote on block, no private key loaded');
125098
+ let expiry;
125099
+ if ((options === null || options === void 0 ? void 0 : options.ttl) !== undefined) {
125100
+ expiry = Date.now() + options.ttl;
125144
125101
  }
125145
- if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
125146
- throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
125102
+ if (value === undefined || value === null) {
125103
+ delete storeArena[key];
125104
+ return;
125147
125105
  }
125148
- const privateKey = client_ledger_classPrivateFieldGet(client_ledger_privateKey, this);
125149
- const ledgerPubKey = privateKey.publicKeyString.get();
125150
- if (quote !== undefined) {
125151
- if (otherVotes !== undefined) {
125152
- throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Quote should not be included when requesting permanent votes');
125106
+ storeArena[key] = {
125107
+ value,
125108
+ expiry
125109
+ };
125110
+ }
125111
+ async get(arena, key) {
125112
+ if (arena === null) {
125113
+ arena = client_nullArena;
125114
+ }
125115
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
125116
+ if (!storeArena[key]) {
125117
+ return undefined;
125118
+ }
125119
+ const {
125120
+ expiry,
125121
+ value
125122
+ } = storeArena[key];
125123
+ if (expiry !== undefined) {
125124
+ if (expiry < Date.now()) {
125125
+ delete storeArena[key];
125126
+ return undefined;
125153
125127
  }
125154
- if (!quote.issuer.comparePublicKey(ledgerPubKey)) {
125155
- throw new client_ledger('LEDGER_QUOTE_MISMATCH', 'Provided quote does not match issuer public key');
125128
+ }
125129
+ const retval = client_deserialize(value);
125130
+ return retval;
125131
+ }
125132
+ async getAll(arena) {
125133
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
125134
+ const retval = {};
125135
+ for (const key in storeArena) {
125136
+ const value = await this.get(arena, key);
125137
+ if (value === undefined) {
125138
+ continue;
125156
125139
  }
125140
+ retval[key] = value;
125157
125141
  }
125158
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125159
-
125160
- /**
125161
- * If there are other votes, ensure one of them was issued by
125162
- * us and the blocks are in the same order as the set of
125163
- * blocks we are voting on now
125164
- */
125165
- if (otherVotes !== undefined) {
125166
- let foundOurVote = false;
125167
- const seenVoteUIDs = new Set();
125168
- const seenVoteIssuers = new client_lib_account.Set();
125169
- const possibleFeeBlock = blocks.at(-1);
125170
- let hasFeeBlock = false;
125171
- let blockCount = blocks.length;
125172
- if ((possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.purpose) === client_BlockPurpose.FEE) {
125173
- hasFeeBlock = true;
125174
- blockCount--;
125175
- }
125176
- const requiredFees = new Map();
125177
- for (const checkVote of otherVotes) {
125178
- if (checkVote.quote === true) {
125179
- throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Cannot request permanent votes with quotes');
125180
- }
125181
- if (seenVoteUIDs.has(checkVote.$id)) {
125182
- throw new client_ledger('LEDGER_DUPLICATE_VOTE_FOUND', 'Duplicate vote UID found');
125183
- }
125184
- if (seenVoteIssuers.has(checkVote.issuer)) {
125185
- throw new client_ledger('LEDGER_DUPLICATE_VOTE_ISSUER_FOUND', 'Multiple votes found from same issuer');
125186
- }
125187
- seenVoteIssuers.add(checkVote.issuer);
125188
- seenVoteUIDs.add(checkVote.$id);
125189
- if (checkVote.fee !== undefined) {
125190
- requiredFees.set(checkVote.issuer, checkVote.fee);
125191
- }
125192
- if (checkVote.$permanent) {
125193
- throw new client_ledger('LEDGER_CANNOT_EXCHANGE_PERM_VOTE', 'Asked to exchange a permanent vote for a permanent vote');
125194
- }
125195
- let blocksDifferFromVoteBlocks = checkVote.blocks.length !== blockCount;
125196
-
125197
- /* If they do not differ from length alone, compare block hashes */
125198
- if (!blocksDifferFromVoteBlocks) {
125199
- for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {
125200
- if (!blocks[blockIndex].hash.compareHexString(checkVote.blocks[blockIndex])) {
125201
- blocksDifferFromVoteBlocks = true;
125202
- break;
125203
- }
125204
- }
125205
- }
125206
- if (blocksDifferFromVoteBlocks) {
125207
- throw new client_ledger('LEDGER_BLOCKS_DIFFER_FROM_VOTED_ON', 'Asked to exchange different number of blocks for a permanent vote');
125208
- }
125209
- if (checkVote.issuer.comparePublicKey(ledgerPubKey)) {
125210
- foundOurVote = true;
125211
- }
125212
- }
125213
- if (requiredFees.size > 0) {
125214
- if (!hasFeeBlock) {
125215
- throw new client_ledger('LEDGER_MISSING_REQUIRED_FEE_BLOCK', 'Missing fee block but votes require it');
125216
- }
125217
- if (requiredFees.size !== (possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.length)) {
125218
- throw new client_ledger('LEDGER_REQUIRED_FEE_MISMATCH', 'Fee Block Operations do not match required fees');
125219
- }
125220
- }
125221
-
125222
- // Verify that all required fees have been included in the fee block
125223
- for (const [issuer, fee] of requiredFees) {
125224
- const foundFee = possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.find(operation => {
125225
- var _fee$payTo, _fee$token;
125226
- const expectedPayTo = (_fee$payTo = fee.payTo) !== null && _fee$payTo !== void 0 ? _fee$payTo : issuer;
125227
- const expectedToken = (_fee$token = fee.token) !== null && _fee$token !== void 0 ? _fee$token : client_ledger_classPrivateFieldGet(src_client_ledger, this).baseToken;
125228
- if (operation.type === client_OperationType.SEND && operation.to.comparePublicKey(expectedPayTo)) {
125229
- if (operation.amount !== fee.amount) {
125230
- throw new client_ledger('LEDGER_FEE_AMOUNT_MISMATCH', `Fee Amount Mismatch, found: ${operation.amount} expected: ${fee.amount}`);
125231
- }
125232
- if (!operation.token.comparePublicKey(expectedToken)) {
125233
- throw new client_ledger('LEDGER_FEE_TOKEN_MISMATCH', `Fee Token Mismatch, found: ${operation.token.publicKeyString.get()} expected: ${expectedToken.publicKeyString.get()}`);
125234
- }
125235
- return true;
125236
- }
125237
- return false;
125238
- });
125239
- if (foundFee === undefined) {
125240
- var _fee$payTo$publicKeyS, _fee$payTo2;
125241
- throw new client_ledger('LEDGER_FEE_MISSING', `Missing Required Fee for ${(_fee$payTo$publicKeyS = (_fee$payTo2 = fee.payTo) === null || _fee$payTo2 === void 0 ? void 0 : _fee$payTo2.publicKeyString.get()) !== null && _fee$payTo$publicKeyS !== void 0 ? _fee$payTo$publicKeyS : issuer.publicKeyString.get()}`);
125242
- }
125243
- }
125244
- if (!foundOurVote) {
125245
- throw new client_ledger('LEDGER_NO_PERM_WITHOUT_SELF_TEMP', 'Asked to give a permanent vote without a temporary vote from us');
125246
- }
125142
+ return retval;
125143
+ }
125144
+ async list(arena) {
125145
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
125146
+ return Object.keys(storeArena);
125147
+ }
125148
+ async incr(arena, key, change) {
125149
+ var _previous$value;
125150
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
125151
+ const previous = storeArena[key];
125152
+ let previousValue = (_previous$value = previous === null || previous === void 0 ? void 0 : previous.value) !== null && _previous$value !== void 0 ? _previous$value : 0;
125153
+ if (typeof previousValue !== 'number') {
125154
+ throw new Error('May not increment non-number');
125247
125155
  }
125248
- const allLedgerHeads = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125249
- const needToGetHeadFor = new client_lib_account.Set(allLedgerHeads.keys());
125250
- const allHeads = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlockHashes(transaction, needToGetHeadFor);
125251
- for (const [account, expectedBlock] of allLedgerHeads.entries()) {
125252
- const accountHead = allHeads[account.publicKeyString.get()];
125253
- if (accountHead === null) {
125254
- if (!expectedBlock.$opening) {
125255
- throw new client_ledger('LEDGER_NOT_OPENING', 'Cannot vote on non-opening block for an empty account');
125256
- }
125257
- continue;
125258
- }
125259
- if (expectedBlock.$opening) {
125260
- throw new client_ledger('LEDGER_NOT_EMPTY', 'Cannot vote on opening block for a non-empty account');
125261
- }
125262
- if (expectedBlock.previous.toString() !== accountHead.toString()) {
125263
- throw new client_ledger('LEDGER_NOT_SUCCESSOR', 'The block is not the successor to the account head block');
125156
+ let newExpiry;
125157
+ if ((previous === null || previous === void 0 ? void 0 : previous.expiry) !== undefined) {
125158
+ if (previous.expiry < Date.now()) {
125159
+ previousValue = 0;
125160
+ } else {
125161
+ newExpiry = previous.expiry;
125264
125162
  }
125265
125163
  }
125266
-
125267
- /**
125268
- * Ensure we have no active vote for another conflicting successor of this block's parent (previous),
125269
- * which could cause a fork
125270
- */
125271
- const previousToCheckFor = blocks.map(b => b.previous);
125272
- const allPrevious = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesFromMultiplePrevious(transaction, previousToCheckFor, 'both', client_lib_account.toAccount(ledgerPubKey));
125273
- for (const block of blocks) {
125274
- const previousVotes = allPrevious[block.previous.toString()];
125275
- if (previousVotes !== null && previousVotes.length > 0) {
125276
- /**
125277
- * If we do have a previous vote, we can
125278
- * replace it with a permanent vote if
125279
- * there is only 1 previous vote, issued by us,
125280
- * and it's a short vote
125281
- */
125282
-
125283
- let mayReplace = false;
125284
- if (previousVotes.length === 1 && otherVotes !== undefined && otherVotes.length !== 0) {
125285
- const ourVote = previousVotes[0];
125286
- mayReplace = !ourVote.$permanent && ourVote.issuer.comparePublicKey(ledgerPubKey);
125287
- }
125288
- if (!mayReplace) {
125289
- throw new client_ledger('LEDGER_SUCCESSOR_VOTE_EXISTS', `We cannot vote for this block (hash=${block.hash.toString()}), we have an existing vote for a successor (previous votes = ${JSON.stringify(client_toJSONSerializable(previousVotes))})`);
125290
- }
125291
- }
125164
+ const newVal = previousValue + change;
125165
+ storeArena[key] = {
125166
+ value: newVal,
125167
+ expiry: newExpiry
125168
+ };
125169
+ return BigInt(newVal);
125170
+ }
125171
+ async xor(arena, key, change) {
125172
+ await super.xor(arena, key, change);
125173
+ const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, client_nullArena);
125174
+ const previous = storeArena[key];
125175
+ const value = previous === null || previous === void 0 ? void 0 : previous.value;
125176
+ if (value === undefined) {
125177
+ storeArena[key] = {
125178
+ value: change
125179
+ };
125180
+ return;
125292
125181
  }
125293
-
125294
- /**
125295
- * If no other votes have been supplied, validate that the blocks are valid, and issue a short vote
125296
- */
125297
- if (otherVotes === undefined) {
125298
- const vote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'VOTE', quote);
125299
- const blocksAndVote = src_client_VoteStaple.fromVotesAndBlocks([vote], blocks);
125300
- await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
125301
- return vote;
125182
+ if (!src_client_BufferStorage.isInstance(value) || previous.expiry !== undefined) {
125183
+ throw new Error('May only use XOR on keys containing BufferStorage without expiry');
125302
125184
  }
125185
+ const valueBigInt = value.toBigInt();
125186
+ const changeBigInt = change.toBigInt();
125187
+ const valueLength = Math.max(value.length, change.length);
125188
+ const newValue = valueBigInt ^ changeBigInt;
125189
+ storeArena[key] = {
125190
+ value: new src_client_BufferStorage(newValue, valueLength)
125191
+ };
125192
+ }
125193
+ }
125194
+ function client_getArena(arena) {
125195
+ if (client_kv_memory_classPrivateFieldGet(client_db, this)[arena] === undefined) {
125196
+ client_kv_memory_classPrivateFieldGet(client_db, this)[arena] = {};
125197
+ }
125198
+ return client_kv_memory_classPrivateFieldGet(client_db, this)[arena];
125199
+ }
125200
+ /* harmony default export */ const client_kv_memory = (client_KVStorageProviderMemory);
125201
+ ;// ./src/lib/stats.ts
125202
+ function client_stats_classPrivateFieldInitSpec(e, t, a) { client_stats_checkPrivateRedeclaration(e, t), t.set(e, a); }
125203
+ function client_stats_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
125204
+ function client_stats_classPrivateFieldGet(s, a) { return s.get(client_stats_assertClassBrand(s, a)); }
125205
+ function client_stats_classPrivateFieldSet(s, a, r) { return s.set(client_stats_assertClassBrand(s, a), r), r; }
125206
+ function client_stats_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
125207
+ function client_stats_defineProperty(e, r, t) { return (r = client_stats_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
125208
+ function client_stats_toPropertyKey(t) { var i = client_stats_toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
125209
+ function client_stats_toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
125303
125210
 
125304
- /**
125305
- * Validate the votes are sufficient weight and grant
125306
- * our permanent vote
125307
- */
125308
- const votesSufficient = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateVotingWeight).call(this, otherVotes);
125309
- if (votesSufficient !== true) {
125310
- throw new client_ledger('LEDGER_INSUFFICIENT_VOTING_WEIGHT', 'Unable to create a vote from these votes, they do not represent enough voting power');
125311
- }
125312
125211
 
125313
- /**
125314
- * Serial number
125315
- */
125316
- const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
125317
- const wipVote = new src_client_VoteBuilder(privateKey);
125318
- for (const block of blocks) {
125319
- wipVote.addBlock(block);
125320
- }
125321
- const vote = await wipVote.seal(serial, null);
125322
- const blocksAndVote = src_client_VoteStaple.fromVotesAndBlocks([vote], blocks);
125323
125212
 
125324
- /**
125325
- * Add this pending vote to our side ledger;
125326
- * Replacing an existing temporary vote with a permanent one
125327
- */
125328
- await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
125329
- return vote;
125213
+ /**
125214
+ * Size of the XOR buffer objects -- we use them for block hashes so they
125215
+ * should be the same size as a block hash
125216
+ */
125217
+ const client_XOR_BUFFER_SIZE = client_HashFunctionLength;
125218
+ const client_durationRanges = {
125219
+ '-1ms': [-1, -1],
125220
+ '0ms': [0, 0],
125221
+ '10ms': [1, 10],
125222
+ '100ms': [11, 100],
125223
+ '200ms': [101, 200],
125224
+ '300ms': [201, 300],
125225
+ '400ms': [301, 400],
125226
+ '500ms': [401, 500],
125227
+ '600ms': [501, 600],
125228
+ '700ms': [601, 700],
125229
+ '800ms': [701, 800],
125230
+ '900ms': [801, 900],
125231
+ '1000ms': [901, 1000],
125232
+ '1500ms': [1001, 1500],
125233
+ '2000ms': [1501, 2000],
125234
+ '5000ms': [2001, 5000],
125235
+ '10000ms': [5001, 10000],
125236
+ '100000ms': [10001, 100000],
125237
+ 'ExtraLong': [100000, Number.MAX_SAFE_INTEGER]
125238
+ };
125239
+ class client_stats_StatsPending {
125240
+ constructor() {
125241
+ client_stats_defineProperty(this, "localDBIncr", {});
125242
+ client_stats_defineProperty(this, "localDBXOR", {});
125243
+ }
125244
+ consume() {
125245
+ const incrChanges = this.localDBIncr;
125246
+ this.localDBIncr = {};
125247
+ const xorChanges = this.localDBXOR;
125248
+ this.localDBXOR = {};
125249
+ return {
125250
+ incrChanges,
125251
+ xorChanges
125252
+ };
125330
125253
  }
125331
- async quote(blocks) {
125332
- await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125333
- const quote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'QUOTE');
125334
- return quote;
125254
+ compoundKey(arena, key) {
125255
+ const compoundKey = [arena, key].join('|');
125256
+ return compoundKey;
125335
125257
  }
125336
- async add(votesAndBlocks, from) {
125337
- var _classPrivateFieldGet2, _classPrivateFieldGet3, _classPrivateFieldGet4, _classPrivateFieldGet5;
125338
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125339
- switch (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode) {
125340
- case 'read-only':
125341
- throw new Error('Cannot add blocks to a read-only ledger');
125342
- case 'bootstrap-only':
125343
- if (from === 'bootstrap') {
125344
- break;
125345
- }
125346
- throw new Error('Cannot add blocks to a read-only ledger (except for bootstrapping)');
125347
- case 'read-write':
125348
- case 'no-voting':
125349
- break;
125350
- default:
125351
- throw new Error(`internal error: invalid ledger write mode: ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode}`);
125258
+ incrCompoundKey(compoundKey, change) {
125259
+ if (this.localDBIncr[compoundKey] === undefined) {
125260
+ this.localDBIncr[compoundKey] = 0;
125352
125261
  }
125262
+ this.localDBIncr[compoundKey] += change;
125263
+ }
125264
+ incr(arena, key) {
125265
+ let change = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
125266
+ const compoundKey = this.compoundKey(arena, key);
125267
+ this.incrCompoundKey(compoundKey, change);
125268
+ }
125269
+ xor(key, change) {
125270
+ const changeValue = typeof change === 'bigint' ? change : change.toBigInt();
125271
+ const existingValue = this.localDBXOR[key];
125272
+ if (existingValue === undefined) {
125273
+ this.localDBXOR[key] = changeValue;
125274
+ return;
125275
+ }
125276
+ this.localDBXOR[key] ^= changeValue;
125277
+ }
125278
+ merge(pending) {
125353
125279
  const {
125354
- votes,
125355
- blocks
125356
- } = votesAndBlocks;
125357
- if (votes.length < 1) {
125358
- throw new Error('Must have at least 1 vote in the staple');
125280
+ incrChanges,
125281
+ xorChanges
125282
+ } = pending.consume();
125283
+ // Merge incr changes
125284
+ for (const [key, value] of Object.entries(incrChanges)) {
125285
+ this.incrCompoundKey(key, value);
125359
125286
  }
125360
- for (const block of blocks) {
125361
- if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
125362
- throw new Error('Cannot process block for a different network');
125363
- }
125364
- if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
125365
- throw new Error('Cannot process block for a different subnet');
125366
- }
125287
+
125288
+ // Merge xor changes
125289
+ for (const [key, value] of Object.entries(xorChanges)) {
125290
+ this.xor(key, value);
125367
125291
  }
125368
- for (const vote of votes) {
125369
- if (!vote.$permanent) {
125370
- throw new Error('Can only insert permanent votes');
125371
- }
125292
+ }
125293
+ }
125294
+ var client_syncPromise = /*#__PURE__*/new WeakMap();
125295
+ var client_kv = /*#__PURE__*/new WeakMap();
125296
+ class client_Stats extends client_stats_StatsPending {
125297
+ constructor(config) {
125298
+ super();
125299
+ client_stats_classPrivateFieldInitSpec(this, client_syncPromise, void 0);
125300
+ client_stats_classPrivateFieldInitSpec(this, client_kv, void 0);
125301
+ let kv = config.kv;
125302
+ if (kv === null) {
125303
+ kv = new client_kv_memory();
125372
125304
  }
125373
- const weightTiming = (_classPrivateFieldGet2 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet2 === void 0 ? void 0 : _classPrivateFieldGet2.timing.startTime('db-add/getWeight');
125374
- const votesSufficient = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateVotingWeight).call(this, votesAndBlocks.votes);
125375
- if (votesSufficient !== true) {
125376
- throw new client_ledger('LEDGER_INSUFFICIENT_VOTING_WEIGHT', 'Votes attached do not represent enough voting power');
125305
+ client_stats_classPrivateFieldSet(client_kv, this, kv);
125306
+ }
125307
+
125308
+ // Return all keys from durationRanges
125309
+ static durationBreakdownList() {
125310
+ // We know the keys are all valid to the type, but typescript does not know this
125311
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
125312
+ return Object.keys(client_durationRanges);
125313
+ }
125314
+ static assertDurationBreakdown(duration) {
125315
+ if (!(duration in client_durationRanges)) {
125316
+ throw new Error(`Invalid duration: ${duration}`);
125377
125317
  }
125378
- weightTiming === null || weightTiming === void 0 || weightTiming.end();
125379
- const changesTiming = (_classPrivateFieldGet3 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.timing.startTime('db-add/computeEffectOfBlocks');
125380
- const changes = client_computeEffectOfBlocks(votesAndBlocks.blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125381
- changesTiming === null || changesTiming === void 0 || changesTiming.end();
125382
- const adjustTiming = (_classPrivateFieldGet4 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.timing.startTime('db-add/adjust');
125383
- const voteStaples = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).adjust(transaction, votesAndBlocks, changes);
125384
- adjustTiming === null || adjustTiming === void 0 || adjustTiming.end();
125385
- const postambleTiming = (_classPrivateFieldGet5 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.timing.startTime('db-add/postamble');
125386
- /**
125387
- * Add all the block hashes to the node checksum
125388
- */
125389
- const ourNode = client_ledger_classPrivateFieldGet(src_client_ledger, this).node;
125390
- if (ourNode) {
125391
- for (const staple of voteStaples) {
125392
- for (const block of staple.blocks) {
125393
- ourNode.stats.xor('ledgerChecksum', block.hash);
125394
- }
125318
+ }
125319
+ // Get duration key for specific number
125320
+ static durationBreakdown(duration) {
125321
+ // Loop through ranges and select key with range that fits around duration
125322
+
125323
+ if (duration < 0) {
125324
+ duration = 0;
125325
+ }
125326
+ for (const name of this.durationBreakdownList()) {
125327
+ const [min, max] = client_durationRanges[name];
125328
+ if (duration >= min && (max === undefined || duration <= max)) {
125329
+ return name;
125395
125330
  }
125396
125331
  }
125397
- postambleTiming === null || postambleTiming === void 0 || postambleTiming.end();
125398
- return voteStaples;
125332
+ throw new Error(`Time frame not found for duration: ${duration}`);
125399
125333
  }
125400
- async getBalance(account, token) {
125401
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125402
- const balance = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBalance(transaction, account, token);
125403
- if (balance < 0n) {
125404
- throw new Error(`internal error: Account with negative balance: ${account.publicKeyString.get()}/${client_lib_account.toPublicKeyString(token)}: ${balance}`);
125334
+ static placeholderTimingData() {
125335
+ const ret = {};
125336
+ for (const key of this.durationBreakdownList()) {
125337
+ ret[key] = {
125338
+ count: -1,
125339
+ range: client_stats_assertClassBrand(client_Stats, this, client_getDurationRange).call(this, key)
125340
+ };
125405
125341
  }
125406
- return balance;
125342
+
125343
+ // We know this fits TimeStats because we just created it with all of the keys
125344
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
125345
+ return ret;
125407
125346
  }
125408
- async getAllBalances(account) {
125409
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125410
- const balances = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAllBalances(transaction, account);
125411
- for (const {
125412
- token,
125413
- balance
125414
- } of balances) {
125415
- if (balance < 0n) {
125416
- throw new Error(`internal error: Account with negative balance: ${account.publicKeyString.get()}/${token.publicKeyString.get()}: ${balance}`);
125417
- }
125347
+ async getXor(key) {
125348
+ await client_stats_classPrivateFieldGet(client_syncPromise, this);
125349
+ const bufferKey = `@buffer:${key}`;
125350
+ const baseString = await client_stats_classPrivateFieldGet(client_kv, this).get(null, bufferKey);
125351
+ let base = 0n;
125352
+ if (baseString !== undefined) {
125353
+ base = BigInt(`0x${baseString}`);
125418
125354
  }
125419
- return balances;
125420
- }
125421
- async getAccountCertificates(account) {
125422
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125423
- return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountCertificates(client_ledger_classPrivateFieldGet(client_transaction, this), account);
125355
+ let local = 0n;
125356
+ if (this.localDBXOR[key] !== undefined) {
125357
+ local = this.localDBXOR[key];
125358
+ }
125359
+ const computed = base ^ local;
125360
+ const retval = new src_client_BufferStorage(computed, client_XOR_BUFFER_SIZE);
125361
+ return retval;
125424
125362
  }
125425
- async getAccountCertificateByHash(account, hash) {
125426
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125427
- return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountCertificateByHash(client_ledger_classPrivateFieldGet(client_transaction, this), account, hash);
125363
+
125364
+ // Calculate key and increment for specific duration/category
125365
+ addTimingPoint(arena, category, duration) {
125366
+ let returnOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
125367
+ const breakdown = client_Stats.durationBreakdown(duration);
125368
+ const params = [arena, `${category}@${breakdown}`, 1];
125369
+ if (returnOnly !== true) {
125370
+ this.incr(...params);
125371
+ }
125372
+ return params;
125428
125373
  }
125429
- async listACLsByPrincipal(principal, entityList) {
125430
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125431
- const permissions = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listACLsByPrincipal(transaction, principal, entityList);
125432
- return permissions;
125374
+ addRequestTiming(arena, timing) {
125375
+ let returnOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
125376
+ const retval = [];
125377
+ for (const sectionInfo of Object.values(timing.getAllTiming())) {
125378
+ const duration = sectionInfo.duration;
125379
+ const name = sectionInfo.name;
125380
+ retval.push(this.addTimingPoint(arena, name, duration, returnOnly));
125381
+ }
125382
+ return retval;
125433
125383
  }
125434
- async listACLsByEntity(entity) {
125435
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125436
- const permissions = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listACLsByEntity(transaction, entity);
125437
- return permissions;
125384
+ async get(arena, key) {
125385
+ await client_stats_classPrivateFieldGet(client_syncPromise, this);
125386
+ const compoundKey = this.compoundKey(arena, key);
125387
+ let base = await client_stats_classPrivateFieldGet(client_kv, this).get('stats', compoundKey);
125388
+ if (base === undefined) {
125389
+ base = 0;
125390
+ }
125391
+ if (typeof base === 'string') {
125392
+ base = Number(base);
125393
+ }
125394
+ if (typeof base !== 'number' || isNaN(base)) {
125395
+ throw new Error('internal error: corrupt data in stats table');
125396
+ }
125397
+ let local = 0;
125398
+ if (this.localDBIncr[compoundKey] !== undefined) {
125399
+ local = this.localDBIncr[compoundKey];
125400
+ }
125401
+ return base + local;
125438
125402
  }
125439
- async votingPower(rep) {
125440
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125441
- const weight = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction, rep);
125442
125403
 
125443
- /* Voting Power = Weight (for now) */
125444
- return weight;
125445
- }
125446
- async getVotes(block) {
125447
- let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125448
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125449
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotes(transaction, block, from);
125404
+ // Get all timing data from specific arena/category
125405
+ async getTimingData(arena, category) {
125406
+ const retval = client_Stats.placeholderTimingData();
125407
+ const keys = Object.keys(retval);
125408
+ client_assertDurationBreakdowns.call(client_Stats, keys);
125409
+ await Promise.all(keys.map(async breakdown => {
125410
+ const key = `${category}@${breakdown}`;
125411
+ const range = client_getDurationRange.call(client_Stats, breakdown);
125412
+ let count = -1;
125413
+ try {
125414
+ count = await this.get(arena, key);
125415
+ } catch (_ignored_error) {
125416
+ /* Errors fetching single stat are ignored */
125417
+ } finally {
125418
+ retval[breakdown] = {
125419
+ count,
125420
+ range
125421
+ };
125422
+ }
125423
+ }));
125450
125424
  return retval;
125451
125425
  }
125452
- async getVotesFromMultiplePrevious(prevBlocks) {
125453
- let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125454
- let issuer = arguments.length > 2 ? arguments[2] : undefined;
125455
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125456
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesFromMultiplePrevious(transaction, prevBlocks, from, issuer);
125457
- return retval;
125426
+ async sync() {
125427
+ const {
125428
+ incrChanges,
125429
+ xorChanges
125430
+ } = this.consume();
125431
+ await client_stats_classPrivateFieldGet(client_syncPromise, this);
125432
+ client_stats_classPrivateFieldSet(client_syncPromise, this, (async () => {
125433
+ const updatePromises = [];
125434
+ for (const [key, value] of Object.entries(incrChanges)) {
125435
+ if (value === undefined) {
125436
+ continue;
125437
+ }
125438
+ updatePromises.push(client_stats_classPrivateFieldGet(client_kv, this).incr('stats', key, value));
125439
+ }
125440
+ for (const [key, value] of Object.entries(xorChanges)) {
125441
+ if (value === undefined) {
125442
+ continue;
125443
+ }
125444
+ const valueBuffer = new src_client_BufferStorage(value, client_XOR_BUFFER_SIZE);
125445
+ const bufferKey = `@buffer:${key}`;
125446
+ updatePromises.push(client_stats_classPrivateFieldGet(client_kv, this).xor(null, bufferKey, valueBuffer));
125447
+ }
125448
+ await Promise.all(updatePromises);
125449
+ })());
125450
+ await client_stats_classPrivateFieldGet(client_syncPromise, this);
125451
+ client_stats_classPrivateFieldSet(client_syncPromise, this, undefined);
125458
125452
  }
125459
- async getBlockFromPrevious(block, from) {
125460
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125461
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlockFromPrevious(transaction, block, from);
125462
- return retval;
125453
+ }
125454
+ function client_assertDurationBreakdowns(durations) {
125455
+ for (const duration of durations) {
125456
+ this.assertDurationBreakdown(duration);
125463
125457
  }
125464
- async getHeadBlocks(accounts, from) {
125465
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125466
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlocks(transaction, accounts, from);
125467
- return retval;
125458
+ }
125459
+ function client_getDurationRange(duration) {
125460
+ this.assertDurationBreakdown(duration);
125461
+ const range = client_durationRanges[duration];
125462
+ if (!range) {
125463
+ throw new Error(`Could not get range for invalid duration: ${duration}, got range ${range}`);
125468
125464
  }
125469
- async getHeadBlock(account, from) {
125470
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125471
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlock(transaction, account, from);
125472
- return retval;
125465
+
125466
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
125467
+ return range;
125468
+ }
125469
+ /* harmony default export */ const client_stats = (client_Stats);
125470
+ ;// ./src/lib/ledger/index.ts
125471
+ var client_Ledger;
125472
+ function client_usingCtx2() { var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) { var n = Error(); return n.name = "SuppressedError", n.error = r, n.suppressed = e, n; }, e = {}, n = []; function using(r, e) { if (null != e) { if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined."); if (r) var o = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")]; if (void 0 === o && (o = e[Symbol.dispose || Symbol.for("Symbol.dispose")], r)) var t = o; if ("function" != typeof o) throw new TypeError("Object is not disposable."); t && (o = function () { try { t.call(e); } catch (r) { return Promise.reject(r); } }), n.push({ v: e, d: o, a: r }); } else r && n.push({ d: e, a: r }); return e; } return { e: e, u: using.bind(null, !1), a: using.bind(null, !0), d: function () { var o, t = this.e, s = 0; function next() { for (; o = n.pop();) try { if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next); if (o.d) { var r = o.d.call(o.v); if (o.a) return s |= 2, Promise.resolve(r).then(next, err); } else s |= 1; } catch (r) { return err(r); } if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve(); if (t !== e) throw t; } function err(n) { return t = t !== e ? new r(n, t) : n, next(); } return next(); } }; }
125473
+ function client_lib_ledger_defineProperty(e, r, t) { return (r = client_lib_ledger_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
125474
+ function client_lib_ledger_toPropertyKey(t) { var i = client_lib_ledger_toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
125475
+ function client_lib_ledger_toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
125476
+ function client_ledger_classPrivateMethodInitSpec(e, a) { client_ledger_checkPrivateRedeclaration(e, a), a.add(e); }
125477
+ function client_ledger_classPrivateFieldInitSpec(e, t, a) { client_ledger_checkPrivateRedeclaration(e, t), t.set(e, a); }
125478
+ function client_ledger_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
125479
+ function client_ledger_classPrivateFieldGet(s, a) { return s.get(client_ledger_assertClassBrand(s, a)); }
125480
+ function client_ledger_classPrivateFieldSet(s, a, r) { return s.set(client_ledger_assertClassBrand(s, a), r), r; }
125481
+ function client_ledger_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
125482
+
125483
+
125484
+
125485
+
125486
+
125487
+
125488
+
125489
+
125490
+
125491
+
125492
+
125493
+
125494
+
125495
+
125496
+ /**
125497
+ * Kind of ledger
125498
+ */
125499
+ let client_LedgerKind = /*#__PURE__*/function (LedgerKind) {
125500
+ LedgerKind[LedgerKind["REPRESENTATIVE"] = 0] = "REPRESENTATIVE";
125501
+ LedgerKind[LedgerKind["ACCOUNT"] = 1] = "ACCOUNT";
125502
+ return LedgerKind;
125503
+ }({});
125504
+
125505
+ /**
125506
+ * Ledger configuration
125507
+ */
125508
+
125509
+ /**
125510
+ * Which ledger to store this data in
125511
+ */
125512
+
125513
+ /**
125514
+ * Which ledger(s) to pull the data from
125515
+ */
125516
+
125517
+ /**
125518
+ * A set of votes and a pointer to the next set/page
125519
+ */
125520
+
125521
+ /**
125522
+ * Options for "getVotesAfter"
125523
+ */
125524
+
125525
+ /**
125526
+ * Each transaction can contain the node object making the request to access things like timing information
125527
+ */
125528
+
125529
+ class client_LedgerStorageTransactionBase {
125530
+ constructor(options) {
125531
+ var _options$moment, _options$readOnly;
125532
+ this.node = options.node;
125533
+ this.moment = (_options$moment = options.moment) !== null && _options$moment !== void 0 ? _options$moment : new Date();
125534
+ this.identifier = options.identifier;
125535
+ this.readOnly = (_options$readOnly = options.readOnly) !== null && _options$readOnly !== void 0 ? _options$readOnly : true;
125536
+ this.statsPending = new StatsPending();
125473
125537
  }
125474
- async getAccountRep(account) {
125475
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125476
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountRep(transaction, account);
125477
- return retval;
125538
+ }
125539
+
125540
+ /**
125541
+ * Each Ledger Storage backend must implement this interface
125542
+ */
125543
+ var client_network = /*#__PURE__*/new WeakMap();
125544
+ var client_subnet = /*#__PURE__*/new WeakMap();
125545
+ var client_kind = /*#__PURE__*/new WeakMap();
125546
+ var client_ledger_privateKey = /*#__PURE__*/new WeakMap();
125547
+ var client_computeFeeFromBlocks = /*#__PURE__*/new WeakMap();
125548
+ var client_ledger_storage = /*#__PURE__*/new WeakMap();
125549
+ var src_client_ledger = /*#__PURE__*/new WeakMap();
125550
+ var src_client_cache = /*#__PURE__*/new WeakMap();
125551
+ var client_transaction = /*#__PURE__*/new WeakMap();
125552
+ var client_LedgerAtomicInterface_brand = /*#__PURE__*/new WeakSet();
125553
+ /**
125554
+ * Atomic transactional interface to a storage backend
125555
+ */
125556
+ class client_LedgerAtomicInterface {
125557
+ constructor(_transaction2, storage, config, ledger) {
125558
+ client_ledger_classPrivateMethodInitSpec(this, client_LedgerAtomicInterface_brand);
125559
+ client_ledger_classPrivateFieldInitSpec(this, client_network, void 0);
125560
+ client_ledger_classPrivateFieldInitSpec(this, client_subnet, void 0);
125561
+ client_ledger_classPrivateFieldInitSpec(this, client_kind, void 0);
125562
+ client_ledger_classPrivateFieldInitSpec(this, client_ledger_privateKey, void 0);
125563
+ client_ledger_classPrivateFieldInitSpec(this, client_computeFeeFromBlocks, void 0);
125564
+ client_ledger_classPrivateFieldInitSpec(this, client_ledger_storage, void 0);
125565
+ client_ledger_classPrivateFieldInitSpec(this, src_client_ledger, void 0);
125566
+ client_ledger_classPrivateFieldInitSpec(this, src_client_cache, void 0);
125567
+ client_ledger_classPrivateFieldInitSpec(this, client_transaction, void 0);
125568
+ client_ledger_classPrivateFieldSet(client_network, this, config.network);
125569
+ client_ledger_classPrivateFieldSet(client_subnet, this, config.subnet);
125570
+ client_ledger_classPrivateFieldSet(client_kind, this, config.kind);
125571
+ client_ledger_classPrivateFieldSet(client_ledger_privateKey, this, config.privateKey);
125572
+ client_ledger_classPrivateFieldSet(client_computeFeeFromBlocks, this, config.computeFeeFromBlocks);
125573
+ client_ledger_classPrivateFieldSet(src_client_ledger, this, ledger);
125574
+ client_ledger_classPrivateFieldSet(client_ledger_storage, this, storage);
125575
+ client_ledger_classPrivateFieldSet(client_transaction, this, _transaction2);
125576
+
125577
+ /**
125578
+ * Link the storage driver's cache to the transaction cache
125579
+ */
125580
+ let existingCache;
125581
+ if ('cache' in storage && storage.cache !== undefined) {
125582
+ existingCache = storage.cache(_transaction2);
125583
+ }
125584
+ if (existingCache !== undefined) {
125585
+ client_ledger_classPrivateFieldSet(src_client_cache, this, existingCache);
125586
+ } else {
125587
+ client_ledger_classPrivateFieldSet(src_client_cache, this, new client_cache());
125588
+ }
125478
125589
  }
125479
- async getAccountInfo(account) {
125590
+ async commit() {
125591
+ var _classPrivateFieldGet2;
125480
125592
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125481
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountInfo(transaction, account);
125482
- return retval;
125593
+ client_ledger_classPrivateFieldSet(client_transaction, this, null);
125594
+ await client_ledger_classPrivateFieldGet(client_ledger_storage, this).commitTransaction(transaction);
125595
+ (_classPrivateFieldGet2 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet2 === void 0 || _classPrivateFieldGet2.stats.merge(transaction.statsPending);
125483
125596
  }
125484
- async getBlock(blockhash) {
125485
- let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125597
+ async abort() {
125486
125598
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125487
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlock(transaction, blockhash, from);
125488
- return retval;
125599
+ client_ledger_classPrivateFieldSet(client_transaction, this, null);
125600
+ await client_ledger_classPrivateFieldGet(client_ledger_storage, this).abortTransaction(transaction);
125489
125601
  }
125490
- async getVoteStaple(stapleBlockHash) {
125491
- let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125492
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125493
- const results = await this.getVoteStaples([stapleBlockHash], from);
125494
- const retval = results.get(stapleBlockHash);
125495
- if (retval === undefined) {
125496
- throw new Error(`internal error: missing vote staple for ${stapleBlockHash}`);
125602
+ async vote(blocks, otherVotes, quote) {
125603
+ if (blocks.length === 0) {
125604
+ throw new client_ledger('LEDGER_MISSING_BLOCKS', 'At least one block is required to issue a vote');
125497
125605
  }
125498
- return retval;
125499
- }
125500
- async getVoteStaples(stapleBlockHashes) {
125501
- let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125502
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125503
- if (stapleBlockHashes.length === 0) {
125504
- return new client_VoteBlockHashMap();
125606
+ if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
125607
+ throw new Error('Cannot vote on block, no private key loaded');
125505
125608
  }
125506
- if (stapleBlockHashes.length > 10000) {
125507
- throw new Error('Cannot fetch more than 10,000 vote staples at once');
125609
+ if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
125610
+ throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
125508
125611
  }
125509
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaples(transaction, stapleBlockHashes, from);
125510
- return retval;
125511
- }
125512
- async getHistory(account, start) {
125513
- let limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 25;
125514
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125515
- const voteStapleHashes = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHistory(transaction, account, start, limit);
125516
- const voteStaplesMap = await this.getVoteStaples(voteStapleHashes, 'main');
125517
- const voteStaples = voteStapleHashes.map(function (voteStapleHash) {
125518
- const voteStaple = voteStaplesMap.get(voteStapleHash);
125519
- if (voteStaple === undefined || voteStaple === null) {
125520
- throw new Error(`internal error: missing vote staple for ${voteStapleHash}`);
125612
+ const privateKey = client_ledger_classPrivateFieldGet(client_ledger_privateKey, this);
125613
+ const ledgerPubKey = privateKey.publicKeyString.get();
125614
+ if (quote !== undefined) {
125615
+ if (otherVotes !== undefined) {
125616
+ throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Quote should not be included when requesting permanent votes');
125617
+ }
125618
+ if (!quote.issuer.comparePublicKey(ledgerPubKey)) {
125619
+ throw new client_ledger('LEDGER_QUOTE_MISMATCH', 'Provided quote does not match issuer public key');
125521
125620
  }
125522
- return voteStaple;
125523
- });
125524
- return voteStaples;
125525
- }
125526
- async getStaplesFromBlockHashes(hashes) {
125527
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125528
- if (client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaplesFromBlockHash) {
125529
- const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaplesFromBlockHash(transaction, hashes, 'main');
125530
- return retval;
125531
125621
  }
125532
- const staples = [];
125533
- const seenVoteUIDs = new Set();
125534
- const seenBlockHashes = new client_block_BlockHash.Set();
125535
- for (const blockHash of hashes) {
125536
- if (seenBlockHashes.has(blockHash)) {
125537
- continue;
125622
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125623
+
125624
+ /**
125625
+ * If there are other votes, ensure one of them was issued by
125626
+ * us and the blocks are in the same order as the set of
125627
+ * blocks we are voting on now
125628
+ */
125629
+ if (otherVotes !== undefined) {
125630
+ let foundOurVote = false;
125631
+ const seenVoteUIDs = new Set();
125632
+ const seenVoteIssuers = new client_lib_account.Set();
125633
+ const possibleFeeBlock = blocks.at(-1);
125634
+ let hasFeeBlock = false;
125635
+ let blockCount = blocks.length;
125636
+ if ((possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.purpose) === client_BlockPurpose.FEE) {
125637
+ hasFeeBlock = true;
125638
+ blockCount--;
125538
125639
  }
125640
+ const requiredFees = new Map();
125641
+ for (const checkVote of otherVotes) {
125642
+ if (checkVote.quote === true) {
125643
+ throw new client_ledger('LEDGER_PERM_VOTE_WITH_QUOTE', 'Cannot request permanent votes with quotes');
125644
+ }
125645
+ if (seenVoteUIDs.has(checkVote.$id)) {
125646
+ throw new client_ledger('LEDGER_DUPLICATE_VOTE_FOUND', 'Duplicate vote UID found');
125647
+ }
125648
+ if (seenVoteIssuers.has(checkVote.issuer)) {
125649
+ throw new client_ledger('LEDGER_DUPLICATE_VOTE_ISSUER_FOUND', 'Multiple votes found from same issuer');
125650
+ }
125651
+ seenVoteIssuers.add(checkVote.issuer);
125652
+ seenVoteUIDs.add(checkVote.$id);
125653
+ if (checkVote.fee !== undefined) {
125654
+ requiredFees.set(checkVote.issuer, checkVote.fee);
125655
+ }
125656
+ if (checkVote.$permanent) {
125657
+ throw new client_ledger('LEDGER_CANNOT_EXCHANGE_PERM_VOTE', 'Asked to exchange a permanent vote for a permanent vote');
125658
+ }
125659
+ let blocksDifferFromVoteBlocks = checkVote.blocks.length !== blockCount;
125539
125660
 
125540
- /**
125541
- * Get all the votes on the same set of blocks (any
125542
- * block can be used for this purpose)
125543
- */
125544
- const relatedVotes = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotes(transaction, blockHash, 'main');
125545
- if (!relatedVotes) {
125546
- continue;
125661
+ /* If they do not differ from length alone, compare block hashes */
125662
+ if (!blocksDifferFromVoteBlocks) {
125663
+ for (let blockIndex = 0; blockIndex < blockCount; blockIndex++) {
125664
+ if (!blocks[blockIndex].hash.compareHexString(checkVote.blocks[blockIndex])) {
125665
+ blocksDifferFromVoteBlocks = true;
125666
+ break;
125667
+ }
125668
+ }
125669
+ }
125670
+ if (blocksDifferFromVoteBlocks) {
125671
+ throw new client_ledger('LEDGER_BLOCKS_DIFFER_FROM_VOTED_ON', 'Asked to exchange different number of blocks for a permanent vote');
125672
+ }
125673
+ if (checkVote.issuer.comparePublicKey(ledgerPubKey)) {
125674
+ foundOurVote = true;
125675
+ }
125676
+ }
125677
+ if (requiredFees.size > 0) {
125678
+ if (!hasFeeBlock) {
125679
+ throw new client_ledger('LEDGER_MISSING_REQUIRED_FEE_BLOCK', 'Missing fee block but votes require it');
125680
+ }
125681
+ if (requiredFees.size !== (possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.length)) {
125682
+ throw new client_ledger('LEDGER_REQUIRED_FEE_MISMATCH', 'Fee Block Operations do not match required fees');
125683
+ }
125547
125684
  }
125548
- const relatedBlockHashes = relatedVotes[0].blocks;
125549
125685
 
125550
- /**
125551
- * We do not need to process any blocks within this vote again
125552
- * All of them will be the same staple
125553
- */
125554
- for (const relatedBlockHash of relatedBlockHashes) {
125555
- seenBlockHashes.add(relatedBlockHash);
125686
+ // Verify that all required fees have been included in the fee block
125687
+ for (const [issuer, fee] of requiredFees) {
125688
+ const foundFee = possibleFeeBlock === null || possibleFeeBlock === void 0 ? void 0 : possibleFeeBlock.operations.find(operation => {
125689
+ var _fee$payTo, _fee$token;
125690
+ const expectedPayTo = (_fee$payTo = fee.payTo) !== null && _fee$payTo !== void 0 ? _fee$payTo : issuer;
125691
+ const expectedToken = (_fee$token = fee.token) !== null && _fee$token !== void 0 ? _fee$token : client_ledger_classPrivateFieldGet(src_client_ledger, this).baseToken;
125692
+ if (operation.type === client_OperationType.SEND && operation.to.comparePublicKey(expectedPayTo)) {
125693
+ if (operation.amount !== fee.amount) {
125694
+ throw new client_ledger('LEDGER_FEE_AMOUNT_MISMATCH', `Fee Amount Mismatch, found: ${operation.amount} expected: ${fee.amount}`);
125695
+ }
125696
+ if (!operation.token.comparePublicKey(expectedToken)) {
125697
+ throw new client_ledger('LEDGER_FEE_TOKEN_MISMATCH', `Fee Token Mismatch, found: ${operation.token.publicKeyString.get()} expected: ${expectedToken.publicKeyString.get()}`);
125698
+ }
125699
+ return true;
125700
+ }
125701
+ return false;
125702
+ });
125703
+ if (foundFee === undefined) {
125704
+ var _fee$payTo$publicKeyS, _fee$payTo2;
125705
+ throw new client_ledger('LEDGER_FEE_MISSING', `Missing Required Fee for ${(_fee$payTo$publicKeyS = (_fee$payTo2 = fee.payTo) === null || _fee$payTo2 === void 0 ? void 0 : _fee$payTo2.publicKeyString.get()) !== null && _fee$payTo$publicKeyS !== void 0 ? _fee$payTo$publicKeyS : issuer.publicKeyString.get()}`);
125706
+ }
125556
125707
  }
125557
- if (seenVoteUIDs.has(relatedVotes[0].$id)) {
125708
+ if (!foundOurVote) {
125709
+ throw new client_ledger('LEDGER_NO_PERM_WITHOUT_SELF_TEMP', 'Asked to give a permanent vote without a temporary vote from us');
125710
+ }
125711
+ }
125712
+ const allLedgerHeads = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125713
+ const needToGetHeadFor = new client_lib_account.Set(allLedgerHeads.keys());
125714
+ const allHeads = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlockHashes(transaction, needToGetHeadFor);
125715
+ for (const [account, expectedBlock] of allLedgerHeads.entries()) {
125716
+ const accountHead = allHeads[account.publicKeyString.get()];
125717
+ if (accountHead === null) {
125718
+ if (!expectedBlock.$opening) {
125719
+ throw new client_ledger('LEDGER_NOT_OPENING', 'Cannot vote on non-opening block for an empty account');
125720
+ }
125558
125721
  continue;
125559
125722
  }
125560
-
125561
- /**
125562
- * Indicate we have now seen all these votes -- even if
125563
- * we cannot create a VoteStaple from it due to
125564
- * missing blocks, there's no point in retrying that.
125565
- */
125566
- for (const relatedVote of relatedVotes) {
125567
- seenVoteUIDs.add(relatedVote.$id);
125723
+ if (expectedBlock.$opening) {
125724
+ throw new client_ledger('LEDGER_NOT_EMPTY', 'Cannot vote on opening block for a non-empty account');
125725
+ }
125726
+ if (expectedBlock.previous.toString() !== accountHead.toString()) {
125727
+ throw new client_ledger('LEDGER_NOT_SUCCESSOR', 'The block is not the successor to the account head block');
125568
125728
  }
125729
+ }
125569
125730
 
125570
- /**
125571
- * Fetch all the blocks mentioned in the vote
125572
- */
125573
- const resolvedVoteBlocks = [];
125574
- let foundInvalidBlock = false;
125575
- const voteBlockPromises = relatedBlockHashes.map(async relatedHash => {
125576
- try {
125577
- const block = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlock(transaction, relatedHash, 'main');
125731
+ /**
125732
+ * Ensure we have no active vote for another conflicting successor of this block's parent (previous),
125733
+ * which could cause a fork
125734
+ */
125735
+ const previousToCheckFor = blocks.map(b => b.previous);
125736
+ const allPrevious = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesFromMultiplePrevious(transaction, previousToCheckFor, 'both', client_lib_account.toAccount(ledgerPubKey));
125737
+ for (const block of blocks) {
125738
+ const previousVotes = allPrevious[block.previous.toString()];
125739
+ if (previousVotes !== null && previousVotes.length > 0) {
125740
+ /**
125741
+ * If we do have a previous vote, we can
125742
+ * replace it with a permanent vote if
125743
+ * there is only 1 previous vote, issued by us,
125744
+ * and it's a short vote
125745
+ */
125578
125746
 
125579
- // We only care about valid blocks
125580
- if (src_client_Block.isInstance(block)) {
125581
- resolvedVoteBlocks.push(block);
125582
- return;
125583
- }
125584
- } catch {
125585
- /* Ignore the error, we will check for undefined blocks later */
125747
+ let mayReplace = false;
125748
+ if (previousVotes.length === 1 && otherVotes !== undefined && otherVotes.length !== 0) {
125749
+ const ourVote = previousVotes[0];
125750
+ mayReplace = !ourVote.$permanent && ourVote.issuer.comparePublicKey(ledgerPubKey);
125751
+ }
125752
+ if (!mayReplace) {
125753
+ throw new client_ledger('LEDGER_SUCCESSOR_VOTE_EXISTS', `We cannot vote for this block (hash=${block.hash.toString()}), we have an existing vote for a successor (previous votes = ${JSON.stringify(client_toJSONSerializable(previousVotes))})`);
125586
125754
  }
125587
- foundInvalidBlock = true;
125588
- });
125589
- await Promise.all(voteBlockPromises);
125590
-
125591
- /**
125592
- * If there were any blocks that we don't currently have, we shouldn't construct a staple
125593
- */
125594
- if (foundInvalidBlock) {
125595
- continue;
125596
125755
  }
125756
+ }
125597
125757
 
125598
- /**
125599
- * Construct the staple from the information gathered
125600
- */
125601
- const staple = src_client_Vote.Staple.fromVotesAndBlocks(relatedVotes, resolvedVoteBlocks);
125602
- staples.push(staple);
125758
+ /**
125759
+ * If no other votes have been supplied, validate that the blocks are valid, and issue a short vote
125760
+ */
125761
+ if (otherVotes === undefined) {
125762
+ const vote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'VOTE', quote);
125763
+ const blocksAndVote = src_client_VoteStaple.fromVotesAndBlocks([vote], blocks);
125764
+ await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
125765
+ return vote;
125603
125766
  }
125604
- return staples;
125767
+
125768
+ /**
125769
+ * Validate the votes are sufficient weight and grant
125770
+ * our permanent vote
125771
+ */
125772
+ const votesSufficient = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateVotingWeight).call(this, otherVotes);
125773
+ if (votesSufficient !== true) {
125774
+ throw new client_ledger('LEDGER_INSUFFICIENT_VOTING_WEIGHT', 'Unable to create a vote from these votes, they do not represent enough voting power');
125775
+ }
125776
+
125777
+ /**
125778
+ * Serial number
125779
+ */
125780
+ const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
125781
+ const wipVote = new src_client_VoteBuilder(privateKey);
125782
+ for (const block of blocks) {
125783
+ wipVote.addBlock(block);
125784
+ }
125785
+ const vote = await wipVote.seal(serial, null);
125786
+ const blocksAndVote = src_client_VoteStaple.fromVotesAndBlocks([vote], blocks);
125787
+
125788
+ /**
125789
+ * Add this pending vote to our side ledger;
125790
+ * Replacing an existing temporary vote with a permanent one
125791
+ */
125792
+ await client_ledger_classPrivateFieldGet(client_ledger_storage, this).addPendingVote(transaction, blocksAndVote);
125793
+ return vote;
125605
125794
  }
125606
- async getVoteStaplesAfter(moment) {
125607
- let limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
125608
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
125795
+ async quote(blocks) {
125796
+ await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateBlocksForVote).call(this, blocks);
125797
+ const quote = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_voteOrQuoteWithFees).call(this, blocks, 'QUOTE');
125798
+ return quote;
125799
+ }
125800
+ async add(votesAndBlocks, from) {
125801
+ var _classPrivateFieldGet3, _classPrivateFieldGet4, _classPrivateFieldGet5, _classPrivateFieldGet6;
125609
125802
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125610
- const {
125611
- bloomFilter,
125612
- timeout
125613
- } = options;
125614
- const retval = [];
125615
- const startTime = Date.now();
125616
- let startKey;
125617
- while (retval.length < limit) {
125618
- /**
125619
- * If the timeout is reached and we have at least one
125620
- * result already, return it.
125621
- */
125622
- if (retval.length > 0 && timeout !== undefined) {
125623
- const now = Date.now();
125624
- if (now - startTime > timeout) {
125803
+ switch (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode) {
125804
+ case 'read-only':
125805
+ throw new Error('Cannot add blocks to a read-only ledger');
125806
+ case 'bootstrap-only':
125807
+ if (from === 'bootstrap') {
125625
125808
  break;
125626
125809
  }
125810
+ throw new Error('Cannot add blocks to a read-only ledger (except for bootstrapping)');
125811
+ case 'read-write':
125812
+ case 'no-voting':
125813
+ break;
125814
+ default:
125815
+ throw new Error(`internal error: invalid ledger write mode: ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode}`);
125816
+ }
125817
+ const {
125818
+ votes,
125819
+ blocks
125820
+ } = votesAndBlocks;
125821
+ if (votes.length < 1) {
125822
+ throw new Error('Must have at least 1 vote in the staple');
125823
+ }
125824
+ for (const block of blocks) {
125825
+ if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
125826
+ throw new Error('Cannot process block for a different network');
125627
125827
  }
125628
-
125629
- /**
125630
- * Compute the maximum number of votes we can fetch from the
125631
- * storage driver in a single page, we request 32x the
125632
- * remaining limit, but no more than 200
125633
- */
125634
- let maxVotesPerPage = (limit - retval.length) * 32;
125635
- if (maxVotesPerPage > 200) {
125636
- maxVotesPerPage = 200;
125828
+ if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
125829
+ throw new Error('Cannot process block for a different subnet');
125637
125830
  }
125638
-
125639
- /**
125640
- * Get all the votes from the storage driver that occurred on
125641
- * or after the moment specified.
125642
- */
125643
- const page = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesAfter(transaction, moment, startKey, {
125644
- maxVotesPerPage,
125645
- ...options
125646
- });
125647
- startKey = page.nextKey;
125648
- const pageBlockHashes = page.votes.map(vote => vote.blocks);
125649
-
125650
- // Convert BlockHash[][] to BlockHash[] and remove duplicates
125651
- const seenBlockHashes = new client_block_BlockHash.Set();
125652
- const flattenedHashes = pageBlockHashes.flat().filter(function (hash) {
125653
- return !seenBlockHashes.has(hash);
125654
- });
125655
- const staples = await this.getStaplesFromBlockHashes(flattenedHashes);
125656
- for (const staple of staples) {
125657
- /**
125658
- * Break out of the loop if we have reached capacity
125659
- */
125660
- if (retval.length >= limit) {
125661
- break;
125662
- }
125663
-
125664
- /**
125665
- * If a filter has been supplied, check
125666
- * it to see if the new vote has already
125667
- * been sent
125668
- */
125669
- if (bloomFilter) {
125670
- if (bloomFilter.has(staple.toBytes())) {
125671
- continue;
125672
- }
125673
- }
125674
- retval.push(staple);
125831
+ }
125832
+ for (const vote of votes) {
125833
+ if (!vote.$permanent) {
125834
+ throw new Error('Can only insert permanent votes');
125675
125835
  }
125676
-
125677
- /**
125678
- * If there is no next key, exit the loop
125679
- */
125680
- if (startKey === undefined) {
125681
- break;
125836
+ }
125837
+ const weightTiming = (_classPrivateFieldGet3 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.timing.startTime('db-add/getWeight');
125838
+ const votesSufficient = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateVotingWeight).call(this, votesAndBlocks.votes);
125839
+ if (votesSufficient !== true) {
125840
+ throw new client_ledger('LEDGER_INSUFFICIENT_VOTING_WEIGHT', 'Votes attached do not represent enough voting power');
125841
+ }
125842
+ weightTiming === null || weightTiming === void 0 || weightTiming.end();
125843
+ const changesTiming = (_classPrivateFieldGet4 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.timing.startTime('db-add/computeEffectOfBlocks');
125844
+ const changes = client_computeEffectOfBlocks(votesAndBlocks.blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125845
+ changesTiming === null || changesTiming === void 0 || changesTiming.end();
125846
+ const adjustTiming = (_classPrivateFieldGet5 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.timing.startTime('db-add/adjust');
125847
+ const voteStaples = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).adjust(transaction, votesAndBlocks, changes);
125848
+ adjustTiming === null || adjustTiming === void 0 || adjustTiming.end();
125849
+ const postambleTiming = (_classPrivateFieldGet6 = client_ledger_classPrivateFieldGet(src_client_ledger, this).node) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.timing.startTime('db-add/postamble');
125850
+ /**
125851
+ * Add all the block hashes to the node checksum
125852
+ */
125853
+ for (const staple of voteStaples) {
125854
+ for (const block of staple.blocks) {
125855
+ transaction.statsPending.xor('ledgerChecksum', block.hash);
125856
+ }
125857
+ }
125858
+ postambleTiming === null || postambleTiming === void 0 || postambleTiming.end();
125859
+ return voteStaples;
125860
+ }
125861
+ async getBalance(account, token) {
125862
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125863
+ const balance = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBalance(transaction, account, token);
125864
+ if (balance < 0n) {
125865
+ throw new Error(`internal error: Account with negative balance: ${account.publicKeyString.get()}/${client_lib_account.toPublicKeyString(token)}: ${balance}`);
125866
+ }
125867
+ return balance;
125868
+ }
125869
+ async getAllBalances(account) {
125870
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125871
+ const balances = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAllBalances(transaction, account);
125872
+ for (const {
125873
+ token,
125874
+ balance
125875
+ } of balances) {
125876
+ if (balance < 0n) {
125877
+ throw new Error(`internal error: Account with negative balance: ${account.publicKeyString.get()}/${token.publicKeyString.get()}: ${balance}`);
125682
125878
  }
125683
125879
  }
125880
+ return balances;
125881
+ }
125882
+ async getAccountCertificates(account) {
125883
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125884
+ return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountCertificates(client_ledger_classPrivateFieldGet(client_transaction, this), account);
125885
+ }
125886
+ async getAccountCertificateByHash(account, hash) {
125887
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125888
+ return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountCertificateByHash(client_ledger_classPrivateFieldGet(client_transaction, this), account, hash);
125889
+ }
125890
+ async listACLsByPrincipal(principal, entityList) {
125891
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125892
+ const permissions = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listACLsByPrincipal(transaction, principal, entityList);
125893
+ return permissions;
125894
+ }
125895
+ async listACLsByEntity(entity) {
125896
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125897
+ const permissions = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listACLsByEntity(transaction, entity);
125898
+ return permissions;
125899
+ }
125900
+ async votingPower(rep) {
125901
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125902
+ const weight = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction, rep);
125903
+
125904
+ /* Voting Power = Weight (for now) */
125905
+ return weight;
125906
+ }
125907
+ async getVotes(block) {
125908
+ let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125909
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125910
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotes(transaction, block, from);
125684
125911
  return retval;
125685
125912
  }
125686
- async gc(timeLimitMS) {
125913
+ async getVotesFromMultiplePrevious(prevBlocks) {
125914
+ let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125915
+ let issuer = arguments.length > 2 ? arguments[2] : undefined;
125687
125916
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125688
- return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).gc(transaction, timeLimitMS);
125917
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesFromMultiplePrevious(transaction, prevBlocks, from, issuer);
125918
+ return retval;
125689
125919
  }
125690
- async getFee(blocks, effectsInput) {
125691
- const effects = effectsInput !== null && effectsInput !== void 0 ? effectsInput : client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125692
- return client_ledger_classPrivateFieldGet(client_computeFeeFromBlocks, this).call(this, client_ledger_classPrivateFieldGet(src_client_ledger, this), blocks, effects);
125920
+ async getBlockFromPrevious(block, from) {
125921
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125922
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlockFromPrevious(transaction, block, from);
125923
+ return retval;
125693
125924
  }
125694
- async _testingRunStorageFunction(code) {
125925
+ async getHeadBlocks(accounts, from) {
125695
125926
  const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125696
- const retval = await code(client_ledger_classPrivateFieldGet(client_ledger_storage, this), transaction);
125927
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlocks(transaction, accounts, from);
125697
125928
  return retval;
125698
125929
  }
125699
- }
125700
-
125701
- /**
125702
- * The core Ledger components
125703
- */
125704
- function client_assertTransaction() {
125705
- if (client_ledger_classPrivateFieldGet(client_transaction, this) === null) {
125706
- throw new Error('Attempt to use closed transaction');
125930
+ async getHeadBlock(account, from) {
125931
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125932
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHeadBlock(transaction, account, from);
125933
+ return retval;
125707
125934
  }
125708
- return client_ledger_classPrivateFieldGet(client_transaction, this);
125709
- }
125710
- async function client_validateVotingWeight(votes) {
125711
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125712
- const totalVotingPower = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction);
125713
-
125714
- /**
125715
- * See if the weight across the network is 0
125716
- * If so, we want to ensure that it has a vote by the trusted account, and only that account
125717
- */
125718
- if (totalVotingPower === 0n) {
125719
- const foundTrustedVote = votes.find(vote => {
125720
- return vote.issuer.comparePublicKey(client_ledger_classPrivateFieldGet(src_client_ledger, this).initialTrustedAccount);
125721
- });
125722
- return foundTrustedVote !== undefined;
125935
+ async getAccountRep(account) {
125936
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125937
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountRep(transaction, account);
125938
+ return retval;
125723
125939
  }
125724
- const twoThirdsOfTotalWeight = totalVotingPower / 3n * 2n;
125725
- const requiredPower = twoThirdsOfTotalWeight + 1n;
125726
- const voters = votes.map(function (vote) {
125727
- return vote.issuer;
125728
- });
125729
- const votedPowerSum = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction, new client_lib_account.Set(voters));
125730
- return votedPowerSum >= requiredPower;
125731
- }
125732
- async function client_listAccountInfo(accounts) {
125733
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125734
- const accountInfo = {};
125735
- const permissionPromises = Array.from(accounts).map(async account => {
125736
- if (account.isIdentifier() === false) {
125737
- return;
125738
- }
125739
- accountInfo[account.publicKeyString.get()] = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountInfo(transaction, account);
125740
- });
125741
- await Promise.all(permissionPromises);
125742
- return accountInfo;
125743
- }
125744
- async function client_checkSingleAccountPermissions(account, requirements, accountInfos) {
125745
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125746
-
125747
- // Remove duplicates in entity
125748
- const unfilteredEntity = requirements.map(acct => acct.entity);
125749
- const entityAccounts = new client_lib_account.Set(unfilteredEntity).toArray();
125750
- const gotPermissions = await this.listACLsByPrincipal(account, entityAccounts);
125751
- for (const requirement of requirements) {
125752
- var _accountInfos$reqEnti;
125753
- const reqEntityKey = requirement.entity.publicKeyString.get();
125754
- const foundACLRow = client_findPermissionMatch(requirement, gotPermissions);
125755
- let foundPermission;
125756
- if (foundACLRow !== null && foundACLRow !== void 0 && foundACLRow.permissions) {
125757
- foundPermission = foundACLRow === null || foundACLRow === void 0 ? void 0 : foundACLRow.permissions;
125758
- } else if ((_accountInfos$reqEnti = accountInfos[reqEntityKey]) !== null && _accountInfos$reqEnti !== void 0 && _accountInfos$reqEnti.defaultPermission) {
125759
- foundPermission = accountInfos[reqEntityKey].defaultPermission;
125760
- } else {
125761
- foundPermission = new client_permissions_Permissions();
125940
+ async getAccountInfo(account) {
125941
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125942
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountInfo(transaction, account);
125943
+ return retval;
125944
+ }
125945
+ async getBlock(blockhash) {
125946
+ let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125947
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125948
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlock(transaction, blockhash, from);
125949
+ return retval;
125950
+ }
125951
+ async getVoteStaple(stapleBlockHash) {
125952
+ let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125953
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125954
+ const results = await this.getVoteStaples([stapleBlockHash], from);
125955
+ const retval = results.get(stapleBlockHash);
125956
+ if (retval === undefined) {
125957
+ throw new Error(`internal error: missing vote staple for ${stapleBlockHash}`);
125762
125958
  }
125763
- if (requirement.permissions === null) {
125764
- continue;
125959
+ return retval;
125960
+ }
125961
+ async getVoteStaples(stapleBlockHashes) {
125962
+ let from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'main';
125963
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125964
+ if (stapleBlockHashes.length === 0) {
125965
+ return new client_VoteBlockHashMap();
125765
125966
  }
125766
- const hasPermissions = foundPermission.has(requirement.permissions);
125767
- if (!hasPermissions) {
125768
- var _requirement$target;
125769
- const accountPubKey = account.publicKeyString.get();
125770
- const baseFlagsStr = requirement.permissions.base.flags.join(', ');
125771
- const externalOffsetsStr = requirement.permissions.external.trueOffsets.join(', ');
125772
- const reqTargetKey = (_requirement$target = requirement.target) === null || _requirement$target === void 0 ? void 0 : _requirement$target.publicKeyString.get();
125773
- throw new client_ledger('LEDGER_INVALID_PERMISSIONS', `${accountPubKey} does not have required permissions to perform action on ${reqEntityKey}/${reqTargetKey} -- needs [${baseFlagsStr}]/[${externalOffsetsStr}]`);
125967
+ if (stapleBlockHashes.length > 10000) {
125968
+ throw new Error('Cannot fetch more than 10,000 vote staples at once');
125774
125969
  }
125970
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaples(transaction, stapleBlockHashes, from);
125971
+ return retval;
125775
125972
  }
125776
- }
125777
- async function client_checkPermissionRequirements(effects) {
125778
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125779
- const newOwners = {};
125780
- const requirementsByPrincipal = {};
125781
- const needToGetAccountInfoFor = new client_lib_account.Set();
125782
- const allAccountsChanges = Object.values(effects);
125783
- const foundMultisigSignerLengths = [];
125784
- for (const {
125785
- account,
125786
- fields
125787
- } of allAccountsChanges) {
125788
- if (account.isMultisig()) {
125789
- if (fields.minSignerSetLength !== undefined) {
125790
- needToGetAccountInfoFor.add(account);
125791
- foundMultisigSignerLengths.push([account, fields.minSignerSetLength]);
125973
+ async getHistory(account, start) {
125974
+ let limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 25;
125975
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125976
+ const voteStapleHashes = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getHistory(transaction, account, start, limit);
125977
+ const voteStaplesMap = await this.getVoteStaples(voteStapleHashes, 'main');
125978
+ const voteStaples = voteStapleHashes.map(function (voteStapleHash) {
125979
+ const voteStaple = voteStaplesMap.get(voteStapleHash);
125980
+ if (voteStaple === undefined || voteStaple === null) {
125981
+ throw new Error(`internal error: missing vote staple for ${voteStapleHash}`);
125792
125982
  }
125983
+ return voteStaple;
125984
+ });
125985
+ return voteStaples;
125986
+ }
125987
+ async getStaplesFromBlockHashes(hashes) {
125988
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125989
+ if (client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaplesFromBlockHash) {
125990
+ const retval = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVoteStaplesFromBlockHash(transaction, hashes, 'main');
125991
+ return retval;
125793
125992
  }
125794
- for (const singleRequirement of (_fields$permissionReq = fields.permissionRequirements) !== null && _fields$permissionReq !== void 0 ? _fields$permissionReq : []) {
125795
- var _fields$permissionReq;
125796
- const principal = singleRequirement.principal;
125797
- const principalPubKey = principal.publicKeyString.get();
125798
- if (!requirementsByPrincipal[principalPubKey]) {
125799
- requirementsByPrincipal[principalPubKey] = [];
125993
+ const staples = [];
125994
+ const seenVoteUIDs = new Set();
125995
+ const seenBlockHashes = new client_block_BlockHash.Set();
125996
+ for (const blockHash of hashes) {
125997
+ if (seenBlockHashes.has(blockHash)) {
125998
+ continue;
125800
125999
  }
125801
- requirementsByPrincipal[principalPubKey].push(singleRequirement);
125802
- const {
125803
- entity,
125804
- permissions
125805
- } = singleRequirement;
125806
- const entityKey = entity.publicKeyString.get();
125807
- if (permissions === null) {
126000
+
126001
+ /**
126002
+ * Get all the votes on the same set of blocks (any
126003
+ * block can be used for this purpose)
126004
+ */
126005
+ const relatedVotes = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotes(transaction, blockHash, 'main');
126006
+ if (!relatedVotes) {
125808
126007
  continue;
125809
126008
  }
125810
- if (permissions.has(['OWNER'])) {
125811
- if (newOwners[entityKey] === undefined) {
125812
- newOwners[entityKey] = {
125813
- entity,
125814
- owners: []
125815
- };
125816
- }
125817
- newOwners[entityKey].owners.push(principal);
126009
+ const relatedBlockHashes = relatedVotes[0].blocks;
126010
+
126011
+ /**
126012
+ * We do not need to process any blocks within this vote again
126013
+ * All of them will be the same staple
126014
+ */
126015
+ for (const relatedBlockHash of relatedBlockHashes) {
126016
+ seenBlockHashes.add(relatedBlockHash);
125818
126017
  }
125819
- if (permissions.base.isValidForDefault && entity.isIdentifier()) {
125820
- needToGetAccountInfoFor.add(entity);
126018
+ if (seenVoteUIDs.has(relatedVotes[0].$id)) {
126019
+ continue;
125821
126020
  }
125822
- }
125823
- }
125824
- const foundAccountInfo = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_listAccountInfo).call(this, needToGetAccountInfoFor);
125825
- for (const [multisig, foundSingerLength] of foundMultisigSignerLengths) {
125826
- const multisigPubKey = multisig.publicKeyString.get();
125827
- const foundInfo = foundAccountInfo[multisigPubKey];
125828
- if (!(foundInfo !== null && foundInfo !== void 0 && foundInfo.multisigQuorum)) {
125829
- throw new Error(`Multisig quorum not found for ${multisigPubKey}`);
125830
- }
125831
- if (foundInfo.multisigQuorum > foundSingerLength) {
125832
- throw new client_ledger('LEDGER_INVALID_PERMISSIONS', `Quorum of ${foundInfo.multisigQuorum} not reached for ${multisigPubKey} -- got ${foundSingerLength}`);
125833
- }
125834
- }
125835
- const checkPromises = [];
125836
- for (const principalPubKey in requirementsByPrincipal) {
125837
- const accountRequirements = requirementsByPrincipal[principalPubKey];
125838
- const principal = client_lib_account.fromPublicKeyString(principalPubKey);
125839
- checkPromises.push(client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkSingleAccountPermissions).call(this, principal, accountRequirements, foundAccountInfo));
125840
- }
125841
- await Promise.all(checkPromises);
125842
- return {
125843
- newOwners
125844
- };
125845
- }
125846
- /**
125847
- * Ensure all parts of a transaction do not have a negative outcome
125848
- * Balance/Supply cannot fall negative at any point in transaction
125849
- * Accounts have required permissions to perform actions
125850
- * After permission owner modifications all accounts must have exactly one owner
125851
- */
125852
- async function client_validateLedgerOutcome(blocks) {
125853
- const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
125854
- const ownersByIdentifier = {};
125855
126021
 
125856
- // 'ADD' or 'REMOVE' an owner from ownersByIdentifier
125857
- const modifyOwners = (method, entity, principal) => {
125858
- if (entity.isIdentifier() === false || entity.isMultisig()) {
125859
- return;
125860
- }
125861
- const entityPubKey = entity.assertIdentifier().publicKeyString.get();
125862
- if (ownersByIdentifier[entityPubKey] === undefined) {
125863
- ownersByIdentifier[entityPubKey] = {
125864
- added: new client_lib_account.Set(),
125865
- removed: new client_lib_account.Set()
125866
- };
125867
- }
125868
- switch (method) {
125869
- case 'ADD':
125870
- // If it is not already included, push added owner
125871
- ownersByIdentifier[entityPubKey].added.add(principal);
125872
- ownersByIdentifier[entityPubKey].removed.delete(principal);
125873
- break;
125874
- case 'REMOVE':
125875
- // Remove owner if it is already included
125876
- ownersByIdentifier[entityPubKey].added.delete(principal);
125877
- ownersByIdentifier[entityPubKey].removed.add(principal);
125878
- break;
125879
- }
125880
- };
125881
- const effects = client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
125882
- const accountEffects = effects.accounts;
125883
- const allAccountsChanges = Object.values(accountEffects);
125884
-
125885
- /**
125886
- * Ensure all required permissions are met
125887
- * See which accounts are now owners, and add those accounts to the set that we have
125888
- */
125889
- const {
125890
- newOwners
125891
- } = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkPermissionRequirements).call(this, accountEffects);
125892
- for (const entityPubKey in newOwners) {
125893
- const {
125894
- entity,
125895
- owners
125896
- } = newOwners[entityPubKey];
125897
- for (const newOwner of owners) {
125898
- modifyOwners('ADD', entity, newOwner);
125899
- }
125900
- }
125901
- for (const accountChanges of allAccountsChanges) {
125902
- var _fields$createRequest, _fields$permissions;
125903
- const {
125904
- account,
125905
- fields = {}
125906
- } = accountChanges;
125907
-
125908
- /**
125909
- * Newly created identifiers automatically grant the creator ownership.
125910
- */
125911
- const createRequests = (_fields$createRequest = fields.createRequests) !== null && _fields$createRequest !== void 0 ? _fields$createRequest : [];
125912
- for (const createRequest of createRequests) {
125913
- modifyOwners('ADD', createRequest.createdIdentifier, account);
125914
- }
125915
-
125916
- /**
125917
- * If an account was granted permissions, we should take that into effect
125918
- */
125919
- const addedPermissions = (_fields$permissions = fields.permissions) !== null && _fields$permissions !== void 0 ? _fields$permissions : [];
125920
- for (const newPerm of addedPermissions) {
125921
- let method = 'ADD';
125922
- if (newPerm.permissions === null || !newPerm.permissions.has(['OWNER'])) {
125923
- method = 'REMOVE';
126022
+ /**
126023
+ * Indicate we have now seen all these votes -- even if
126024
+ * we cannot create a VoteStaple from it due to
126025
+ * missing blocks, there's no point in retrying that.
126026
+ */
126027
+ for (const relatedVote of relatedVotes) {
126028
+ seenVoteUIDs.add(relatedVote.$id);
125924
126029
  }
125925
- modifyOwners(method, newPerm.entity, newPerm.principal);
125926
- }
125927
- }
125928
126030
 
125929
- /**
125930
- * Ensure there is exactly one owner when permissions were changed
125931
- */
125932
- for (const [identifierPubKey, {
125933
- added,
125934
- removed
125935
- }] of Object.entries(ownersByIdentifier)) {
125936
- let ownerLength = added.size;
126031
+ /**
126032
+ * Fetch all the blocks mentioned in the vote
126033
+ */
126034
+ const resolvedVoteBlocks = [];
126035
+ let foundInvalidBlock = false;
126036
+ const voteBlockPromises = relatedBlockHashes.map(async relatedHash => {
126037
+ try {
126038
+ const block = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getBlock(transaction, relatedHash, 'main');
125937
126039
 
125938
- // If more than one owner was granted and not removed, we know it is invalid without checking
125939
- if (ownerLength <= 1) {
125940
- const identifierAccount = client_lib_account.fromPublicKeyString(identifierPubKey).assertIdentifier();
125941
- const receivedOwners = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listOwners(transaction, identifierAccount);
125942
- for (const receivedOwner of receivedOwners) {
125943
- // We already know about these owners, we do not care about adding/removing them again
125944
- if (added.has(receivedOwner) || removed.has(receivedOwner)) {
125945
- continue;
126040
+ // We only care about valid blocks
126041
+ if (src_client_Block.isInstance(block)) {
126042
+ resolvedVoteBlocks.push(block);
126043
+ return;
126044
+ }
126045
+ } catch {
126046
+ /* Ignore the error, we will check for undefined blocks later */
125946
126047
  }
125947
- ownerLength++;
126048
+ foundInvalidBlock = true;
126049
+ });
126050
+ await Promise.all(voteBlockPromises);
126051
+
126052
+ /**
126053
+ * If there were any blocks that we don't currently have, we shouldn't construct a staple
126054
+ */
126055
+ if (foundInvalidBlock) {
126056
+ continue;
125948
126057
  }
126058
+
126059
+ /**
126060
+ * Construct the staple from the information gathered
126061
+ */
126062
+ const staple = src_client_Vote.Staple.fromVotesAndBlocks(relatedVotes, resolvedVoteBlocks);
126063
+ staples.push(staple);
125949
126064
  }
125950
- if (ownerLength === 1) {
125951
- continue;
125952
- }
125953
- throw new client_ledger('LEDGER_INVALID_OWNER_COUNT', `Invalid number of owners for ${identifierPubKey} - Got ${ownerLength}/1`);
126065
+ return staples;
125954
126066
  }
125955
- const {
125956
- balances
125957
- } = await client_computeLedgerEffect({
125958
- checkRangeConstraints: true,
125959
- baseToken: client_ledger_classPrivateFieldGet(src_client_ledger, this).baseToken
125960
- }, accountEffects, client_ledger_classPrivateFieldGet(client_ledger_storage, this), client_ledger_classPrivateFieldGet(client_network, this), client_ledger_classPrivateFieldGet(client_transaction, this));
125961
- for (const accountPubKey in balances) {
125962
- const acctBalanceChanges = balances[accountPubKey];
125963
- for (const tokenPubKey in acctBalanceChanges) {
125964
- const {
125965
- change,
125966
- fellNegative,
125967
- receiveValidated
125968
- } = acctBalanceChanges[tokenPubKey];
125969
- if (fellNegative) {
125970
- throw new client_ledger('LEDGER_INVALID_BALANCE', `Resulting balance becomes negative at one+ point(s) during this transaction for account/token ${accountPubKey}/${tokenPubKey}: change ${change}`);
126067
+ async getVoteStaplesAfter(moment) {
126068
+ let limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
126069
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
126070
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126071
+ const {
126072
+ bloomFilter,
126073
+ timeout
126074
+ } = options;
126075
+ const retval = [];
126076
+ const startTime = Date.now();
126077
+ let startKey;
126078
+ while (retval.length < limit) {
126079
+ /**
126080
+ * If the timeout is reached and we have at least one
126081
+ * result already, return it.
126082
+ */
126083
+ if (retval.length > 0 && timeout !== undefined) {
126084
+ const now = Date.now();
126085
+ if (now - startTime > timeout) {
126086
+ break;
126087
+ }
125971
126088
  }
125972
- if (receiveValidated === false) {
125973
- throw new client_ledger('LEDGER_RECEIVE_NOT_MET', `${accountPubKey}/${tokenPubKey} did not receive enough of requested token. change: ${change}`);
126089
+
126090
+ /**
126091
+ * Compute the maximum number of votes we can fetch from the
126092
+ * storage driver in a single page, we request 32x the
126093
+ * remaining limit, but no more than 200
126094
+ */
126095
+ let maxVotesPerPage = (limit - retval.length) * 32;
126096
+ if (maxVotesPerPage > 200) {
126097
+ maxVotesPerPage = 200;
125974
126098
  }
125975
- }
125976
- }
125977
- return effects;
125978
- }
125979
- async function client_validateBlocksForVote(blocks) {
125980
- /**
125981
- * Create a map of all blocks by their hash
125982
- */
125983
- const blockHashMap = {};
125984
- for (const block of blocks) {
125985
- blockHashMap[block.hash.toString()] = block;
125986
- }
125987
- const seenBlockHashes = new client_block_BlockHash.Set();
125988
- const usedPreviousBlockHashes = new client_block_BlockHash.Set();
125989
- const allLedgerHeads = new Map();
125990
- for (const block of blocks) {
125991
- const prevBlockHash = block.previous;
125992
- seenBlockHashes.add(block.hash);
125993
- if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
125994
- throw new client_ledger('LEDGER_INVALID_NETWORK', 'Cannot vote on block for a different network');
125995
- }
125996
- if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
125997
- throw new client_ledger('LEDGER_INVALID_SUBNET', 'Cannot vote on block for a different subnet');
125998
- }
125999
- if (usedPreviousBlockHashes.has(prevBlockHash)) {
126000
- throw new client_ledger('LEDGER_PREVIOUS_ALREADY_USED', `Invalid reference to block, previous: ${prevBlockHash} has already been used`);
126001
- }
126002
- usedPreviousBlockHashes.add(prevBlockHash);
126003
126099
 
126004
- /**
126005
- * Only allow this vote if it is the successor the current
126006
- * HEAD block for the account, or if no blocks exist on the
126007
- * account and its an opening block, or if the predecessor
126008
- * block is also being voted on
126009
- */
126010
- let predecessorBeingVotedOn = false;
126011
- if (!block.$opening) {
126012
- const prevBlock = blockHashMap[prevBlockHash.toString()];
126013
- if (prevBlock !== undefined) {
126014
- predecessorBeingVotedOn = true;
126015
- if (!prevBlock.account.comparePublicKey(block.account)) {
126016
- throw new client_ledger('LEDGER_INVALID_CHAIN', 'Invalid chain, changes accounts');
126100
+ /**
126101
+ * Get all the votes from the storage driver that occurred on
126102
+ * or after the moment specified.
126103
+ */
126104
+ const page = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getVotesAfter(transaction, moment, startKey, {
126105
+ maxVotesPerPage,
126106
+ ...options
126107
+ });
126108
+ startKey = page.nextKey;
126109
+ const pageBlockHashes = page.votes.map(vote => vote.blocks);
126110
+
126111
+ // Convert BlockHash[][] to BlockHash[] and remove duplicates
126112
+ const seenBlockHashes = new client_block_BlockHash.Set();
126113
+ const flattenedHashes = pageBlockHashes.flat().filter(function (hash) {
126114
+ return !seenBlockHashes.has(hash);
126115
+ });
126116
+ const staples = await this.getStaplesFromBlockHashes(flattenedHashes);
126117
+ for (const staple of staples) {
126118
+ /**
126119
+ * Break out of the loop if we have reached capacity
126120
+ */
126121
+ if (retval.length >= limit) {
126122
+ break;
126017
126123
  }
126018
- if (!seenBlockHashes.has(prevBlockHash)) {
126019
- throw new client_ledger('LEDGER_PREVIOUS_NOT_SEEN', `Invalid reference to block, out-of-order: ${prevBlockHash} has not already been seen`);
126124
+
126125
+ /**
126126
+ * If a filter has been supplied, check
126127
+ * it to see if the new vote has already
126128
+ * been sent
126129
+ */
126130
+ if (bloomFilter) {
126131
+ if (bloomFilter.has(staple.toBytes())) {
126132
+ continue;
126133
+ }
126020
126134
  }
126135
+ retval.push(staple);
126136
+ }
126137
+
126138
+ /**
126139
+ * If there is no next key, exit the loop
126140
+ */
126141
+ if (startKey === undefined) {
126142
+ break;
126021
126143
  }
126022
126144
  }
126023
- if (!predecessorBeingVotedOn) {
126024
- allLedgerHeads.set(block.account, block);
126025
- }
126145
+ return retval;
126026
126146
  }
126027
- return allLedgerHeads;
126028
- }
126029
- async function client_voteOrQuoteWithFees(blocks, type, quote) {
126030
- var _quote$fee;
126031
- if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
126032
- throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
126147
+ async gc(timeLimitMS) {
126148
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126149
+ return await client_ledger_classPrivateFieldGet(client_ledger_storage, this).gc(transaction, timeLimitMS);
126033
126150
  }
126034
- if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
126035
- throw new Error('Cannot vote on block, no private key loaded');
126151
+ async getFee(blocks, effectsInput) {
126152
+ const effects = effectsInput !== null && effectsInput !== void 0 ? effectsInput : client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
126153
+ return client_ledger_classPrivateFieldGet(client_computeFeeFromBlocks, this).call(this, client_ledger_classPrivateFieldGet(src_client_ledger, this), blocks, effects);
126036
126154
  }
126037
- client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126038
- const effects = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateLedgerOutcome).call(this, blocks);
126039
- const now = Date.now();
126040
- for (const block of blocks) {
126041
- const blockDate = block.date.valueOf();
126042
- const timeOffset = 5 /* m */ * 60 /* s */ * 1000 /* ms */;
126043
-
126044
- /**
126045
- * Do not allow short votes on blocks from the distant past
126046
- */
126047
- if (blockDate < now - timeOffset || blockDate > now + timeOffset) {
126048
- throw new Error(`Refusing to issue vote for block dated ${block.date.toISOString()}`);
126049
- }
126155
+ async _testingRunStorageFunction(code) {
126156
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126157
+ const retval = await code(client_ledger_classPrivateFieldGet(client_ledger_storage, this), transaction);
126158
+ return retval;
126050
126159
  }
126160
+ }
126051
126161
 
126052
- /**
126053
- * Serial number
126054
- */
126055
- const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
126056
-
126057
- /**
126058
- * Short expiry (5 minutes)
126059
- */
126060
- const pendingVoteExpiry = new Date();
126061
- pendingVoteExpiry.setUTCMinutes(pendingVoteExpiry.getUTCMinutes() + 5);
126062
- const builderType = type === 'QUOTE' ? src_client_VoteQuoteBuilder : src_client_VoteBuilder;
126063
- const builder = new builderType(client_ledger_classPrivateFieldGet(client_ledger_privateKey, this));
126064
- for (const block of blocks) {
126065
- builder.addBlock(block);
126162
+ /**
126163
+ * The core Ledger components
126164
+ */
126165
+ function client_assertTransaction() {
126166
+ if (client_ledger_classPrivateFieldGet(client_transaction, this) === null) {
126167
+ throw new Error('Attempt to use closed transaction');
126066
126168
  }
126169
+ return client_ledger_classPrivateFieldGet(client_transaction, this);
126170
+ }
126171
+ async function client_validateVotingWeight(votes) {
126172
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126173
+ const totalVotingPower = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction);
126067
126174
 
126068
126175
  /**
126069
- * If a quote was provided use it as the fee, otherwise generate new fee
126176
+ * See if the weight across the network is 0
126177
+ * If so, we want to ensure that it has a vote by the trusted account, and only that account
126070
126178
  */
126071
- const fee = (_quote$fee = quote === null || quote === void 0 ? void 0 : quote.fee) !== null && _quote$fee !== void 0 ? _quote$fee : await this.getFee(blocks, effects);
126072
- if (fee !== null) {
126073
- builder.addFee(fee);
126179
+ if (totalVotingPower === 0n) {
126180
+ const foundTrustedVote = votes.find(vote => {
126181
+ return vote.issuer.comparePublicKey(client_ledger_classPrivateFieldGet(src_client_ledger, this).initialTrustedAccount);
126182
+ });
126183
+ return foundTrustedVote !== undefined;
126074
126184
  }
126075
- const voteOrQuote = await builder.seal(serial, pendingVoteExpiry);
126076
- return voteOrQuote;
126185
+ const twoThirdsOfTotalWeight = totalVotingPower / 3n * 2n;
126186
+ const requiredPower = twoThirdsOfTotalWeight + 1n;
126187
+ const voters = votes.map(function (vote) {
126188
+ return vote.issuer;
126189
+ });
126190
+ const votedPowerSum = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).delegatedWeight(transaction, new client_lib_account.Set(voters));
126191
+ return votedPowerSum >= requiredPower;
126077
126192
  }
126078
- var client_storage2 = /*#__PURE__*/new WeakMap();
126079
- var src_client_config = /*#__PURE__*/new WeakMap();
126080
- class src_client_Ledger {
126081
- constructor(config, node, existingStorage) {
126082
- client_ledger_classPrivateFieldInitSpec(this, client_storage2, void 0);
126083
- client_ledger_classPrivateFieldInitSpec(this, src_client_config, void 0);
126084
- client_ledger_classPrivateFieldSet(src_client_config, this, {
126085
- ...config
126086
- });
126087
- const {
126088
- baseToken,
126089
- networkAddress
126090
- } = client_lib_account.generateBaseAddresses(config.network);
126091
- this.networkAddress = networkAddress;
126092
- this.baseToken = baseToken;
126093
- this.initialTrustedAccount = config.initialTrustedAccount;
126094
- this.node = node;
126095
- if (config.kind === client_LedgerKind.REPRESENTATIVE) {
126096
- if (config.privateKey === undefined) {
126097
- throw new Error('A private key must be provided if this is a Ledger for a representative');
126098
- }
126193
+ async function client_listAccountInfo(accounts) {
126194
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126195
+ const accountInfo = {};
126196
+ const permissionPromises = Array.from(accounts).map(async account => {
126197
+ if (account.isIdentifier() === false) {
126198
+ return;
126199
+ }
126200
+ accountInfo[account.publicKeyString.get()] = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getAccountInfo(transaction, account);
126201
+ });
126202
+ await Promise.all(permissionPromises);
126203
+ return accountInfo;
126204
+ }
126205
+ async function client_checkSingleAccountPermissions(account, requirements, accountInfos) {
126206
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126207
+
126208
+ // Remove duplicates in entity
126209
+ const unfilteredEntity = requirements.map(acct => acct.entity);
126210
+ const entityAccounts = new client_lib_account.Set(unfilteredEntity).toArray();
126211
+ const gotPermissions = await this.listACLsByPrincipal(account, entityAccounts);
126212
+ for (const requirement of requirements) {
126213
+ var _accountInfos$reqEnti;
126214
+ const reqEntityKey = requirement.entity.publicKeyString.get();
126215
+ const foundACLRow = client_findPermissionMatch(requirement, gotPermissions);
126216
+ let foundPermission;
126217
+ if (foundACLRow !== null && foundACLRow !== void 0 && foundACLRow.permissions) {
126218
+ foundPermission = foundACLRow === null || foundACLRow === void 0 ? void 0 : foundACLRow.permissions;
126219
+ } else if ((_accountInfos$reqEnti = accountInfos[reqEntityKey]) !== null && _accountInfos$reqEnti !== void 0 && _accountInfos$reqEnti.defaultPermission) {
126220
+ foundPermission = accountInfos[reqEntityKey].defaultPermission;
126221
+ } else {
126222
+ foundPermission = new client_permissions_Permissions();
126099
126223
  }
126100
- if (existingStorage !== undefined) {
126101
- client_ledger_classPrivateFieldSet(client_storage2, this, existingStorage);
126102
- return;
126224
+ if (requirement.permissions === null) {
126225
+ continue;
126103
126226
  }
126104
- client_ledger_classPrivateFieldSet(client_storage2, this, config.storageDriver);
126105
- client_ledger_classPrivateFieldGet(client_storage2, this).init(client_ledger_classPrivateFieldGet(src_client_config, this), this);
126106
- }
126107
- get ledgerWriteMode() {
126108
- const retval = client_ledger_classPrivateFieldGet(src_client_config, this).ledgerWriteMode;
126109
- if (retval === undefined) {
126110
- return 'read-write';
126227
+ const hasPermissions = foundPermission.has(requirement.permissions);
126228
+ if (!hasPermissions) {
126229
+ var _requirement$target;
126230
+ const accountPubKey = account.publicKeyString.get();
126231
+ const baseFlagsStr = requirement.permissions.base.flags.join(', ');
126232
+ const externalOffsetsStr = requirement.permissions.external.trueOffsets.join(', ');
126233
+ const reqTargetKey = (_requirement$target = requirement.target) === null || _requirement$target === void 0 ? void 0 : _requirement$target.publicKeyString.get();
126234
+ throw new client_ledger('LEDGER_INVALID_PERMISSIONS', `${accountPubKey} does not have required permissions to perform action on ${reqEntityKey}/${reqTargetKey} -- needs [${baseFlagsStr}]/[${externalOffsetsStr}]`);
126111
126235
  }
126112
- return retval;
126113
- }
126114
- copy(newNode) {
126115
- return new src_client_Ledger(client_ledger_classPrivateFieldGet(src_client_config, this), newNode, client_ledger_classPrivateFieldGet(client_storage2, this));
126116
126236
  }
126117
- getFeePayToAndToken(accounts, token) {
126118
- const retval = {};
126119
- if (accounts !== undefined && accounts.length > 0) {
126120
- var _classPrivateFieldGet6;
126121
- // Get a random fee account from the set of possible accounts
126122
- const feeAccount = accounts[Math.floor(Math.random() * accounts.length)];
126123
-
126124
- // If the fee account matches the ledger private key then we can omit the account
126125
- // Fee is then paid to the vote issuer
126126
- if (!feeAccount.comparePublicKey((_classPrivateFieldGet6 = client_ledger_classPrivateFieldGet(src_client_config, this).privateKey) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.publicKeyString.get())) {
126127
- retval.payTo = feeAccount;
126237
+ }
126238
+ async function client_checkPermissionRequirements(effects) {
126239
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126240
+ const newOwners = {};
126241
+ const requirementsByPrincipal = {};
126242
+ const needToGetAccountInfoFor = new client_lib_account.Set();
126243
+ const allAccountsChanges = Object.values(effects);
126244
+ const foundMultisigSignerLengths = [];
126245
+ for (const {
126246
+ account,
126247
+ fields
126248
+ } of allAccountsChanges) {
126249
+ if (account.isMultisig()) {
126250
+ if (fields.minSignerSetLength !== undefined) {
126251
+ needToGetAccountInfoFor.add(account);
126252
+ foundMultisigSignerLengths.push([account, fields.minSignerSetLength]);
126128
126253
  }
126129
126254
  }
126130
- if (token !== undefined) {
126131
- // If base token matches ledger fee token then we can omit the token
126132
- // Fee is then paid using the base token
126133
- if (!this.baseToken.comparePublicKey(token)) {
126134
- retval.token = token;
126255
+ for (const singleRequirement of (_fields$permissionReq = fields.permissionRequirements) !== null && _fields$permissionReq !== void 0 ? _fields$permissionReq : []) {
126256
+ var _fields$permissionReq;
126257
+ const principal = singleRequirement.principal;
126258
+ const principalPubKey = principal.publicKeyString.get();
126259
+ if (!requirementsByPrincipal[principalPubKey]) {
126260
+ requirementsByPrincipal[principalPubKey] = [];
126135
126261
  }
126136
- }
126137
- return retval;
126138
- }
126139
-
126140
- /**
126141
- * Execute some code with a transaction held, if the code fails the
126142
- * transaction is aborted, otherwise it is committed
126143
- *
126144
- * @param code - Code to run
126145
- * @returns The return value from "code"
126146
- */
126147
- async run(identifier, code, readOnly) {
126148
- try {
126149
- var _this$node, _classPrivateFieldGet7, _classPrivateFieldGet8, _this$node4;
126150
- var _usingCtx = client_usingCtx2();
126151
- const _timing = _usingCtx.u((_this$node = this.node) === null || _this$node === void 0 ? void 0 : _this$node.timing.startTime(`run-${identifier}`));
126152
- let retryConfig;
126153
- if (((_classPrivateFieldGet7 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.maxRetries) !== undefined) {
126154
- retryConfig = {
126155
- mode: 'count',
126156
- maxRetries: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.maxRetries
126157
- };
126158
- } else if (((_classPrivateFieldGet8 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet8 === void 0 ? void 0 : _classPrivateFieldGet8.timeout) !== undefined) {
126159
- retryConfig = {
126160
- mode: 'time',
126161
- timeout: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.timeout
126162
- };
126163
- } else {
126164
- /* Legacy default */
126165
- // retryConfig = {
126166
- // mode: 'count',
126167
- // maxCount: 128
126168
- // };
126169
- retryConfig = {
126170
- mode: 'time',
126171
- timeout: 5000
126172
- };
126262
+ requirementsByPrincipal[principalPubKey].push(singleRequirement);
126263
+ const {
126264
+ entity,
126265
+ permissions
126266
+ } = singleRequirement;
126267
+ const entityKey = entity.publicKeyString.get();
126268
+ if (permissions === null) {
126269
+ continue;
126173
126270
  }
126174
- let retval;
126175
- let retryCount = 0;
126176
- const startTime = Date.now();
126177
- for (;; retryCount++) {
126178
- try {
126179
- let runError;
126180
- let threw = false;
126181
- const transaction = await this.beginTransaction(identifier, readOnly);
126182
- try {
126183
- retval = await code(transaction);
126184
- } catch (e) {
126185
- threw = true;
126186
- runError = e;
126187
- }
126188
-
126189
- // If running code was successful, commit, otherwise abort and throw error
126190
- if (threw === false) {
126191
- var _this$node2;
126192
- await client_RequestTiming.runTimer(`${identifier}/commit`, (_this$node2 = this.node) === null || _this$node2 === void 0 ? void 0 : _this$node2.timing, async () => {
126193
- await transaction.commit();
126194
- });
126195
- } else {
126196
- var _this$node3;
126197
- await client_RequestTiming.runTimer(`${identifier}/abort`, (_this$node3 = this.node) === null || _this$node3 === void 0 ? void 0 : _this$node3.timing, async () => {
126198
- await transaction.abort();
126199
- });
126200
- throw runError;
126201
- }
126202
- } catch (runError) {
126203
- const txnError = await client_ledger_classPrivateFieldGet(client_storage2, this).evaluateError(runError);
126204
- let shouldTryToRetry = false;
126205
- if (retryConfig.mode === 'count') {
126206
- shouldTryToRetry = retryCount < retryConfig.maxRetries;
126207
- } else if (retryConfig.mode === 'time') {
126208
- const now = Date.now();
126209
- shouldTryToRetry = now - startTime < retryConfig.timeout;
126210
- }
126211
- if (shouldTryToRetry) {
126212
- if (client_ledger.isInstance(txnError)) {
126213
- if (txnError.shouldRetry) {
126214
- let retryDelay = 20;
126215
- if (txnError.retryDelay) {
126216
- retryDelay = txnError.retryDelay;
126217
- }
126218
- await client_asleep(retryDelay);
126219
- continue;
126220
- }
126221
- }
126222
- }
126223
- throw txnError;
126271
+ if (permissions.has(['OWNER'])) {
126272
+ if (newOwners[entityKey] === undefined) {
126273
+ newOwners[entityKey] = {
126274
+ entity,
126275
+ owners: []
126276
+ };
126224
126277
  }
126225
- break;
126278
+ newOwners[entityKey].owners.push(principal);
126226
126279
  }
126227
- if (retval === undefined) {
126228
- throw new Error('Return value for run() is undefined');
126280
+ if (permissions.base.isValidForDefault && entity.isIdentifier()) {
126281
+ needToGetAccountInfoFor.add(entity);
126229
126282
  }
126230
- (_this$node4 = this.node) === null || _this$node4 === void 0 || _this$node4.stats.incr('ledger', 'dbRetries', retryCount);
126231
- return retval;
126232
- } catch (_) {
126233
- _usingCtx.e = _;
126234
- } finally {
126235
- _usingCtx.d();
126236
126283
  }
126237
126284
  }
126238
- async runReadOnly(identifier, code) {
126239
- return await this.run(identifier, code, true);
126240
- }
126241
- async beginTransaction(identifier) {
126242
- let readOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
126243
- const transactionBase = {
126244
- node: this.node,
126245
- moment: new Date(),
126246
- identifier,
126247
- readOnly
126248
- };
126249
- const transaction = await client_ledger_classPrivateFieldGet(client_storage2, this).beginTransaction(transactionBase);
126250
- return new client_LedgerAtomicInterface(transaction, client_ledger_classPrivateFieldGet(client_storage2, this), client_ledger_classPrivateFieldGet(src_client_config, this), this);
126251
- }
126252
- async vote() {
126253
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
126254
- args[_key] = arguments[_key];
126285
+ const foundAccountInfo = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_listAccountInfo).call(this, needToGetAccountInfoFor);
126286
+ for (const [multisig, foundSingerLength] of foundMultisigSignerLengths) {
126287
+ const multisigPubKey = multisig.publicKeyString.get();
126288
+ const foundInfo = foundAccountInfo[multisigPubKey];
126289
+ if (!(foundInfo !== null && foundInfo !== void 0 && foundInfo.multisigQuorum)) {
126290
+ throw new Error(`Multisig quorum not found for ${multisigPubKey}`);
126255
126291
  }
126256
- return await this.run('db-vote', async function (transaction) {
126257
- return await transaction.vote(...args);
126258
- });
126259
- }
126260
- async quote() {
126261
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
126262
- args[_key2] = arguments[_key2];
126292
+ if (foundInfo.multisigQuorum > foundSingerLength) {
126293
+ throw new client_ledger('LEDGER_INVALID_PERMISSIONS', `Quorum of ${foundInfo.multisigQuorum} not reached for ${multisigPubKey} -- got ${foundSingerLength}`);
126263
126294
  }
126264
- return await this.run('db-quote', async function (transaction) {
126265
- return await transaction.quote(...args);
126266
- });
126267
126295
  }
126268
- async add() {
126269
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
126270
- args[_key3] = arguments[_key3];
126271
- }
126272
- return await this.run('db-add', async function (transaction) {
126273
- return await transaction.add(...args);
126274
- });
126296
+ const checkPromises = [];
126297
+ for (const principalPubKey in requirementsByPrincipal) {
126298
+ const accountRequirements = requirementsByPrincipal[principalPubKey];
126299
+ const principal = client_lib_account.fromPublicKeyString(principalPubKey);
126300
+ checkPromises.push(client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkSingleAccountPermissions).call(this, principal, accountRequirements, foundAccountInfo));
126275
126301
  }
126276
- async listACLsByPrincipal() {
126277
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
126278
- args[_key4] = arguments[_key4];
126302
+ await Promise.all(checkPromises);
126303
+ return {
126304
+ newOwners
126305
+ };
126306
+ }
126307
+ /**
126308
+ * Ensure all parts of a transaction do not have a negative outcome
126309
+ * Balance/Supply cannot fall negative at any point in transaction
126310
+ * Accounts have required permissions to perform actions
126311
+ * After permission owner modifications all accounts must have exactly one owner
126312
+ */
126313
+ async function client_validateLedgerOutcome(blocks) {
126314
+ const transaction = client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126315
+ const ownersByIdentifier = {};
126316
+
126317
+ // 'ADD' or 'REMOVE' an owner from ownersByIdentifier
126318
+ const modifyOwners = (method, entity, principal) => {
126319
+ if (entity.isIdentifier() === false || entity.isMultisig()) {
126320
+ return;
126279
126321
  }
126280
- return await this.runReadOnly('db-listACLs', async function (transaction) {
126281
- return await transaction.listACLsByPrincipal(...args);
126282
- });
126283
- }
126284
- async listACLsByEntity() {
126285
- for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
126286
- args[_key5] = arguments[_key5];
126322
+ const entityPubKey = entity.assertIdentifier().publicKeyString.get();
126323
+ if (ownersByIdentifier[entityPubKey] === undefined) {
126324
+ ownersByIdentifier[entityPubKey] = {
126325
+ added: new client_lib_account.Set(),
126326
+ removed: new client_lib_account.Set()
126327
+ };
126287
126328
  }
126288
- return await this.runReadOnly('db-listACLs', async function (transaction) {
126289
- return await transaction.listACLsByEntity(...args);
126290
- });
126291
- }
126292
- async getBalance() {
126293
- for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
126294
- args[_key6] = arguments[_key6];
126329
+ switch (method) {
126330
+ case 'ADD':
126331
+ // If it is not already included, push added owner
126332
+ ownersByIdentifier[entityPubKey].added.add(principal);
126333
+ ownersByIdentifier[entityPubKey].removed.delete(principal);
126334
+ break;
126335
+ case 'REMOVE':
126336
+ // Remove owner if it is already included
126337
+ ownersByIdentifier[entityPubKey].added.delete(principal);
126338
+ ownersByIdentifier[entityPubKey].removed.add(principal);
126339
+ break;
126295
126340
  }
126296
- return await this.runReadOnly('db-getBalance', async function (transaction) {
126297
- return await transaction.getBalance(...args);
126298
- });
126299
- }
126300
- async getAllBalances() {
126301
- for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
126302
- args[_key7] = arguments[_key7];
126341
+ };
126342
+ const effects = client_computeEffectOfBlocks(blocks, client_ledger_classPrivateFieldGet(src_client_ledger, this));
126343
+ const accountEffects = effects.accounts;
126344
+ const allAccountsChanges = Object.values(accountEffects);
126345
+
126346
+ /**
126347
+ * Ensure all required permissions are met
126348
+ * See which accounts are now owners, and add those accounts to the set that we have
126349
+ */
126350
+ const {
126351
+ newOwners
126352
+ } = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_checkPermissionRequirements).call(this, accountEffects);
126353
+ for (const entityPubKey in newOwners) {
126354
+ const {
126355
+ entity,
126356
+ owners
126357
+ } = newOwners[entityPubKey];
126358
+ for (const newOwner of owners) {
126359
+ modifyOwners('ADD', entity, newOwner);
126303
126360
  }
126304
- return await this.runReadOnly('db-getAllBalances', async function (transaction) {
126305
- return await transaction.getAllBalances(...args);
126306
- });
126307
126361
  }
126308
- async getAccountCertificates() {
126309
- for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
126310
- args[_key8] = arguments[_key8];
126362
+ for (const accountChanges of allAccountsChanges) {
126363
+ var _fields$createRequest, _fields$permissions;
126364
+ const {
126365
+ account,
126366
+ fields = {}
126367
+ } = accountChanges;
126368
+
126369
+ /**
126370
+ * Newly created identifiers automatically grant the creator ownership.
126371
+ */
126372
+ const createRequests = (_fields$createRequest = fields.createRequests) !== null && _fields$createRequest !== void 0 ? _fields$createRequest : [];
126373
+ for (const createRequest of createRequests) {
126374
+ modifyOwners('ADD', createRequest.createdIdentifier, account);
126311
126375
  }
126312
- return await this.runReadOnly('db-getAccountCertificates', async function (transaction) {
126313
- return await transaction.getAccountCertificates(...args);
126314
- });
126315
- }
126316
- async getAccountCertificateByHash() {
126317
- for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
126318
- args[_key9] = arguments[_key9];
126376
+
126377
+ /**
126378
+ * If an account was granted permissions, we should take that into effect
126379
+ */
126380
+ const addedPermissions = (_fields$permissions = fields.permissions) !== null && _fields$permissions !== void 0 ? _fields$permissions : [];
126381
+ for (const newPerm of addedPermissions) {
126382
+ let method = 'ADD';
126383
+ if (newPerm.permissions === null || !newPerm.permissions.has(['OWNER'])) {
126384
+ method = 'REMOVE';
126385
+ }
126386
+ modifyOwners(method, newPerm.entity, newPerm.principal);
126319
126387
  }
126320
- return await this.runReadOnly('db-getAccountCertificateByHash', async function (transaction) {
126321
- return await transaction.getAccountCertificateByHash(...args);
126322
- });
126323
126388
  }
126324
- async votingPower() {
126325
- for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
126326
- args[_key10] = arguments[_key10];
126389
+
126390
+ /**
126391
+ * Ensure there is exactly one owner when permissions were changed
126392
+ */
126393
+ for (const [identifierPubKey, {
126394
+ added,
126395
+ removed
126396
+ }] of Object.entries(ownersByIdentifier)) {
126397
+ let ownerLength = added.size;
126398
+
126399
+ // If more than one owner was granted and not removed, we know it is invalid without checking
126400
+ if (ownerLength <= 1) {
126401
+ const identifierAccount = client_lib_account.fromPublicKeyString(identifierPubKey).assertIdentifier();
126402
+ const receivedOwners = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).listOwners(transaction, identifierAccount);
126403
+ for (const receivedOwner of receivedOwners) {
126404
+ // We already know about these owners, we do not care about adding/removing them again
126405
+ if (added.has(receivedOwner) || removed.has(receivedOwner)) {
126406
+ continue;
126407
+ }
126408
+ ownerLength++;
126409
+ }
126327
126410
  }
126328
- return await this.runReadOnly('db-votingPower', async function (transaction) {
126329
- return await transaction.votingPower(...args);
126330
- });
126331
- }
126332
- async getVotes() {
126333
- for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
126334
- args[_key11] = arguments[_key11];
126411
+ if (ownerLength === 1) {
126412
+ continue;
126335
126413
  }
126336
- return await this.runReadOnly('db-getVotes', async function (transaction) {
126337
- return await transaction.getVotes(...args);
126338
- });
126414
+ throw new client_ledger('LEDGER_INVALID_OWNER_COUNT', `Invalid number of owners for ${identifierPubKey} - Got ${ownerLength}/1`);
126339
126415
  }
126340
- async getVotesFromMultiplePrevious() {
126341
- for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
126342
- args[_key12] = arguments[_key12];
126416
+ const {
126417
+ balances
126418
+ } = await client_computeLedgerEffect({
126419
+ checkRangeConstraints: true,
126420
+ baseToken: client_ledger_classPrivateFieldGet(src_client_ledger, this).baseToken
126421
+ }, accountEffects, client_ledger_classPrivateFieldGet(client_ledger_storage, this), client_ledger_classPrivateFieldGet(client_network, this), client_ledger_classPrivateFieldGet(client_transaction, this));
126422
+ for (const accountPubKey in balances) {
126423
+ const acctBalanceChanges = balances[accountPubKey];
126424
+ for (const tokenPubKey in acctBalanceChanges) {
126425
+ const {
126426
+ change,
126427
+ fellNegative,
126428
+ receiveValidated
126429
+ } = acctBalanceChanges[tokenPubKey];
126430
+ if (fellNegative) {
126431
+ throw new client_ledger('LEDGER_INVALID_BALANCE', `Resulting balance becomes negative at one+ point(s) during this transaction for account/token ${accountPubKey}/${tokenPubKey}: change ${change}`);
126432
+ }
126433
+ if (receiveValidated === false) {
126434
+ throw new client_ledger('LEDGER_RECEIVE_NOT_MET', `${accountPubKey}/${tokenPubKey} did not receive enough of requested token. change: ${change}`);
126435
+ }
126343
126436
  }
126344
- return await this.runReadOnly('db-getVotesFromMultiplePrevious', async function (transaction) {
126345
- return await transaction.getVotesFromMultiplePrevious(...args);
126346
- });
126347
126437
  }
126348
- async getBlockFromPrevious() {
126349
- for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
126350
- args[_key13] = arguments[_key13];
126351
- }
126352
- return await this.runReadOnly('db-getBlockFromPrevious', async function (transaction) {
126353
- return await transaction.getBlockFromPrevious(...args);
126354
- });
126438
+ return effects;
126439
+ }
126440
+ async function client_validateBlocksForVote(blocks) {
126441
+ /**
126442
+ * Create a map of all blocks by their hash
126443
+ */
126444
+ const blockHashMap = {};
126445
+ for (const block of blocks) {
126446
+ blockHashMap[block.hash.toString()] = block;
126355
126447
  }
126356
- async getHeadBlocks() {
126357
- for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
126358
- args[_key14] = arguments[_key14];
126448
+ const seenBlockHashes = new client_block_BlockHash.Set();
126449
+ const usedPreviousBlockHashes = new client_block_BlockHash.Set();
126450
+ const allLedgerHeads = new Map();
126451
+ for (const block of blocks) {
126452
+ const prevBlockHash = block.previous;
126453
+ seenBlockHashes.add(block.hash);
126454
+ if (block.network !== client_ledger_classPrivateFieldGet(client_network, this)) {
126455
+ throw new client_ledger('LEDGER_INVALID_NETWORK', 'Cannot vote on block for a different network');
126359
126456
  }
126360
- return await this.runReadOnly('db-getHeadBlocks', async function (transaction) {
126361
- return await transaction.getHeadBlocks(...args);
126362
- });
126363
- }
126364
- async getHeadBlock() {
126365
- for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
126366
- args[_key15] = arguments[_key15];
126457
+ if (block.subnet !== client_ledger_classPrivateFieldGet(client_subnet, this)) {
126458
+ throw new client_ledger('LEDGER_INVALID_SUBNET', 'Cannot vote on block for a different subnet');
126367
126459
  }
126368
- return await this.runReadOnly('db-getHeadBlock', async function (transaction) {
126369
- return await transaction.getHeadBlock(...args);
126370
- });
126371
- }
126372
- async getAccountRep() {
126373
- for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) {
126374
- args[_key16] = arguments[_key16];
126460
+ if (usedPreviousBlockHashes.has(prevBlockHash)) {
126461
+ throw new client_ledger('LEDGER_PREVIOUS_ALREADY_USED', `Invalid reference to block, previous: ${prevBlockHash} has already been used`);
126375
126462
  }
126376
- return await this.runReadOnly('db-getAccountRep', async function (transaction) {
126377
- return await transaction.getAccountRep(...args);
126378
- });
126379
- }
126380
- async getAccountInfo() {
126381
- for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) {
126382
- args[_key17] = arguments[_key17];
126463
+ usedPreviousBlockHashes.add(prevBlockHash);
126464
+
126465
+ /**
126466
+ * Only allow this vote if it is the successor the current
126467
+ * HEAD block for the account, or if no blocks exist on the
126468
+ * account and its an opening block, or if the predecessor
126469
+ * block is also being voted on
126470
+ */
126471
+ let predecessorBeingVotedOn = false;
126472
+ if (!block.$opening) {
126473
+ const prevBlock = blockHashMap[prevBlockHash.toString()];
126474
+ if (prevBlock !== undefined) {
126475
+ predecessorBeingVotedOn = true;
126476
+ if (!prevBlock.account.comparePublicKey(block.account)) {
126477
+ throw new client_ledger('LEDGER_INVALID_CHAIN', 'Invalid chain, changes accounts');
126478
+ }
126479
+ if (!seenBlockHashes.has(prevBlockHash)) {
126480
+ throw new client_ledger('LEDGER_PREVIOUS_NOT_SEEN', `Invalid reference to block, out-of-order: ${prevBlockHash} has not already been seen`);
126481
+ }
126482
+ }
126383
126483
  }
126384
- return await this.runReadOnly('db-getAccountInfo', async function (transaction) {
126385
- return await transaction.getAccountInfo(...args);
126386
- });
126387
- }
126388
- async getBlock() {
126389
- for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
126390
- args[_key18] = arguments[_key18];
126484
+ if (!predecessorBeingVotedOn) {
126485
+ allLedgerHeads.set(block.account, block);
126391
126486
  }
126392
- return await this.runReadOnly('db-getBlock', async function (transaction) {
126393
- return await transaction.getBlock(...args);
126394
- });
126395
126487
  }
126396
- async getVoteStaple() {
126397
- for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) {
126398
- args[_key19] = arguments[_key19];
126399
- }
126400
- return await this.runReadOnly('db-getVoteStaple', async function (transaction) {
126401
- return await transaction.getVoteStaple(...args);
126402
- });
126488
+ return allLedgerHeads;
126489
+ }
126490
+ async function client_voteOrQuoteWithFees(blocks, type, quote) {
126491
+ var _quote$fee;
126492
+ if (client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode !== 'read-write') {
126493
+ throw new Error(`May not issue votes in read-only mode, in ${client_ledger_classPrivateFieldGet(src_client_ledger, this).ledgerWriteMode} mode`);
126403
126494
  }
126404
- async getVoteStaples() {
126405
- for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) {
126406
- args[_key20] = arguments[_key20];
126407
- }
126408
- return await this.runReadOnly('db-getVoteStaples', async function (transaction) {
126409
- return await transaction.getVoteStaples(...args);
126410
- });
126495
+ if (!client_ledger_classPrivateFieldGet(client_ledger_privateKey, this)) {
126496
+ throw new Error('Cannot vote on block, no private key loaded');
126411
126497
  }
126412
- async getHistory() {
126413
- for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) {
126414
- args[_key21] = arguments[_key21];
126498
+ client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_assertTransaction).call(this);
126499
+ const effects = await client_ledger_assertClassBrand(client_LedgerAtomicInterface_brand, this, client_validateLedgerOutcome).call(this, blocks);
126500
+ const now = Date.now();
126501
+ for (const block of blocks) {
126502
+ const blockDate = block.date.valueOf();
126503
+ const timeOffset = 5 /* m */ * 60 /* s */ * 1000 /* ms */;
126504
+
126505
+ /**
126506
+ * Do not allow short votes on blocks from the distant past
126507
+ */
126508
+ if (blockDate < now - timeOffset || blockDate > now + timeOffset) {
126509
+ throw new Error(`Refusing to issue vote for block dated ${block.date.toISOString()}`);
126415
126510
  }
126416
- return await this.runReadOnly('db-getHistory', async function (transaction) {
126417
- return await transaction.getHistory(...args);
126418
- });
126419
126511
  }
126420
- async getStaplesFromBlockHashes() {
126421
- for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) {
126422
- args[_key22] = arguments[_key22];
126423
- }
126424
- return await this.runReadOnly('db-getStaplesFromBlockHashes', async function (transaction) {
126425
- return await transaction.getStaplesFromBlockHashes(...args);
126426
- });
126512
+
126513
+ /**
126514
+ * Serial number
126515
+ */
126516
+ const serial = await client_ledger_classPrivateFieldGet(client_ledger_storage, this).getNextSerialNumber(client_ledger_classPrivateFieldGet(client_transaction, this));
126517
+
126518
+ /**
126519
+ * Short expiry (5 minutes)
126520
+ */
126521
+ const pendingVoteExpiry = new Date();
126522
+ pendingVoteExpiry.setUTCMinutes(pendingVoteExpiry.getUTCMinutes() + 5);
126523
+ const builderType = type === 'QUOTE' ? src_client_VoteQuoteBuilder : src_client_VoteBuilder;
126524
+ const builder = new builderType(client_ledger_classPrivateFieldGet(client_ledger_privateKey, this));
126525
+ for (const block of blocks) {
126526
+ builder.addBlock(block);
126427
126527
  }
126428
- async getVoteStaplesAfter() {
126429
- for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
126430
- args[_key23] = arguments[_key23];
126431
- }
126432
- return await this.runReadOnly('db-getVoteStaplesAfter', async function (transaction) {
126433
- return await transaction.getVoteStaplesAfter(...args);
126434
- });
126528
+
126529
+ /**
126530
+ * If a quote was provided use it as the fee, otherwise generate new fee
126531
+ */
126532
+ const fee = (_quote$fee = quote === null || quote === void 0 ? void 0 : quote.fee) !== null && _quote$fee !== void 0 ? _quote$fee : await this.getFee(blocks, effects);
126533
+ if (fee !== null) {
126534
+ builder.addFee(fee);
126435
126535
  }
126436
- async gc() {
126437
- for (var _len24 = arguments.length, args = new Array(_len24), _key24 = 0; _key24 < _len24; _key24++) {
126438
- args[_key24] = arguments[_key24];
126439
- }
126440
- return await this.run('db-gc', async function (transaction) {
126441
- return await transaction.gc(...args);
126536
+ const voteOrQuote = await builder.seal(serial, pendingVoteExpiry);
126537
+ return voteOrQuote;
126538
+ }
126539
+ var client_storage2 = /*#__PURE__*/new WeakMap();
126540
+ var src_client_config = /*#__PURE__*/new WeakMap();
126541
+ class src_client_Ledger {
126542
+ constructor(config, node, existingStorage) {
126543
+ client_ledger_classPrivateFieldInitSpec(this, client_storage2, void 0);
126544
+ client_ledger_classPrivateFieldInitSpec(this, src_client_config, void 0);
126545
+ client_ledger_classPrivateFieldSet(src_client_config, this, {
126546
+ ...config
126442
126547
  });
126443
- }
126444
- async getFee() {
126445
- for (var _len25 = arguments.length, args = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
126446
- args[_key25] = arguments[_key25];
126548
+ const {
126549
+ baseToken,
126550
+ networkAddress
126551
+ } = client_lib_account.generateBaseAddresses(config.network);
126552
+ this.networkAddress = networkAddress;
126553
+ this.baseToken = baseToken;
126554
+ this.initialTrustedAccount = config.initialTrustedAccount;
126555
+ this.node = node;
126556
+ if (config.kind === client_LedgerKind.REPRESENTATIVE) {
126557
+ if (config.privateKey === undefined) {
126558
+ throw new Error('A private key must be provided if this is a Ledger for a representative');
126559
+ }
126447
126560
  }
126448
- return await this.run('db-getFee', async function (transaction) {
126449
- return await transaction.getFee(...args);
126450
- });
126561
+ if (existingStorage !== undefined) {
126562
+ client_ledger_classPrivateFieldSet(client_storage2, this, existingStorage);
126563
+ return;
126564
+ }
126565
+ client_ledger_classPrivateFieldSet(client_storage2, this, config.storageDriver);
126566
+ client_ledger_classPrivateFieldGet(client_storage2, this).init(client_ledger_classPrivateFieldGet(src_client_config, this), this);
126451
126567
  }
126452
- async stats() {
126453
- try {
126454
- var _this$node5;
126455
- var _usingCtx3 = client_usingCtx2();
126456
- const _timing = _usingCtx3.u((_this$node5 = this.node) === null || _this$node5 === void 0 ? void 0 : _this$node5.timing.startTime('db-stats'));
126457
- const retval = await client_ledger_classPrivateFieldGet(client_storage2, this).stats();
126458
- return retval;
126459
- } catch (_) {
126460
- _usingCtx3.e = _;
126461
- } finally {
126462
- _usingCtx3.d();
126568
+ get ledgerWriteMode() {
126569
+ const retval = client_ledger_classPrivateFieldGet(src_client_config, this).ledgerWriteMode;
126570
+ if (retval === undefined) {
126571
+ return 'read-write';
126463
126572
  }
126573
+ return retval;
126464
126574
  }
126465
- async _testingRunStorageFunction(code) {
126466
- return await this.run('db-runStorageFunction', async function (transaction) {
126467
- return await transaction._testingRunStorageFunction(code);
126468
- });
126575
+ copy(newNode) {
126576
+ return new src_client_Ledger(client_ledger_classPrivateFieldGet(src_client_config, this), newNode, client_ledger_classPrivateFieldGet(client_storage2, this));
126469
126577
  }
126470
- }
126471
- client_Ledger = src_client_Ledger;
126472
- client_lib_ledger_defineProperty(src_client_Ledger, "Kind", client_LedgerKind);
126473
- client_lib_ledger_defineProperty(src_client_Ledger, "isInstance", client_checkableGenerator(client_Ledger));
126474
- /* harmony default export */ const client_lib_ledger = (src_client_Ledger);
126475
- ;// ./src/lib/kv/index.ts
126476
- function client_kv_defineProperty(e, r, t) { return (r = client_kv_toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
126477
- function client_kv_toPropertyKey(t) { var i = client_kv_toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
126478
- function client_kv_toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
126578
+ getFeePayToAndToken(accounts, token) {
126579
+ const retval = {};
126580
+ if (accounts !== undefined && accounts.length > 0) {
126581
+ var _classPrivateFieldGet7;
126582
+ // Get a random fee account from the set of possible accounts
126583
+ const feeAccount = accounts[Math.floor(Math.random() * accounts.length)];
126479
126584
 
126480
- class client_KVStorageProviderBase {
126481
- constructor() {
126482
- client_kv_defineProperty(this, "id", (0,client_lib_crypto.randomUUID)());
126483
- }
126484
- async xor(_ignored_arena, key, _ignored_change, _ignored_options) {
126485
- if (key.startsWith('@buffer:')) {
126486
- return;
126585
+ // If the fee account matches the ledger private key then we can omit the account
126586
+ // Fee is then paid to the vote issuer
126587
+ if (!feeAccount.comparePublicKey((_classPrivateFieldGet7 = client_ledger_classPrivateFieldGet(src_client_config, this).privateKey) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.publicKeyString.get())) {
126588
+ retval.payTo = feeAccount;
126589
+ }
126487
126590
  }
126488
- throw new Error('Key provided for XOR must begin with "@buffer"');
126591
+ if (token !== undefined) {
126592
+ // If base token matches ledger fee token then we can omit the token
126593
+ // Fee is then paid using the base token
126594
+ if (!this.baseToken.comparePublicKey(token)) {
126595
+ retval.token = token;
126596
+ }
126597
+ }
126598
+ return retval;
126489
126599
  }
126490
- }
126491
- ;// ./src/lib/kv/kv_memory.ts
126492
- function client_kv_memory_classPrivateMethodInitSpec(e, a) { client_kv_memory_checkPrivateRedeclaration(e, a), a.add(e); }
126493
- function client_kv_memory_classPrivateFieldInitSpec(e, t, a) { client_kv_memory_checkPrivateRedeclaration(e, t), t.set(e, a); }
126494
- function client_kv_memory_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
126495
- function client_kv_memory_classPrivateFieldGet(s, a) { return s.get(client_kv_memory_assertClassBrand(s, a)); }
126496
- function client_kv_memory_classPrivateFieldSet(s, a, r) { return s.set(client_kv_memory_assertClassBrand(s, a), r), r; }
126497
- function client_kv_memory_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
126498
126600
 
126601
+ /**
126602
+ * Execute some code with a transaction held, if the code fails the
126603
+ * transaction is aborted, otherwise it is committed
126604
+ *
126605
+ * @param code - Code to run
126606
+ * @returns The return value from "code"
126607
+ */
126608
+ async run(identifier, code, readOnly) {
126609
+ try {
126610
+ var _this$node, _classPrivateFieldGet8, _classPrivateFieldGet9, _this$node4;
126611
+ var _usingCtx = client_usingCtx2();
126612
+ const _timing = _usingCtx.u((_this$node = this.node) === null || _this$node === void 0 ? void 0 : _this$node.timing.startTime(`run-${identifier}`));
126613
+ let retryConfig;
126614
+ if (((_classPrivateFieldGet8 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet8 === void 0 ? void 0 : _classPrivateFieldGet8.maxRetries) !== undefined) {
126615
+ retryConfig = {
126616
+ mode: 'count',
126617
+ maxRetries: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.maxRetries
126618
+ };
126619
+ } else if (((_classPrivateFieldGet9 = client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries) === null || _classPrivateFieldGet9 === void 0 ? void 0 : _classPrivateFieldGet9.timeout) !== undefined) {
126620
+ retryConfig = {
126621
+ mode: 'time',
126622
+ timeout: client_ledger_classPrivateFieldGet(src_client_config, this).transactionRetries.timeout
126623
+ };
126624
+ } else {
126625
+ /* Legacy default */
126626
+ // retryConfig = {
126627
+ // mode: 'count',
126628
+ // maxCount: 128
126629
+ // };
126630
+ retryConfig = {
126631
+ mode: 'time',
126632
+ timeout: 5000
126633
+ };
126634
+ }
126635
+ let retval;
126636
+ let retryCount = 0;
126637
+ const startTime = Date.now();
126638
+ for (;; retryCount++) {
126639
+ try {
126640
+ let runError;
126641
+ let threw = false;
126642
+ const transaction = await this.beginTransaction(identifier, readOnly);
126643
+ try {
126644
+ retval = await code(transaction);
126645
+ } catch (e) {
126646
+ threw = true;
126647
+ runError = e;
126648
+ }
126499
126649
 
126500
- const client_nullArena = 'null:43c98976-2282-44c2-819a-769732ceb847';
126501
- function client_deserialize(value) {
126502
- if (src_client_BufferStorage.isInstance(value)) {
126503
- value = value.toString('hex');
126504
- }
126505
- return value;
126506
- }
126507
- var client_db = /*#__PURE__*/new WeakMap();
126508
- var client_KVStorageProviderMemory_brand = /*#__PURE__*/new WeakSet();
126509
- class client_KVStorageProviderMemory extends client_KVStorageProviderBase {
126510
- constructor() {
126511
- super();
126512
- client_kv_memory_classPrivateMethodInitSpec(this, client_KVStorageProviderMemory_brand);
126513
- client_kv_memory_classPrivateFieldInitSpec(this, client_db, void 0);
126514
- client_kv_memory_classPrivateFieldSet(client_db, this, {});
126515
- }
126516
- async set(arena, key, value, options) {
126517
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
126518
- if (value !== undefined) {
126519
- if (options !== null && options !== void 0 && options.exclusiveCreate) {
126520
- if (storeArena[key] !== undefined) {
126521
- throw new Error('unable to exclusively create this item, already exists');
126650
+ // If running code was successful, commit, otherwise abort and throw error
126651
+ if (threw === false) {
126652
+ var _this$node2;
126653
+ await client_RequestTiming.runTimer(`${identifier}/commit`, (_this$node2 = this.node) === null || _this$node2 === void 0 ? void 0 : _this$node2.timing, async () => {
126654
+ await transaction.commit();
126655
+ });
126656
+ } else {
126657
+ var _this$node3;
126658
+ await client_RequestTiming.runTimer(`${identifier}/abort`, (_this$node3 = this.node) === null || _this$node3 === void 0 ? void 0 : _this$node3.timing, async () => {
126659
+ await transaction.abort();
126660
+ });
126661
+ throw runError;
126662
+ }
126663
+ } catch (runError) {
126664
+ const txnError = await client_ledger_classPrivateFieldGet(client_storage2, this).evaluateError(runError);
126665
+ let shouldTryToRetry = false;
126666
+ if (retryConfig.mode === 'count') {
126667
+ shouldTryToRetry = retryCount < retryConfig.maxRetries;
126668
+ } else if (retryConfig.mode === 'time') {
126669
+ const now = Date.now();
126670
+ shouldTryToRetry = now - startTime < retryConfig.timeout;
126671
+ }
126672
+ if (shouldTryToRetry) {
126673
+ if (client_ledger.isInstance(txnError)) {
126674
+ if (txnError.shouldRetry) {
126675
+ let retryDelay = 20;
126676
+ if (txnError.retryDelay) {
126677
+ retryDelay = txnError.retryDelay;
126678
+ }
126679
+ await client_asleep(retryDelay);
126680
+ continue;
126681
+ }
126682
+ }
126683
+ }
126684
+ throw txnError;
126522
126685
  }
126686
+ break;
126523
126687
  }
126524
- }
126525
- let expiry;
126526
- if ((options === null || options === void 0 ? void 0 : options.ttl) !== undefined) {
126527
- expiry = Date.now() + options.ttl;
126528
- }
126529
- if (value === undefined || value === null) {
126530
- delete storeArena[key];
126531
- return;
126532
- }
126533
- storeArena[key] = {
126534
- value,
126535
- expiry
126536
- };
126537
- }
126538
- async get(arena, key) {
126539
- if (arena === null) {
126540
- arena = client_nullArena;
126541
- }
126542
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
126543
- if (!storeArena[key]) {
126544
- return undefined;
126545
- }
126546
- const {
126547
- expiry,
126548
- value
126549
- } = storeArena[key];
126550
- if (expiry !== undefined) {
126551
- if (expiry < Date.now()) {
126552
- delete storeArena[key];
126553
- return undefined;
126688
+ if (retval === undefined) {
126689
+ throw new Error('Return value for run() is undefined');
126554
126690
  }
126691
+ (_this$node4 = this.node) === null || _this$node4 === void 0 || _this$node4.stats.incr('ledger', 'dbRetries', retryCount);
126692
+ return retval;
126693
+ } catch (_) {
126694
+ _usingCtx.e = _;
126695
+ } finally {
126696
+ _usingCtx.d();
126555
126697
  }
126556
- const retval = client_deserialize(value);
126557
- return retval;
126558
126698
  }
126559
- async getAll(arena) {
126560
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
126561
- const retval = {};
126562
- for (const key in storeArena) {
126563
- const value = await this.get(arena, key);
126564
- if (value === undefined) {
126565
- continue;
126566
- }
126567
- retval[key] = value;
126699
+ async runReadOnly(identifier, code) {
126700
+ return await this.run(identifier, code, true);
126701
+ }
126702
+ async beginTransaction(identifier) {
126703
+ let readOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
126704
+ const transaction = await client_ledger_classPrivateFieldGet(client_storage2, this).beginTransaction({
126705
+ node: this.node,
126706
+ moment: new Date(),
126707
+ identifier,
126708
+ readOnly
126709
+ });
126710
+ return new client_LedgerAtomicInterface(transaction, client_ledger_classPrivateFieldGet(client_storage2, this), client_ledger_classPrivateFieldGet(src_client_config, this), this);
126711
+ }
126712
+ async vote() {
126713
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
126714
+ args[_key] = arguments[_key];
126568
126715
  }
126569
- return retval;
126716
+ return await this.run('db-vote', async function (transaction) {
126717
+ return await transaction.vote(...args);
126718
+ });
126570
126719
  }
126571
- async list(arena) {
126572
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
126573
- return Object.keys(storeArena);
126720
+ async quote() {
126721
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
126722
+ args[_key2] = arguments[_key2];
126723
+ }
126724
+ return await this.run('db-quote', async function (transaction) {
126725
+ return await transaction.quote(...args);
126726
+ });
126574
126727
  }
126575
- async incr(arena, key, change) {
126576
- var _previous$value;
126577
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, arena);
126578
- const previous = storeArena[key];
126579
- let previousValue = (_previous$value = previous === null || previous === void 0 ? void 0 : previous.value) !== null && _previous$value !== void 0 ? _previous$value : 0;
126580
- if (typeof previousValue !== 'number') {
126581
- throw new Error('May not increment non-number');
126728
+ async add() {
126729
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
126730
+ args[_key3] = arguments[_key3];
126582
126731
  }
126583
- let newExpiry;
126584
- if ((previous === null || previous === void 0 ? void 0 : previous.expiry) !== undefined) {
126585
- if (previous.expiry < Date.now()) {
126586
- previousValue = 0;
126587
- } else {
126588
- newExpiry = previous.expiry;
126589
- }
126732
+ return await this.run('db-add', async function (transaction) {
126733
+ return await transaction.add(...args);
126734
+ });
126735
+ }
126736
+ async listACLsByPrincipal() {
126737
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
126738
+ args[_key4] = arguments[_key4];
126590
126739
  }
126591
- const newVal = previousValue + change;
126592
- storeArena[key] = {
126593
- value: newVal,
126594
- expiry: newExpiry
126595
- };
126596
- return BigInt(newVal);
126740
+ return await this.runReadOnly('db-listACLs', async function (transaction) {
126741
+ return await transaction.listACLsByPrincipal(...args);
126742
+ });
126597
126743
  }
126598
- async xor(arena, key, change) {
126599
- await super.xor(arena, key, change);
126600
- const storeArena = client_kv_memory_assertClassBrand(client_KVStorageProviderMemory_brand, this, client_getArena).call(this, client_nullArena);
126601
- const previous = storeArena[key];
126602
- const value = previous === null || previous === void 0 ? void 0 : previous.value;
126603
- if (value === undefined) {
126604
- storeArena[key] = {
126605
- value: change
126606
- };
126607
- return;
126744
+ async listACLsByEntity() {
126745
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
126746
+ args[_key5] = arguments[_key5];
126608
126747
  }
126609
- if (!src_client_BufferStorage.isInstance(value) || previous.expiry !== undefined) {
126610
- throw new Error('May only use XOR on keys containing BufferStorage without expiry');
126748
+ return await this.runReadOnly('db-listACLs', async function (transaction) {
126749
+ return await transaction.listACLsByEntity(...args);
126750
+ });
126751
+ }
126752
+ async getBalance() {
126753
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
126754
+ args[_key6] = arguments[_key6];
126611
126755
  }
126612
- const valueBigInt = value.toBigInt();
126613
- const changeBigInt = change.toBigInt();
126614
- const valueLength = Math.max(value.length, change.length);
126615
- const newValue = valueBigInt ^ changeBigInt;
126616
- storeArena[key] = {
126617
- value: new src_client_BufferStorage(newValue, valueLength)
126618
- };
126756
+ return await this.runReadOnly('db-getBalance', async function (transaction) {
126757
+ return await transaction.getBalance(...args);
126758
+ });
126619
126759
  }
126620
- }
126621
- function client_getArena(arena) {
126622
- if (client_kv_memory_classPrivateFieldGet(client_db, this)[arena] === undefined) {
126623
- client_kv_memory_classPrivateFieldGet(client_db, this)[arena] = {};
126760
+ async getAllBalances() {
126761
+ for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
126762
+ args[_key7] = arguments[_key7];
126763
+ }
126764
+ return await this.runReadOnly('db-getAllBalances', async function (transaction) {
126765
+ return await transaction.getAllBalances(...args);
126766
+ });
126624
126767
  }
126625
- return client_kv_memory_classPrivateFieldGet(client_db, this)[arena];
126626
- }
126627
- /* harmony default export */ const client_kv_memory = (client_KVStorageProviderMemory);
126628
- ;// ./src/lib/stats.ts
126629
- function client_stats_classPrivateMethodInitSpec(e, a) { client_stats_checkPrivateRedeclaration(e, a), a.add(e); }
126630
- function client_stats_classPrivateFieldInitSpec(e, t, a) { client_stats_checkPrivateRedeclaration(e, t), t.set(e, a); }
126631
- function client_stats_checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
126632
- function client_stats_classPrivateFieldGet(s, a) { return s.get(client_stats_assertClassBrand(s, a)); }
126633
- function client_stats_classPrivateFieldSet(s, a, r) { return s.set(client_stats_assertClassBrand(s, a), r), r; }
126634
- function client_stats_assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
126635
-
126636
-
126637
-
126638
- /**
126639
- * Size of the XOR buffer objects -- we use them for block hashes so they
126640
- * should be the same size as a block hash
126641
- */
126642
- const client_XOR_BUFFER_SIZE = client_HashFunctionLength;
126643
- const client_durationRanges = {
126644
- '-1ms': [-1, -1],
126645
- '0ms': [0, 0],
126646
- '10ms': [1, 10],
126647
- '100ms': [11, 100],
126648
- '200ms': [101, 200],
126649
- '300ms': [201, 300],
126650
- '400ms': [301, 400],
126651
- '500ms': [401, 500],
126652
- '600ms': [501, 600],
126653
- '700ms': [601, 700],
126654
- '800ms': [701, 800],
126655
- '900ms': [801, 900],
126656
- '1000ms': [901, 1000],
126657
- '1500ms': [1001, 1500],
126658
- '2000ms': [1501, 2000],
126659
- '5000ms': [2001, 5000],
126660
- '10000ms': [5001, 10000],
126661
- '100000ms': [10001, 100000],
126662
- 'ExtraLong': [100000, Number.MAX_SAFE_INTEGER]
126663
- };
126664
- var client_localDBIncr = /*#__PURE__*/new WeakMap();
126665
- var client_localDBXOR = /*#__PURE__*/new WeakMap();
126666
- var client_syncPromise = /*#__PURE__*/new WeakMap();
126667
- var client_kv = /*#__PURE__*/new WeakMap();
126668
- var client_Stats_brand = /*#__PURE__*/new WeakSet();
126669
- class client_Stats {
126670
- constructor(config) {
126671
- client_stats_classPrivateMethodInitSpec(this, client_Stats_brand);
126672
- client_stats_classPrivateFieldInitSpec(this, client_localDBIncr, {});
126673
- client_stats_classPrivateFieldInitSpec(this, client_localDBXOR, {});
126674
- client_stats_classPrivateFieldInitSpec(this, client_syncPromise, void 0);
126675
- client_stats_classPrivateFieldInitSpec(this, client_kv, void 0);
126676
- let kv = config.kv;
126677
- if (kv === null) {
126678
- kv = new client_kv_memory();
126768
+ async getAccountCertificates() {
126769
+ for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
126770
+ args[_key8] = arguments[_key8];
126679
126771
  }
126680
- client_stats_classPrivateFieldSet(client_kv, this, kv);
126772
+ return await this.runReadOnly('db-getAccountCertificates', async function (transaction) {
126773
+ return await transaction.getAccountCertificates(...args);
126774
+ });
126681
126775
  }
126682
- // Return all keys from durationRanges
126683
- static durationBreakdownList() {
126684
- // We know the keys are all valid to the type, but typescript does not know this
126685
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
126686
- return Object.keys(client_durationRanges);
126776
+ async getAccountCertificateByHash() {
126777
+ for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
126778
+ args[_key9] = arguments[_key9];
126779
+ }
126780
+ return await this.runReadOnly('db-getAccountCertificateByHash', async function (transaction) {
126781
+ return await transaction.getAccountCertificateByHash(...args);
126782
+ });
126687
126783
  }
126688
- static assertDurationBreakdown(duration) {
126689
- if (!(duration in client_durationRanges)) {
126690
- throw new Error(`Invalid duration: ${duration}`);
126784
+ async votingPower() {
126785
+ for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
126786
+ args[_key10] = arguments[_key10];
126691
126787
  }
126788
+ return await this.runReadOnly('db-votingPower', async function (transaction) {
126789
+ return await transaction.votingPower(...args);
126790
+ });
126692
126791
  }
126693
- // Get duration key for specific number
126694
- static durationBreakdown(duration) {
126695
- // Loop through ranges and select key with range that fits around duration
126696
-
126697
- if (duration < 0) {
126698
- duration = 0;
126792
+ async getVotes() {
126793
+ for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
126794
+ args[_key11] = arguments[_key11];
126699
126795
  }
126700
- for (const name of this.durationBreakdownList()) {
126701
- const [min, max] = client_durationRanges[name];
126702
- if (duration >= min && (max === undefined || duration <= max)) {
126703
- return name;
126704
- }
126796
+ return await this.runReadOnly('db-getVotes', async function (transaction) {
126797
+ return await transaction.getVotes(...args);
126798
+ });
126799
+ }
126800
+ async getVotesFromMultiplePrevious() {
126801
+ for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
126802
+ args[_key12] = arguments[_key12];
126705
126803
  }
126706
- throw new Error(`Time frame not found for duration: ${duration}`);
126804
+ return await this.runReadOnly('db-getVotesFromMultiplePrevious', async function (transaction) {
126805
+ return await transaction.getVotesFromMultiplePrevious(...args);
126806
+ });
126707
126807
  }
126708
- static placeholderTimingData() {
126709
- const ret = {};
126710
- for (const key of this.durationBreakdownList()) {
126711
- ret[key] = {
126712
- count: -1,
126713
- range: client_stats_assertClassBrand(client_Stats, this, client_getDurationRange).call(this, key)
126714
- };
126808
+ async getBlockFromPrevious() {
126809
+ for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
126810
+ args[_key13] = arguments[_key13];
126715
126811
  }
126716
-
126717
- // We know this fits TimeStats because we just created it with all of the keys
126718
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
126719
- return ret;
126812
+ return await this.runReadOnly('db-getBlockFromPrevious', async function (transaction) {
126813
+ return await transaction.getBlockFromPrevious(...args);
126814
+ });
126720
126815
  }
126721
- incr(arena, key) {
126722
- let change = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
126723
- const compoundKey = client_stats_assertClassBrand(client_Stats_brand, this, client_compoundKey).call(this, arena, key);
126724
- if (client_stats_classPrivateFieldGet(client_localDBIncr, this)[compoundKey] === undefined) {
126725
- client_stats_classPrivateFieldGet(client_localDBIncr, this)[compoundKey] = 0;
126816
+ async getHeadBlocks() {
126817
+ for (var _len14 = arguments.length, args = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
126818
+ args[_key14] = arguments[_key14];
126726
126819
  }
126727
- client_stats_classPrivateFieldGet(client_localDBIncr, this)[compoundKey] += change;
126820
+ return await this.runReadOnly('db-getHeadBlocks', async function (transaction) {
126821
+ return await transaction.getHeadBlocks(...args);
126822
+ });
126728
126823
  }
126729
- xor(key, change) {
126730
- const changeValue = change.toBigInt();
126731
- const existingValue = client_stats_classPrivateFieldGet(client_localDBXOR, this)[key];
126732
- if (existingValue === undefined) {
126733
- client_stats_classPrivateFieldGet(client_localDBXOR, this)[key] = changeValue;
126734
- return;
126824
+ async getHeadBlock() {
126825
+ for (var _len15 = arguments.length, args = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
126826
+ args[_key15] = arguments[_key15];
126735
126827
  }
126736
- client_stats_classPrivateFieldGet(client_localDBXOR, this)[key] ^= changeValue;
126828
+ return await this.runReadOnly('db-getHeadBlock', async function (transaction) {
126829
+ return await transaction.getHeadBlock(...args);
126830
+ });
126737
126831
  }
126738
- async getXor(key) {
126739
- await client_stats_classPrivateFieldGet(client_syncPromise, this);
126740
- const bufferKey = `@buffer:${key}`;
126741
- const baseString = await client_stats_classPrivateFieldGet(client_kv, this).get(null, bufferKey);
126742
- let base = 0n;
126743
- if (baseString !== undefined) {
126744
- base = BigInt(`0x${baseString}`);
126832
+ async getAccountRep() {
126833
+ for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) {
126834
+ args[_key16] = arguments[_key16];
126745
126835
  }
126746
- let local = 0n;
126747
- if (client_stats_classPrivateFieldGet(client_localDBXOR, this)[key] !== undefined) {
126748
- local = client_stats_classPrivateFieldGet(client_localDBXOR, this)[key];
126836
+ return await this.runReadOnly('db-getAccountRep', async function (transaction) {
126837
+ return await transaction.getAccountRep(...args);
126838
+ });
126839
+ }
126840
+ async getAccountInfo() {
126841
+ for (var _len17 = arguments.length, args = new Array(_len17), _key17 = 0; _key17 < _len17; _key17++) {
126842
+ args[_key17] = arguments[_key17];
126749
126843
  }
126750
- const computed = base ^ local;
126751
- const retval = new src_client_BufferStorage(computed, client_XOR_BUFFER_SIZE);
126752
- return retval;
126844
+ return await this.runReadOnly('db-getAccountInfo', async function (transaction) {
126845
+ return await transaction.getAccountInfo(...args);
126846
+ });
126753
126847
  }
126754
-
126755
- // Calculate key and increment for specific duration/category
126756
- addTimingPoint(arena, category, duration) {
126757
- let returnOnly = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
126758
- const breakdown = client_Stats.durationBreakdown(duration);
126759
- const params = [arena, `${category}@${breakdown}`, 1];
126760
- if (returnOnly !== true) {
126761
- this.incr(...params);
126848
+ async getBlock() {
126849
+ for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
126850
+ args[_key18] = arguments[_key18];
126762
126851
  }
126763
- return params;
126852
+ return await this.runReadOnly('db-getBlock', async function (transaction) {
126853
+ return await transaction.getBlock(...args);
126854
+ });
126764
126855
  }
126765
- addRequestTiming(arena, timing) {
126766
- let returnOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
126767
- const retval = [];
126768
- for (const sectionInfo of Object.values(timing.getAllTiming())) {
126769
- const duration = sectionInfo.duration;
126770
- const name = sectionInfo.name;
126771
- retval.push(this.addTimingPoint(arena, name, duration, returnOnly));
126856
+ async getVoteStaple() {
126857
+ for (var _len19 = arguments.length, args = new Array(_len19), _key19 = 0; _key19 < _len19; _key19++) {
126858
+ args[_key19] = arguments[_key19];
126772
126859
  }
126773
- return retval;
126860
+ return await this.runReadOnly('db-getVoteStaple', async function (transaction) {
126861
+ return await transaction.getVoteStaple(...args);
126862
+ });
126774
126863
  }
126775
- async get(arena, key) {
126776
- await client_stats_classPrivateFieldGet(client_syncPromise, this);
126777
- const compoundKey = client_stats_assertClassBrand(client_Stats_brand, this, client_compoundKey).call(this, arena, key);
126778
- let base = await client_stats_classPrivateFieldGet(client_kv, this).get('stats', compoundKey);
126779
- if (base === undefined) {
126780
- base = 0;
126864
+ async getVoteStaples() {
126865
+ for (var _len20 = arguments.length, args = new Array(_len20), _key20 = 0; _key20 < _len20; _key20++) {
126866
+ args[_key20] = arguments[_key20];
126781
126867
  }
126782
- if (typeof base === 'string') {
126783
- base = Number(base);
126868
+ return await this.runReadOnly('db-getVoteStaples', async function (transaction) {
126869
+ return await transaction.getVoteStaples(...args);
126870
+ });
126871
+ }
126872
+ async getHistory() {
126873
+ for (var _len21 = arguments.length, args = new Array(_len21), _key21 = 0; _key21 < _len21; _key21++) {
126874
+ args[_key21] = arguments[_key21];
126784
126875
  }
126785
- if (typeof base !== 'number' || isNaN(base)) {
126786
- throw new Error('internal error: corrupt data in stats table');
126876
+ return await this.runReadOnly('db-getHistory', async function (transaction) {
126877
+ return await transaction.getHistory(...args);
126878
+ });
126879
+ }
126880
+ async getStaplesFromBlockHashes() {
126881
+ for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) {
126882
+ args[_key22] = arguments[_key22];
126787
126883
  }
126788
- let local = 0;
126789
- if (client_stats_classPrivateFieldGet(client_localDBIncr, this)[compoundKey] !== undefined) {
126790
- local = client_stats_classPrivateFieldGet(client_localDBIncr, this)[compoundKey];
126884
+ return await this.runReadOnly('db-getStaplesFromBlockHashes', async function (transaction) {
126885
+ return await transaction.getStaplesFromBlockHashes(...args);
126886
+ });
126887
+ }
126888
+ async getVoteStaplesAfter() {
126889
+ for (var _len23 = arguments.length, args = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
126890
+ args[_key23] = arguments[_key23];
126791
126891
  }
126792
- return base + local;
126892
+ return await this.runReadOnly('db-getVoteStaplesAfter', async function (transaction) {
126893
+ return await transaction.getVoteStaplesAfter(...args);
126894
+ });
126793
126895
  }
126794
-
126795
- // Get all timing data from specific arena/category
126796
- async getTimingData(arena, category) {
126797
- const retval = client_Stats.placeholderTimingData();
126798
- const keys = Object.keys(retval);
126799
- client_assertDurationBreakdowns.call(client_Stats, keys);
126800
- await Promise.all(keys.map(async breakdown => {
126801
- const key = `${category}@${breakdown}`;
126802
- const range = client_getDurationRange.call(client_Stats, breakdown);
126803
- let count = -1;
126804
- try {
126805
- count = await this.get(arena, key);
126806
- } catch (_ignored_error) {
126807
- /* Errors fetching single stat are ignored */
126808
- } finally {
126809
- retval[breakdown] = {
126810
- count,
126811
- range
126812
- };
126813
- }
126814
- }));
126815
- return retval;
126896
+ async gc() {
126897
+ for (var _len24 = arguments.length, args = new Array(_len24), _key24 = 0; _key24 < _len24; _key24++) {
126898
+ args[_key24] = arguments[_key24];
126899
+ }
126900
+ return await this.run('db-gc', async function (transaction) {
126901
+ return await transaction.gc(...args);
126902
+ });
126816
126903
  }
126817
- async sync() {
126818
- const localDBIncr = Object.entries(client_stats_classPrivateFieldGet(client_localDBIncr, this));
126819
- const localDBXOR = Object.entries(client_stats_classPrivateFieldGet(client_localDBXOR, this));
126820
- client_stats_classPrivateFieldSet(client_localDBIncr, this, {});
126821
- client_stats_classPrivateFieldSet(client_localDBXOR, this, {});
126822
- await client_stats_classPrivateFieldGet(client_syncPromise, this);
126823
- client_stats_classPrivateFieldSet(client_syncPromise, this, (async () => {
126824
- const updatePromises = [];
126825
- for (const [key, value] of localDBIncr) {
126826
- if (value === undefined) {
126827
- continue;
126828
- }
126829
- updatePromises.push(client_stats_classPrivateFieldGet(client_kv, this).incr('stats', key, value));
126830
- }
126831
- for (const [key, value] of localDBXOR) {
126832
- if (value === undefined) {
126833
- continue;
126834
- }
126835
- const valueBuffer = new src_client_BufferStorage(value, client_XOR_BUFFER_SIZE);
126836
- const bufferKey = `@buffer:${key}`;
126837
- updatePromises.push(client_stats_classPrivateFieldGet(client_kv, this).xor(null, bufferKey, valueBuffer));
126838
- }
126839
- await Promise.all(updatePromises);
126840
- })());
126841
- await client_stats_classPrivateFieldGet(client_syncPromise, this);
126842
- client_stats_classPrivateFieldSet(client_syncPromise, this, undefined);
126904
+ async getFee() {
126905
+ for (var _len25 = arguments.length, args = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
126906
+ args[_key25] = arguments[_key25];
126907
+ }
126908
+ return await this.runReadOnly('db-getFee', async function (transaction) {
126909
+ return await transaction.getFee(...args);
126910
+ });
126843
126911
  }
126844
- }
126845
- function client_compoundKey(arena, key) {
126846
- const compoundKey = [arena, key].join('|');
126847
- return compoundKey;
126848
- }
126849
- function client_assertDurationBreakdowns(durations) {
126850
- for (const duration of durations) {
126851
- this.assertDurationBreakdown(duration);
126912
+ async stats() {
126913
+ try {
126914
+ var _this$node5;
126915
+ var _usingCtx3 = client_usingCtx2();
126916
+ const _timing = _usingCtx3.u((_this$node5 = this.node) === null || _this$node5 === void 0 ? void 0 : _this$node5.timing.startTime('db-stats'));
126917
+ const retval = await client_ledger_classPrivateFieldGet(client_storage2, this).stats();
126918
+ return retval;
126919
+ } catch (_) {
126920
+ _usingCtx3.e = _;
126921
+ } finally {
126922
+ _usingCtx3.d();
126923
+ }
126852
126924
  }
126853
- }
126854
- function client_getDurationRange(duration) {
126855
- this.assertDurationBreakdown(duration);
126856
- const range = client_durationRanges[duration];
126857
- if (!range) {
126858
- throw new Error(`Could not get range for invalid duration: ${duration}, got range ${range}`);
126925
+ async _testingRunStorageFunction(code) {
126926
+ return await this.run('db-runStorageFunction', async function (transaction) {
126927
+ return await transaction._testingRunStorageFunction(code);
126928
+ });
126859
126929
  }
126860
-
126861
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
126862
- return range;
126863
126930
  }
126864
- /* harmony default export */ const client_stats = (client_Stats);
126931
+ client_Ledger = src_client_Ledger;
126932
+ client_lib_ledger_defineProperty(src_client_Ledger, "Kind", client_LedgerKind);
126933
+ client_lib_ledger_defineProperty(src_client_Ledger, "isInstance", client_checkableGenerator(client_Ledger));
126934
+ /* harmony default export */ const client_lib_ledger = (src_client_Ledger);
126865
126935
  // EXTERNAL MODULE: ws (ignored)
126866
126936
  var client_ws_ignored_ = __webpack_require__(4708);
126867
126937
  ;// ./src/version.ts
126868
- const client_version = '0.14.0+g8b0bdc16c0cba85135437a9ffb3a8cea2dae170d';
126938
+ const client_version = '0.14.2+g68f40cc8d6fed6135fa06451bd1fb0691868e25f';
126869
126939
  /* harmony default export */ const client_src_version = ((/* unused pure expression or super */ null && (client_version)));
126870
126940
  ;// ./src/lib/p2p.ts
126871
126941
  /* provided dependency */ var client_p2p_Buffer = __webpack_require__(8287)["Buffer"];
@@ -127583,6 +127653,8 @@ var client_localNode = /*#__PURE__*/new WeakMap();
127583
127653
  var client_manualPeersCheckIntervals = /*#__PURE__*/new WeakMap();
127584
127654
  var client_asyncSends = /*#__PURE__*/new WeakMap();
127585
127655
  var client_messageFilterCache = /*#__PURE__*/new WeakMap();
127656
+ var client_cachedLocalPeerInfo = /*#__PURE__*/new WeakMap();
127657
+ var client_cachedLocalPeerSerialized = /*#__PURE__*/new WeakMap();
127586
127658
  var client_P2PSwitch_brand = /*#__PURE__*/new WeakSet();
127587
127659
  var client_peersCacheSet = /*#__PURE__*/new WeakMap();
127588
127660
  class src_client_P2PSwitch {
@@ -127618,6 +127690,8 @@ class src_client_P2PSwitch {
127618
127690
  client_p2p_classPrivateFieldInitSpec(this, client_manualPeersCheckIntervals, void 0);
127619
127691
  client_p2p_classPrivateFieldInitSpec(this, client_asyncSends, []);
127620
127692
  client_p2p_classPrivateFieldInitSpec(this, client_messageFilterCache, {});
127693
+ client_p2p_classPrivateFieldInitSpec(this, client_cachedLocalPeerInfo, undefined);
127694
+ client_p2p_classPrivateFieldInitSpec(this, client_cachedLocalPeerSerialized, undefined);
127621
127695
  /**
127622
127696
  * Write a debug or error message to the connected node.
127623
127697
  *
@@ -127962,11 +128036,14 @@ class src_client_P2PSwitch {
127962
128036
  return await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
127963
128037
  }
127964
128038
  async getOutgoingGreetingInfo() {
127965
- const greetingInfo = await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
127966
- if (greetingInfo === null) {
127967
- throw new Error('Invalid NodeKind for emitting outgoing greeting');
128039
+ if (client_p2p_classPrivateFieldGet(client_cachedLocalPeerSerialized, this) === undefined) {
128040
+ const greetingInfo = await client_p2p_assertClassBrand(client_P2PSwitch_brand, this, client_getLocalPeerInfo).call(this);
128041
+ if (greetingInfo === null) {
128042
+ throw new Error('Invalid NodeKind for emitting outgoing greeting');
128043
+ }
128044
+ client_p2p_classPrivateFieldSet(client_cachedLocalPeerSerialized, this, client_P2PPeerToJSO(greetingInfo));
127968
128045
  }
127969
- return client_P2PPeerToJSO(greetingInfo);
128046
+ return client_p2p_classPrivateFieldGet(client_cachedLocalPeerSerialized, this);
127970
128047
  }
127971
128048
  /**
127972
128049
  * Receive a message from a connection
@@ -128655,47 +128732,50 @@ async function client_performPeerCleanup() {
128655
128732
  /** XXX:TODO */
128656
128733
  }
128657
128734
  async function client_getLocalPeerInfo() {
128658
- let greetingInfo;
128659
- switch (client_p2p_classPrivateFieldGet(client_localNode, this).config.kind) {
128660
- case client_node_NodeKind.PARTICIPANT:
128661
- greetingInfo = {
128662
- kind: client_p2p_classPrivateFieldGet(client_localNode, this).config.kind,
128663
- id: 'unused'
128664
- };
128665
- break;
128666
- case client_node_NodeKind.REPRESENTATIVE:
128667
- {
128668
- if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints === undefined) {
128669
- throw new Error('internal error: Our endpoints are not defined');
128670
- }
128671
- if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.p2p === undefined) {
128672
- throw new Error('internal error: Our endpoint (p2p) is not defined');
128673
- }
128674
- if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.api === undefined) {
128675
- throw new Error('internal error: Our endpoint (api) is not defined');
128676
- }
128677
- if (client_p2p_classPrivateFieldGet(client_localNode, this).config.ledgerPrivateKey === undefined) {
128678
- throw new Error('internal error: Our ledger key is not defined');
128679
- }
128680
- const greetingInfoSigned = await client_generateP2PPeerSigned({
128735
+ if (client_p2p_classPrivateFieldGet(client_cachedLocalPeerInfo, this) === undefined) {
128736
+ let greetingInfo;
128737
+ switch (client_p2p_classPrivateFieldGet(client_localNode, this).config.kind) {
128738
+ case client_node_NodeKind.PARTICIPANT:
128739
+ greetingInfo = {
128681
128740
  kind: client_p2p_classPrivateFieldGet(client_localNode, this).config.kind,
128682
- key: client_p2p_classPrivateFieldGet(client_localNode, this).config.ledgerPrivateKey,
128683
- endpoints: {
128684
- p2p: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.p2p,
128685
- api: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.api
128686
- },
128687
- preferUpdates: this.config.useHTTPRepublish ? 'http' : 'websocket'
128688
- });
128689
- if (greetingInfoSigned === null) {
128690
- throw new Error('internal error: Could not generate signature');
128691
- }
128692
- greetingInfo = greetingInfoSigned;
128741
+ id: 'unused'
128742
+ };
128693
128743
  break;
128694
- }
128695
- default:
128696
- return null;
128744
+ case client_node_NodeKind.REPRESENTATIVE:
128745
+ {
128746
+ if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints === undefined) {
128747
+ throw new Error('internal error: Our endpoints are not defined');
128748
+ }
128749
+ if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.p2p === undefined) {
128750
+ throw new Error('internal error: Our endpoint (p2p) is not defined');
128751
+ }
128752
+ if (client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.api === undefined) {
128753
+ throw new Error('internal error: Our endpoint (api) is not defined');
128754
+ }
128755
+ if (client_p2p_classPrivateFieldGet(client_localNode, this).config.ledgerPrivateKey === undefined) {
128756
+ throw new Error('internal error: Our ledger key is not defined');
128757
+ }
128758
+ const greetingInfoSigned = await client_generateP2PPeerSigned({
128759
+ kind: client_p2p_classPrivateFieldGet(client_localNode, this).config.kind,
128760
+ key: client_p2p_classPrivateFieldGet(client_localNode, this).config.ledgerPrivateKey,
128761
+ endpoints: {
128762
+ p2p: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.p2p,
128763
+ api: client_p2p_classPrivateFieldGet(client_localNode, this).config.endpoints.api
128764
+ },
128765
+ preferUpdates: this.config.useHTTPRepublish ? 'http' : 'websocket'
128766
+ });
128767
+ if (greetingInfoSigned === null) {
128768
+ throw new Error('internal error: Could not generate signature');
128769
+ }
128770
+ greetingInfo = greetingInfoSigned;
128771
+ break;
128772
+ }
128773
+ default:
128774
+ return null;
128775
+ }
128776
+ client_p2p_classPrivateFieldSet(client_cachedLocalPeerInfo, this, greetingInfo);
128697
128777
  }
128698
- return greetingInfo;
128778
+ return client_p2p_classPrivateFieldGet(client_cachedLocalPeerInfo, this);
128699
128779
  }
128700
128780
  async function client_emitOutgoingGreeting(to) {
128701
128781
  const messageID = client_esm_browser_v4();
@@ -129353,9 +129433,18 @@ function client_builder_assertClassBrand(e, t, n) { if ("function" == typeof e ?
129353
129433
 
129354
129434
 
129355
129435
 
129436
+ /** @expand */
129437
+
129356
129438
  /** @expandType GetPrevFunction */
129357
129439
 
129358
- /** @useDeclaredType */
129440
+ /** @expand */
129441
+
129442
+ /*
129443
+ * Ensure that BlockBuilderOptions is exactly the same as
129444
+ * Partial<AccountSignerOptions> -- we do this so that the
129445
+ * documentation gets generated correctly, otherwise it
129446
+ * gets confused by `Partial`
129447
+ */
129359
129448
 
129360
129449
  /**
129361
129450
  * Either a UserClient or an object with a client and network