@keetanetwork/keetanet-client 0.14.13 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/client/builder.d.ts +29 -3
  2. package/client/index-browser.d.ts +24 -6
  3. package/client/index-browser.js +3426 -2704
  4. package/client/index.d.ts +24 -6
  5. package/client/index.js +1107 -501
  6. package/config/index.d.ts +3 -0
  7. package/docs/assets/hierarchy.js +1 -1
  8. package/docs/assets/search.js +1 -1
  9. package/docs/classes/KeetaNetSDK.Client.html +6 -5
  10. package/docs/classes/KeetaNetSDK.Referenced.Account.html +13 -13
  11. package/docs/classes/KeetaNetSDK.Referenced.BaseSet.html +1 -1
  12. package/docs/classes/KeetaNetSDK.Referenced.BaseVoteBuilder.html +1 -1
  13. package/docs/classes/KeetaNetSDK.Referenced.Block.html +33 -30
  14. package/docs/classes/KeetaNetSDK.Referenced.BlockBuilder.html +2 -1
  15. package/docs/classes/KeetaNetSDK.Referenced.BlockHash.html +3 -2
  16. package/docs/classes/KeetaNetSDK.Referenced.BlockOperation.html +1 -1
  17. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationCREATE_IDENTIFIER.html +2 -2
  18. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMANAGE_CERTIFICATE.html +2 -2
  19. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationMODIFY_PERMISSIONS.html +2 -2
  20. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationRECEIVE.html +2 -2
  21. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSEND.html +2 -2
  22. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_INFO.html +2 -2
  23. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationSET_REP.html +2 -2
  24. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_MODIFY_BALANCE.html +2 -2
  25. package/docs/classes/KeetaNetSDK.Referenced.BlockOperationTOKEN_ADMIN_SUPPLY.html +2 -2
  26. package/docs/classes/KeetaNetSDK.Referenced.Certificate.html +11 -5
  27. package/docs/classes/KeetaNetSDK.Referenced.CertificateBundle.html +1 -1
  28. package/docs/classes/KeetaNetSDK.Referenced.CertificateHash.html +3 -2
  29. package/docs/classes/KeetaNetSDK.Referenced.ECDSAKeyPair.html +1 -1
  30. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1KeyPair.html +1 -1
  31. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PrivateKey.html +4 -2
  32. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1PublicKey.html +4 -2
  33. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256K1Signature.html +4 -2
  34. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1KeyPair.html +1 -1
  35. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PrivateKey.html +4 -2
  36. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1PublicKey.html +4 -2
  37. package/docs/classes/KeetaNetSDK.Referenced.ECDSASECP256R1Signature.html +4 -2
  38. package/docs/classes/KeetaNetSDK.Referenced.ED25519KeyPair.html +1 -1
  39. package/docs/classes/KeetaNetSDK.Referenced.ED25519PrivateKey.html +4 -2
  40. package/docs/classes/KeetaNetSDK.Referenced.ED25519PublicKey.html +4 -2
  41. package/docs/classes/KeetaNetSDK.Referenced.ED25519Signature.html +4 -2
  42. package/docs/classes/KeetaNetSDK.Referenced.ExternalKeyPair.html +1 -1
  43. package/docs/classes/KeetaNetSDK.Referenced.ExternalSet.html +1 -1
  44. package/docs/classes/KeetaNetSDK.Referenced.IdempotentKey.html +3 -2
  45. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKey.html +4 -2
  46. package/docs/classes/KeetaNetSDK.Referenced.IdentifierKeyPair.html +1 -1
  47. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetError.html +2 -2
  48. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetErrorBase.html +1 -1
  49. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetLedgerError.html +1 -1
  50. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetLedgerIdempotentKeyError.html +1 -1
  51. package/docs/classes/KeetaNetSDK.Referenced.KeetaNetLedgerVoteError.html +1 -1
  52. package/docs/classes/KeetaNetSDK.Referenced.KeyInterface.html +1 -1
  53. package/docs/classes/KeetaNetSDK.Referenced.KeyStorage.html +4 -2
  54. package/docs/classes/KeetaNetSDK.Referenced.Log.html +15 -3
  55. package/docs/classes/KeetaNetSDK.Referenced.LogTargetConsole.html +3 -2
  56. package/docs/classes/KeetaNetSDK.Referenced.Node.html +1 -1
  57. package/docs/classes/KeetaNetSDK.Referenced.P2PSwitch.html +4 -2
  58. package/docs/classes/KeetaNetSDK.Referenced.PendingAccount.html +1 -1
  59. package/docs/classes/KeetaNetSDK.Referenced.PermissionSetHolder.html +1 -1
  60. package/docs/classes/KeetaNetSDK.Referenced.PossiblyExpiredVote.html +2 -2
  61. package/docs/classes/KeetaNetSDK.Referenced.PossiblyUnsignedBlock.html +38 -0
  62. package/docs/classes/KeetaNetSDK.Referenced.SignatureStorage.html +4 -2
  63. package/docs/classes/KeetaNetSDK.Referenced.Stats.html +1 -1
  64. package/docs/classes/KeetaNetSDK.Referenced.StatsPending.html +1 -1
  65. package/docs/classes/KeetaNetSDK.Referenced.UnsignedBlock.html +42 -0
  66. package/docs/classes/KeetaNetSDK.Referenced.UserClientBuilder.html +13 -1
  67. package/docs/classes/KeetaNetSDK.Referenced.Vote.html +2 -2
  68. package/docs/classes/KeetaNetSDK.Referenced.VoteBlockBundle.html +11 -9
  69. package/docs/classes/KeetaNetSDK.Referenced.VoteBlockHash.html +4 -2
  70. package/docs/classes/KeetaNetSDK.Referenced.VoteBuilder.html +1 -1
  71. package/docs/classes/KeetaNetSDK.Referenced.VoteHash.html +4 -2
  72. package/docs/classes/KeetaNetSDK.Referenced.VoteLikeBase.html +2 -2
  73. package/docs/classes/KeetaNetSDK.Referenced.VoteQuote.html +2 -2
  74. package/docs/classes/KeetaNetSDK.Referenced.VoteQuoteBuilder.html +1 -1
  75. package/docs/classes/KeetaNetSDK.Referenced.VoteStaple.html +10 -8
  76. package/docs/classes/KeetaNetSDK.Referenced.VoteStapleHash.html +4 -2
  77. package/docs/classes/KeetaNetSDK.Referenced.src_lib_utils_buffer.BufferStorage.html +4 -2
  78. package/docs/classes/KeetaNetSDK.Referenced.src_lib_utils_certificate.CertificateBuilder.html +4 -2
  79. package/docs/classes/KeetaNetSDK.UserClient.html +19 -11
  80. package/docs/documents/GETTING-STARTED.html +2 -2
  81. package/docs/enums/KeetaNetSDK.Referenced.AdjustMethod.html +4 -4
  82. package/docs/enums/KeetaNetSDK.Referenced.OperationType.html +10 -10
  83. package/docs/functions/KeetaNetSDK.Referenced.src_lib_utils_buffer.DecodeBase32.html +2 -2
  84. package/docs/functions/KeetaNetSDK.Referenced.src_lib_utils_buffer.DecodeBase64URL.html +1 -0
  85. package/docs/functions/KeetaNetSDK.Referenced.src_lib_utils_buffer.EncodeBase64URL.html +1 -0
  86. package/docs/functions/KeetaNetSDK.Referenced.src_lib_utils_conversion.toJSONSerializable.html +1 -1
  87. package/docs/hierarchy.html +1 -1
  88. package/docs/interfaces/KeetaNetSDK.Referenced.ACLEntry.html +1 -1
  89. package/docs/interfaces/KeetaNetSDK.Referenced.ACLUpdate.html +1 -1
  90. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ExplicitContextTag.html +1 -1
  91. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1ImplicitContextTag.html +1 -1
  92. package/docs/interfaces/KeetaNetSDK.Referenced.ASN1Object.html +1 -1
  93. package/docs/interfaces/KeetaNetSDK.Referenced.BaseExternalKeyPairFunctions.html +1 -1
  94. package/docs/interfaces/KeetaNetSDK.Referenced.BaseGenerationConfig.html +1 -1
  95. package/docs/interfaces/KeetaNetSDK.Referenced.BaseIdentifierCreateArguments.html +1 -1
  96. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperation.html +1 -1
  97. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationCREATE_IDENTIFIER.html +2 -2
  98. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATE.html +2 -2
  99. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMODIFY_PERMISSIONS.html +2 -2
  100. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationRECEIVE.html +2 -2
  101. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSEND.html +2 -2
  102. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_INFO.html +2 -2
  103. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationSET_REP.html +2 -2
  104. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_MODIFY_BALANCE.html +2 -2
  105. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationTOKEN_ADMIN_SUPPLY.html +2 -2
  106. package/docs/interfaces/KeetaNetSDK.Referenced.BlockOperationValidateContext.html +2 -2
  107. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV1Canonical.html +1 -1
  108. package/docs/interfaces/KeetaNetSDK.Referenced.BlockV2Canonical.html +1 -1
  109. package/docs/interfaces/KeetaNetSDK.Referenced.Constructor.html +1 -1
  110. package/docs/interfaces/KeetaNetSDK.Referenced.DisposableTimingHandle.html +1 -1
  111. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsNoEncryption.html +1 -1
  112. package/docs/interfaces/KeetaNetSDK.Referenced.ExternalKeyPairFunctionsSupportsEncryption.html +1 -1
  113. package/docs/interfaces/KeetaNetSDK.Referenced.IdentifierCreateRequest.html +3 -2
  114. package/docs/interfaces/KeetaNetSDK.Referenced.InitialConfigSupply.html +1 -1
  115. package/docs/interfaces/KeetaNetSDK.Referenced.InstanceSet.html +1 -1
  116. package/docs/interfaces/KeetaNetSDK.Referenced.KVGenericOptionsType.html +1 -1
  117. package/docs/interfaces/KeetaNetSDK.Referenced.KVSetOptionsType.html +1 -1
  118. package/docs/interfaces/KeetaNetSDK.Referenced.LogTarget.html +3 -2
  119. package/docs/interfaces/KeetaNetSDK.Referenced.ModifyTokenBalanceEntry.html +1 -1
  120. package/docs/interfaces/KeetaNetSDK.Referenced.MultiSigIdentifierCreateArguments.html +1 -1
  121. package/docs/interfaces/KeetaNetSDK.Referenced.MultisigConfig.html +1 -1
  122. package/docs/interfaces/KeetaNetSDK.Referenced.NodeConfig.html +2 -2
  123. package/docs/interfaces/KeetaNetSDK.Referenced.NumericValueEntry.html +1 -1
  124. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerBase.html +1 -1
  125. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerListener.html +1 -1
  126. package/docs/interfaces/KeetaNetSDK.Referenced.P2PPeerRepBase.html +1 -1
  127. package/docs/interfaces/KeetaNetSDK.Referenced.PendingOperations.html +2 -2
  128. package/docs/interfaces/KeetaNetSDK.Referenced.PendingOperationsJSON.html +2 -2
  129. package/docs/interfaces/KeetaNetSDK.Referenced.PublicKeyStorage.html +3 -2
  130. package/docs/interfaces/KeetaNetSDK.Referenced.PublishOptions.html +1 -1
  131. package/docs/interfaces/KeetaNetSDK.Referenced.RequestTokenReceiveEntry.html +1 -1
  132. package/docs/interfaces/KeetaNetSDK.Referenced.TokenNumericEntry.html +1 -1
  133. package/docs/interfaces/KeetaNetSDK.Referenced.UserClientConfig.html +1 -1
  134. package/docs/interfaces/KeetaNetSDK.Referenced.UserClientOptions.html +1 -1
  135. package/docs/interfaces/KeetaNetSDK.Referenced.VoteBundleConstructor.html +2 -2
  136. package/docs/interfaces/KeetaNetSDK.Referenced.VoteStapleJSON.html +2 -2
  137. package/docs/interfaces/KeetaNetSDK.Referenced.WithIsInstance.html +1 -1
  138. package/docs/interfaces/KeetaNetSDK.Referenced.src_config.ValidationConfig.html +2 -2
  139. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1BitString.html +1 -1
  140. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Date.html +1 -1
  141. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1OID.html +1 -1
  142. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Set.html +1 -1
  143. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1String.html +1 -1
  144. package/docs/interfaces/KeetaNetSDK.Referenced.src_lib_utils_asn1.ASN1Struct.html +1 -1
  145. package/docs/modules/KeetaNetSDK.Referenced.html +1 -1
  146. package/docs/modules/KeetaNetSDK.Referenced.src_lib_utils_buffer.html +1 -1
  147. package/docs/modules/KeetaNetSDK.Referenced.src_lib_utils_certificate.html +1 -1
  148. package/docs/types/KeetaNetSDK.Referenced.BlockJSONOptionalSigned.html +1 -0
  149. package/docs/types/KeetaNetSDK.Referenced.BlockV1JSONOptionalSigned.html +1 -0
  150. package/docs/types/KeetaNetSDK.Referenced.BlockV2JSONOptionalSigned.html +1 -0
  151. package/docs/types/KeetaNetSDK.Referenced.CertificateUpdate.html +1 -1
  152. package/docs/types/KeetaNetSDK.Referenced.IsTuple.html +1 -0
  153. package/docs/types/KeetaNetSDK.Referenced.JSONDepthLimit.html +1 -0
  154. package/docs/types/KeetaNetSDK.Referenced.KeyUsage.html +1 -0
  155. package/docs/types/KeetaNetSDK.Referenced.KeyUsageBits.html +1 -0
  156. package/docs/types/KeetaNetSDK.Referenced.LogTargetConsoleConfig.html +3 -2
  157. package/docs/types/KeetaNetSDK.Referenced.MultisigSignerFieldJSON.html +1 -1
  158. package/docs/types/KeetaNetSDK.Referenced.VoteOptions.html +7 -3
  159. package/docs/types/KeetaNetSDK.Referenced.VoteStapleInputs.html +2 -0
  160. package/docs/types/KeetaNetSDK.Referenced.VoteStapleOptions.html +9 -0
  161. package/docs/types/KeetaNetSDK.Referenced.src_config.NetworkConfig.html +1 -1
  162. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_certificate.CertificateBundleJSONOutput.html +1 -0
  163. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_certificate.CertificateJSONOutput.html +1 -1
  164. package/docs/types/KeetaNetSDK.Referenced.src_lib_utils_conversion.ToJSONSerializable.html +1 -1
  165. package/docs/variables/KeetaNetSDK.Referenced.BlockOperationASN1Schema.html +2 -2
  166. package/docs/variables/KeetaNetSDK.Referenced.allFullErrorCodes.html +1 -1
  167. package/docs/variables/KeetaNetSDK.Referenced.keyUsageBits.html +1 -0
  168. package/lib/block/index.d.ts +341 -46
  169. package/lib/block/operations.d.ts +14 -21
  170. package/lib/error/block.d.ts +2 -2
  171. package/lib/error/index.d.ts +1 -1
  172. package/lib/ledger/common.d.ts +3 -0
  173. package/lib/ledger/db_spanner_helper.d.ts +1 -1
  174. package/lib/log/common.d.ts +3 -0
  175. package/lib/log/index.d.ts +20 -0
  176. package/lib/log/internal.d.ts +22 -0
  177. package/lib/log/target_console.d.ts +6 -0
  178. package/lib/log/target_gcp.d.ts +6 -0
  179. package/lib/log/target_gcp.js +259 -77
  180. package/lib/log/target_https.d.ts +28 -0
  181. package/lib/log/target_https.js +6055 -0
  182. package/lib/p2p.d.ts +6 -2
  183. package/lib/utils/buffer.d.ts +8 -2
  184. package/lib/utils/certificate.d.ts +41 -25
  185. package/lib/utils/conversion.d.ts +8 -4
  186. package/lib/utils/external-keys/passkey-prf.d.ts +156 -0
  187. package/lib/utils/external-keys/passkey-prf.js +391 -0
  188. package/lib/vote.d.ts +230 -35
  189. package/npm-shrinkwrap.json +2 -2
  190. package/package.json +1 -1
  191. package/version.d.ts +1 -1
  192. package/docs/interfaces/KeetaNetSDK.Referenced.BlockJSONOperationMANAGE_CERTIFICATESerializable.html +0 -5
  193. package/docs/types/KeetaNetSDK.Referenced.ExportedJSONOperation.html +0 -1
  194. package/docs/types/KeetaNetSDK.Referenced.MultisigSignerField.html +0 -1
package/client/index.js CHANGED
@@ -57280,6 +57280,7 @@ const permissions_1 = __webpack_require__(5860);
57280
57280
  const conversion_1 = __webpack_require__(2360);
57281
57281
  const helper_1 = __webpack_require__(3208);
57282
57282
  const certificate_1 = __webpack_require__(5661);
57283
+ const never_1 = __webpack_require__(8692);
57283
57284
  class PendingAccount {
57284
57285
  constructor() {
57285
57286
  _PendingAccount_account.set(this, void 0);
@@ -57303,7 +57304,7 @@ class PendingAccount {
57303
57304
  return (__classPrivateFieldGet(this, _PendingAccount_account, "f"));
57304
57305
  }
57305
57306
  toJSON() {
57306
- return (this.account);
57307
+ return (this.account.publicKeyString.get());
57307
57308
  }
57308
57309
  }
57309
57310
  exports.PendingAccount = PendingAccount;
@@ -57362,8 +57363,29 @@ class UserClientBuilder {
57362
57363
  pendingOperations.tokenSupply = (0, conversion_1.parseHexBigIntString)(operations.tokenSupply);
57363
57364
  }
57364
57365
  if (operations.createIdentifiers !== undefined) {
57365
- pendingOperations.createIdentifiers = operations.createIdentifiers.map(function ({ type }) {
57366
- return ({ type });
57366
+ pendingOperations.createIdentifiers = operations.createIdentifiers.map(function ({ type, createArguments }) {
57367
+ let createArgumentsParsed;
57368
+ if (createArguments !== undefined) {
57369
+ if (createArguments.type === account_1.AccountKeyAlgorithm.MULTISIG) {
57370
+ createArgumentsParsed = {
57371
+ type: account_1.AccountKeyAlgorithm.MULTISIG,
57372
+ quorum: BigInt(createArguments.quorum),
57373
+ signers: createArguments.signers.map(signer => {
57374
+ const parsed = account_1.Account.toAccount(signer);
57375
+ if (parsed.isAccount() || parsed.isMultisig()) {
57376
+ return (parsed);
57377
+ }
57378
+ else {
57379
+ throw (new Error('Multisig signer must be an account or multisig identifier'));
57380
+ }
57381
+ })
57382
+ };
57383
+ }
57384
+ else {
57385
+ (0, never_1.assertNever)(createArguments.type);
57386
+ }
57387
+ }
57388
+ return ({ type, createArguments: createArgumentsParsed });
57367
57389
  });
57368
57390
  }
57369
57391
  if (operations.send !== undefined) {
@@ -57615,14 +57637,15 @@ class UserClientBuilder {
57615
57637
  if (!previous) {
57616
57638
  previous = await renderOptions.getPrevious(account) ?? block_1.Block.NO_PREVIOUS;
57617
57639
  }
57618
- for (const { type, toResolve } of (pending.createIdentifiers ?? [])) {
57640
+ for (const { type, toResolve, createArguments } of (pending.createIdentifiers ?? [])) {
57619
57641
  const createdAddress = account.generateIdentifier(type, previous, operations.length);
57620
57642
  if (PendingAccount.IsInstance(toResolve)) {
57621
57643
  toResolve.account = createdAddress;
57622
57644
  }
57623
57645
  operations.push({
57624
57646
  type: block_1.Block.OperationType.CREATE_IDENTIFIER,
57625
- identifier: createdAddress
57647
+ identifier: createdAddress,
57648
+ createArguments: createArguments
57626
57649
  });
57627
57650
  }
57628
57651
  const allSends = {};
@@ -57864,13 +57887,22 @@ class UserClientBuilder {
57864
57887
  __classPrivateFieldGet(this, _UserClientBuilder_instances, "m", _UserClientBuilder_useOptions).call(this, options);
57865
57888
  __classPrivateFieldGet(this, _UserClientBuilder_pendingOperations, "f").setRep = to;
57866
57889
  }
57867
- generateIdentifier(type, options = {}) {
57890
+ generateIdentifier(toCreate, options = {}) {
57868
57891
  __classPrivateFieldGet(this, _UserClientBuilder_instances, "m", _UserClientBuilder_useOptions).call(this, options);
57892
+ let createType;
57893
+ let createArguments;
57894
+ if (typeof toCreate === 'number') {
57895
+ createType = toCreate;
57896
+ }
57897
+ else {
57898
+ createArguments = toCreate;
57899
+ createType = toCreate.type;
57900
+ }
57869
57901
  if (!__classPrivateFieldGet(this, _UserClientBuilder_pendingOperations, "f").createIdentifiers) {
57870
57902
  __classPrivateFieldGet(this, _UserClientBuilder_pendingOperations, "f").createIdentifiers = [];
57871
57903
  }
57872
57904
  const toResolve = new PendingAccount();
57873
- __classPrivateFieldGet(this, _UserClientBuilder_pendingOperations, "f").createIdentifiers.push({ type, toResolve });
57905
+ __classPrivateFieldGet(this, _UserClientBuilder_pendingOperations, "f").createIdentifiers.push({ type: createType, toResolve, createArguments });
57874
57906
  return (toResolve);
57875
57907
  }
57876
57908
  get blocks() {
@@ -58806,11 +58838,12 @@ class Client {
58806
58838
  * @param account The account to get the history for -- if null then the history for all accounts will be returned
58807
58839
  * @param options The options to use for the request
58808
58840
  * @param options.startBlocksHash The block hash to start from -- this is used to paginate the request
58809
- * @param options.depth The maximum number of vote staples to return -- this is used to limit the number of vote staples returned
58841
+ * @param options.depth The maximum number of vote staples to return -- this is used to limit the number of vote staples returned, default is everything)
58842
+ * @param options.pageSize How large of a page size to request at a given time (default is 200)
58810
58843
  * @return The history of vote staples for the given account, in reverse order starting with the most recent vote staple
58811
58844
  */
58812
58845
  async getHistory(account, options = {}) {
58813
- const { depth = Infinity, startBlocksHash } = options;
58846
+ const { depth = Infinity, pageSize = 200, startBlocksHash } = options;
58814
58847
  account = account_1.default.toPublicKeyString(account);
58815
58848
  let startVoteStapleID = undefined;
58816
58849
  if (startBlocksHash !== undefined) {
@@ -58823,7 +58856,7 @@ class Client {
58823
58856
  }
58824
58857
  const retval = [];
58825
58858
  while (retval.length < depth) {
58826
- const limit = Math.min(depth - retval.length, 200);
58859
+ const limit = Math.min(depth - retval.length, pageSize);
58827
58860
  const query = {
58828
58861
  limit: String(limit)
58829
58862
  };
@@ -58861,7 +58894,16 @@ class Client {
58861
58894
  break;
58862
58895
  }
58863
58896
  }
58864
- startVoteStapleID = history.history.slice(-1)[0]['$id'];
58897
+ if (typeof history.nextKey === 'string' || history.nextKey === null) {
58898
+ if (history.nextKey === null) {
58899
+ break;
58900
+ }
58901
+ startVoteStapleID = history.nextKey;
58902
+ }
58903
+ else {
58904
+ /* @deprecated -- workaround broken API */
58905
+ startVoteStapleID = history.history.slice(-1)[0]['$id'];
58906
+ }
58865
58907
  }
58866
58908
  return (retval);
58867
58909
  }
@@ -60433,16 +60475,9 @@ class UserClient {
60433
60475
  async getQuotes(blocks) {
60434
60476
  return (await __classPrivateFieldGet(this, _UserClient_client, "f").getVoteQuotes(blocks));
60435
60477
  }
60436
- /**
60437
- * Generate a new identifier for the given type and publish the blocks
60438
- *
60439
- * @param type The type of identifier to generate
60440
- * @param options The options to use for the request
60441
- * @return The identifier that was generated
60442
- */
60443
- async generateIdentifier(type, options = {}) {
60478
+ async generateIdentifier(toCreate, options = {}) {
60444
60479
  const builder = this.initBuilder(options);
60445
- const generated = builder.generateIdentifier(type);
60480
+ const generated = builder.generateIdentifier(toCreate);
60446
60481
  await this.publishBuilder(builder);
60447
60482
  return (generated);
60448
60483
  }
@@ -61090,10 +61125,13 @@ exports.baseValidationConfig = {
61090
61125
  maxLength: 256,
61091
61126
  regex: /^[-_A-Za-z0-9+/= ]+$/,
61092
61127
  canBeEmpty: true
61128
+ },
61129
+ validateNumericValues: {
61130
+ cutoffEpoch: 1763683200000n // 2025-11-21T00:00:00.000Z
61093
61131
  }
61094
61132
  },
61095
61133
  idempotentKey: {
61096
- maxByteLength: 32
61134
+ maxByteLength: 36
61097
61135
  }
61098
61136
  };
61099
61137
  function getNetworkAlias(networkOrID) {
@@ -62836,23 +62874,23 @@ var __importStar = (this && this.__importStar) || function (mod) {
62836
62874
  __setModuleDefault(result, mod);
62837
62875
  return result;
62838
62876
  };
62839
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
62840
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
62841
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
62842
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
62843
- };
62844
62877
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
62845
62878
  if (kind === "m") throw new TypeError("Private method is not writable");
62846
62879
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
62847
62880
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
62848
62881
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
62849
62882
  };
62883
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
62884
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
62885
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
62886
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
62887
+ };
62850
62888
  var __importDefault = (this && this.__importDefault) || function (mod) {
62851
62889
  return (mod && mod.__esModule) ? mod : { "default": mod };
62852
62890
  };
62853
- var _Block_instances, _a, _Block_valueBytes, _Block_valueHash, _Block_getSortedRequiredSigners, _Block_validateBytes, _Block_validateOperationsPurpose, _Block_validateSignerField, _Block_validateSignatures, _BlockBuilder_block;
62891
+ var _PossiblyUnsignedBlock_instances, _a, _PossiblyUnsignedBlock_valueBytes, _PossiblyUnsignedBlock_valueHash, _PossiblyUnsignedBlock_hasSignature, _PossiblyUnsignedBlock_nonNullableSignatures_get, _PossiblyUnsignedBlock_validateRecalculatedBytes, _PossiblyUnsignedBlock_validateOperationsPurpose, _PossiblyUnsignedBlock_validateSignerField, _PossiblyUnsignedBlock_validateSignatures, _PossiblyUnsignedBlock_validateIdempotent, _PossiblyUnsignedBlock_toBytesInternal, _b, _BlockBuilder_block, _BlockBuilder_ValidateInputs;
62854
62892
  Object.defineProperty(exports, "__esModule", ({ value: true }));
62855
- exports.BlockBuilder = exports.Block = exports.BlockHash = exports.AdjustMethod = exports.BlockPurpose = void 0;
62893
+ exports.BlockBuilder = exports.Block = exports.UnsignedBlock = exports.BlockHash = exports.AdjustMethod = exports.BlockPurpose = void 0;
62856
62894
  exports.toAdjustMethod = toAdjustMethod;
62857
62895
  const account_1 = __importStar(__webpack_require__(9415));
62858
62896
  const buffer_1 = __webpack_require__(3310);
@@ -62860,6 +62898,7 @@ const hash_1 = __webpack_require__(7908);
62860
62898
  const ASN1 = __importStar(__webpack_require__(6045));
62861
62899
  const helper_1 = __webpack_require__(3208);
62862
62900
  const util_1 = __webpack_require__(9023);
62901
+ const conversion_1 = __webpack_require__(2360);
62863
62902
  const Operations = __importStar(__webpack_require__(2778));
62864
62903
  const block_1 = __importDefault(__webpack_require__(7412));
62865
62904
  const common_1 = __webpack_require__(5663);
@@ -63102,6 +63141,12 @@ function _ignore_static_checks() {
63102
63141
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
63103
63142
  const _ignore_check_blockasn1v2_reverse_2 = _ignore_check_blockasn1v2_reverse_1;
63104
63143
  }
63144
+ function validateIdempotentKeyLength(idempotent, network) {
63145
+ const idempotentValidationConfig = (0, config_1.getValidation)(network).idempotentKey;
63146
+ if (idempotent.length > idempotentValidationConfig.maxByteLength) {
63147
+ throw (new block_1.default('BLOCK_INVALID_IDEMPOTENT_LENGTH', `Block idempotent key is length ${idempotent.length}, but maxByteLength is ${idempotentValidationConfig.maxByteLength}`));
63148
+ }
63149
+ }
63105
63150
  function parseBlockIdempotent(input, network) {
63106
63151
  let output;
63107
63152
  if (Buffer.isBuffer(input)) {
@@ -63119,10 +63164,7 @@ function parseBlockIdempotent(input, network) {
63119
63164
  throw (new block_1.default('BLOCK_INVALID_IDEMPOTENT_FORMAT', 'Could not parse Block idempotent'));
63120
63165
  }
63121
63166
  if (network !== undefined) {
63122
- const idempotentValidationConfig = (0, config_1.getValidation)(network).idempotentKey;
63123
- if (output.length > idempotentValidationConfig.maxByteLength) {
63124
- throw (new block_1.default('BLOCK_INVALID_IDEMPOTENT_LENGTH', `Block idempotent key is length ${output.length}, but maxByteLength is ${idempotentValidationConfig.maxByteLength}`));
63125
- }
63167
+ validateIdempotentKeyLength(output, network);
63126
63168
  }
63127
63169
  return (output);
63128
63170
  }
@@ -63272,11 +63314,22 @@ function assertBlockSignatureField(input) {
63272
63314
  throw (new Error('Input must include 1+ signatures'));
63273
63315
  }
63274
63316
  }
63317
+ function getBlockSignatureFieldFromVersion(version) {
63318
+ if (version === 1) {
63319
+ return ('signature');
63320
+ }
63321
+ else if (version === 2) {
63322
+ return ('signatures');
63323
+ }
63324
+ else {
63325
+ throw (new Error(`Unsupported block version for signature field: ${version}`));
63326
+ }
63327
+ }
63275
63328
  /**
63276
63329
  * Block: An item which contains a number of operations (transactions) which
63277
63330
  * originated from an account at a particular instant
63278
63331
  */
63279
- class Block {
63332
+ class PossiblyUnsignedBlock {
63280
63333
  get principal() {
63281
63334
  if (Array.isArray(this.signer)) {
63282
63335
  return (this.signer[0]);
@@ -63285,53 +63338,44 @@ class Block {
63285
63338
  return (this.signer);
63286
63339
  }
63287
63340
  }
63288
- static async fromUnsignedJSON(input) {
63289
- const inputCheck = input;
63290
- if (typeof inputCheck === 'object' && inputCheck !== null) {
63291
- if ('signature' in inputCheck || 'signatures' in inputCheck) {
63292
- throw (new Error('fromUnsignedJSON() was called when a signature(s) already exists'));
63341
+ static getSortedRequiredSigners(input) {
63342
+ const queue = [input];
63343
+ const visited = new account_1.default.Set();
63344
+ const out = [];
63345
+ while (queue.length > 0) {
63346
+ // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
63347
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
63348
+ const cur = queue.shift();
63349
+ if (account_1.default.isInstance(cur)) {
63350
+ if (visited.has(cur)) {
63351
+ continue;
63352
+ }
63353
+ visited.add(cur);
63354
+ out.push(cur);
63355
+ }
63356
+ else {
63357
+ queue.unshift(...cur[1]);
63293
63358
  }
63294
63359
  }
63295
- const container = this.getASN1ContainerWithoutSignature(input);
63296
- // We have to ignore the type here because the ASN1.JStoASN1 function does not handle recursive types well
63297
- // @ts-ignore
63298
- const bytes = ASN1.JStoASN1(container).toBER(false);
63299
- const hash = new BlockHash((0, hash_1.Hash)(Buffer.from(bytes)));
63300
- const signers = __classPrivateFieldGet(this, _a, "m", _Block_getSortedRequiredSigners).call(this, input.signer);
63301
- const signatures = await Promise.all(signers.map(async function (signer) {
63302
- const signature = await signer.sign(hash.getBuffer());
63303
- return (signature.getBuffer());
63304
- }));
63305
- let blockInput;
63306
- if (input.version === 1) {
63307
- blockInput = { ...input, signature: signatures[0] };
63308
- }
63309
- else {
63310
- blockInput = { ...input, signatures };
63311
- }
63312
- return (new _a(blockInput));
63360
+ return (out);
63313
63361
  }
63314
- static isValidJSON(block, version) {
63362
+ static isValidJSONSignedOrUnsigned(assertSignatureIncluded, block, version) {
63315
63363
  if (!block || typeof block !== 'object' || Array.isArray(block)) {
63316
63364
  return (false);
63317
63365
  }
63318
- if (!('version' in block)) {
63366
+ if (!('version' in block) || typeof block.version !== 'number') {
63319
63367
  return (false);
63320
63368
  }
63321
63369
  if (version !== undefined && block.version !== version) {
63322
63370
  return (false);
63323
63371
  }
63324
63372
  const checkFields = ['date', 'previous', 'network', 'network', 'account', 'signer', 'operations'];
63325
- if (block.version === 1) {
63326
- checkFields.push('signature');
63373
+ if (assertSignatureIncluded) {
63374
+ checkFields.push(getBlockSignatureFieldFromVersion(block.version));
63327
63375
  }
63328
- else if (block.version === 2) {
63329
- checkFields.push('signatures');
63376
+ if (block.version === 2) {
63330
63377
  checkFields.push('purpose');
63331
63378
  }
63332
- else {
63333
- return (false);
63334
- }
63335
63379
  for (const checkField of checkFields) {
63336
63380
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63337
63381
  if (!(checkField in block) || block[checkField] === undefined) {
@@ -63340,10 +63384,11 @@ class Block {
63340
63384
  }
63341
63385
  return (true);
63342
63386
  }
63343
- constructor(input) {
63344
- _Block_instances.add(this);
63345
- _Block_valueBytes.set(this, void 0);
63346
- _Block_valueHash.set(this, void 0);
63387
+ constructor(input, hasSignature) {
63388
+ _PossiblyUnsignedBlock_instances.add(this);
63389
+ _PossiblyUnsignedBlock_valueBytes.set(this, void 0);
63390
+ _PossiblyUnsignedBlock_valueHash.set(this, void 0);
63391
+ _PossiblyUnsignedBlock_hasSignature.set(this, void 0);
63347
63392
  // Extra attributes
63348
63393
  this.$opening = false;
63349
63394
  if (typeof input === 'string') {
@@ -63352,7 +63397,10 @@ class Block {
63352
63397
  if ((0, helper_1.isBuffer)(input)) {
63353
63398
  input = (0, helper_1.bufferToArrayBuffer)(input);
63354
63399
  }
63400
+ let foundSignatureField;
63355
63401
  if (util_1.types.isArrayBuffer(input)) {
63402
+ // For some reason, typescript says this is excessively deep
63403
+ // @ts-ignore
63356
63404
  const data = new ASN1.BufferStorageASN1(input, BlockASN1Schema).getASN1();
63357
63405
  if (Array.isArray(data)) {
63358
63406
  if (data[0] !== 0n) {
@@ -63379,7 +63427,13 @@ class Block {
63379
63427
  const prevHashBuf = data[7];
63380
63428
  this.previous = new BlockHash(prevHashBuf);
63381
63429
  this.operations = Operations.ImportOperationsASN1(data[8], this.network);
63382
- this.signatures = [data[9]];
63430
+ if (data[9]) {
63431
+ // @ts-ignore
63432
+ foundSignatureField = [data[9]];
63433
+ }
63434
+ else {
63435
+ foundSignatureField = null;
63436
+ }
63383
63437
  }
63384
63438
  else if (data.value === 1) {
63385
63439
  this.version = 2;
@@ -63406,24 +63460,31 @@ class Block {
63406
63460
  this.previous = new BlockHash(container[7]);
63407
63461
  this.operations = Operations.ImportOperationsASN1(container[8], this.network);
63408
63462
  const signatureContainer = container[9];
63409
- if (Buffer.isBuffer(signatureContainer)) {
63410
- this.signatures = [signatureContainer];
63463
+ if (signatureContainer) {
63464
+ if (Buffer.isBuffer(signatureContainer)) {
63465
+ foundSignatureField = [signatureContainer];
63466
+ }
63467
+ else {
63468
+ if (signatureContainer.length <= 1) {
63469
+ throw (new Error('Signature field invalid, must be greater than one when using sequence of'));
63470
+ }
63471
+ assertBlockSignatureField(signatureContainer);
63472
+ foundSignatureField = signatureContainer;
63473
+ }
63411
63474
  }
63412
63475
  else {
63413
- if (signatureContainer.length <= 1) {
63414
- throw (new Error('Signature field invalid, must be greater than one when using sequence of'));
63415
- }
63416
- assertBlockSignatureField(signatureContainer);
63417
- this.signatures = signatureContainer;
63476
+ foundSignatureField = null;
63418
63477
  }
63419
63478
  }
63420
63479
  else {
63421
63480
  throw (new Error('Unknown block version'));
63422
63481
  }
63423
- __classPrivateFieldSet(this, _Block_valueBytes, input, "f");
63482
+ __classPrivateFieldSet(this, _PossiblyUnsignedBlock_valueBytes, input, "f");
63424
63483
  }
63425
63484
  else {
63426
- if (_a.isInstance(input)) {
63485
+ // These will be loaded even though they are defined later in the file because the constructor does not get automatically called before their definitions
63486
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
63487
+ if (Block.isInstance(input) || UnsignedBlock.isInstance(input)) {
63427
63488
  this.version = input.version;
63428
63489
  this.purpose = input.purpose;
63429
63490
  this.idempotent = input.idempotent;
@@ -63434,9 +63495,9 @@ class Block {
63434
63495
  this.account = input.account;
63435
63496
  this.operations = input.operations;
63436
63497
  this.signer = input.signer;
63437
- this.signatures = input.signatures;
63498
+ foundSignatureField = input.signatures;
63438
63499
  }
63439
- else if (_a.isValidJSON(input, 1)) {
63500
+ else if (_a.isValidJSONSignedOrUnsigned(hasSignature, input, 1)) {
63440
63501
  /*
63441
63502
  * Map input to our values
63442
63503
  */
@@ -63456,19 +63517,24 @@ class Block {
63456
63517
  * sign the hash of the block based on what has been
63457
63518
  * processed
63458
63519
  */
63459
- if (input.signature === undefined) {
63460
- throw (new Error('Cannot construct block without a signature and explicit direction to sign'));
63461
- }
63462
- let signature;
63463
- if (typeof input.signature === 'string') {
63464
- signature = Buffer.from(input.signature, 'hex');
63520
+ if ('signature' in input && input.signature) {
63521
+ let signature;
63522
+ if (typeof input.signature === 'string') {
63523
+ signature = Buffer.from(input.signature, 'hex');
63524
+ }
63525
+ else if (Buffer.isBuffer(input.signature)) {
63526
+ signature = Buffer.from(input.signature);
63527
+ }
63528
+ else {
63529
+ throw (new Error('Invalid signature format in input'));
63530
+ }
63531
+ foundSignatureField = [signature];
63465
63532
  }
63466
63533
  else {
63467
- signature = Buffer.from(input.signature);
63534
+ foundSignatureField = null;
63468
63535
  }
63469
- this.signatures = [signature];
63470
63536
  }
63471
- else if (_a.isValidJSON(input, 2)) {
63537
+ else if (_a.isValidJSONSignedOrUnsigned(hasSignature, input, 2)) {
63472
63538
  /*
63473
63539
  * Map input to our values
63474
63540
  */
@@ -63488,25 +63554,34 @@ class Block {
63488
63554
  * sign the hash of the block based on what has been
63489
63555
  * processed
63490
63556
  */
63491
- if (input.signatures === undefined) {
63492
- throw (new Error('Cannot construct block without a signature and explicit direction to sign'));
63557
+ if ('signatures' in input && input.signatures) {
63558
+ const signatures = input.signatures.map(function (signature) {
63559
+ if (typeof signature === 'string') {
63560
+ return (Buffer.from(signature, 'hex'));
63561
+ }
63562
+ else {
63563
+ return (Buffer.from(signature));
63564
+ }
63565
+ });
63566
+ assertBlockSignatureField(signatures);
63567
+ foundSignatureField = signatures;
63568
+ }
63569
+ else {
63570
+ foundSignatureField = null;
63493
63571
  }
63494
- const signatures = input.signatures.map(function (signature) {
63495
- if (typeof signature === 'string') {
63496
- return (Buffer.from(signature, 'hex'));
63497
- }
63498
- else {
63499
- return (Buffer.from(signature));
63500
- }
63501
- });
63502
- assertBlockSignatureField(signatures);
63503
- this.signatures = signatures;
63504
63572
  }
63505
63573
  else {
63506
63574
  throw (new Error('Cannot construct block, it is not a valid Block JSON object'));
63507
63575
  }
63508
63576
  /* XXX:TODO: Verify that no extra keys were passed in */
63509
63577
  }
63578
+ if ((foundSignatureField === null) === hasSignature) {
63579
+ throw (new Error('Block signature presence does not match expected hasSignature value'));
63580
+ }
63581
+ // We can assume that the foundSignatureField is of the correct type here since we have verified the hasSignature condition
63582
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63583
+ this.signatures = foundSignatureField;
63584
+ __classPrivateFieldSet(this, _PossiblyUnsignedBlock_hasSignature, hasSignature, "f");
63510
63585
  if (this.previous.compareHexString(this.hash)) {
63511
63586
  throw (new block_1.default('BLOCK_PREVIOUS_SELF', 'internal error: Block references itself'));
63512
63587
  }
@@ -63529,84 +63604,25 @@ class Block {
63529
63604
  if (this.account.isMultisig()) {
63530
63605
  throw (new block_1.default('BLOCK_NO_MULTISIG_OP', 'Cannot create a block for a multisig account'));
63531
63606
  }
63532
- __classPrivateFieldGet(this, _Block_instances, "m", _Block_validateBytes).call(this);
63533
- __classPrivateFieldGet(this, _Block_instances, "m", _Block_validateSignerField).call(this);
63534
- __classPrivateFieldGet(this, _Block_instances, "m", _Block_validateOperationsPurpose).call(this);
63535
- __classPrivateFieldGet(this, _Block_instances, "m", _Block_validateSignatures).call(this);
63607
+ __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_validateSignerField).call(this);
63608
+ __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_validateOperationsPurpose).call(this);
63609
+ __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_validateIdempotent).call(this);
63610
+ __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_validateRecalculatedBytes).call(this);
63611
+ if (hasSignature) {
63612
+ __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_validateSignatures).call(this);
63613
+ }
63536
63614
  }
63537
63615
  static getAccountOpeningHash(account) {
63538
63616
  return (BlockHash.getAccountOpeningHash(account));
63539
63617
  }
63540
- toBytes(includeSignatures = true, useCached = true) {
63541
- if (useCached) {
63542
- if (__classPrivateFieldGet(this, _Block_valueBytes, "f") !== undefined && includeSignatures) {
63543
- return (__classPrivateFieldGet(this, _Block_valueBytes, "f"));
63544
- }
63618
+ toBytes(includeSignatures) {
63619
+ if (includeSignatures === undefined) {
63620
+ includeSignatures = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f");
63545
63621
  }
63546
- const sharedBlockValues = {
63547
- previous: this.previous,
63548
- operations: this.operations,
63549
- account: this.account,
63550
- network: this.network,
63551
- subnet: this.subnet,
63552
- date: this.date,
63553
- idempotent: this.idempotent
63554
- };
63555
- let container;
63556
- if (this.version === 1) {
63557
- if (Array.isArray(this.signer) || this.signatures.length !== 1) {
63558
- throw (new Error('Block v1 only supports single signer'));
63559
- }
63560
- container = _a.getV1ASN1ContainerWithoutSignature({
63561
- ...sharedBlockValues,
63562
- version: 1,
63563
- signer: this.signer
63564
- });
63565
- if (includeSignatures) {
63566
- container.push(this.signatures[0]);
63567
- }
63622
+ else if (includeSignatures !== __classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f")) {
63623
+ throw (new block_1.default('BLOCK_SIGNATURE_PARAMETER_DIFFERS', 'Can only include signatures in toBytes if block has signatures, and vice versa'));
63568
63624
  }
63569
- else {
63570
- const versionTag = this.version - 1;
63571
- if (versionTag !== 1) {
63572
- // We only support version 2
63573
- throw (new block_1.default('BLOCK_INVALID_VERSION', 'We only support version 1/2 blocks'));
63574
- }
63575
- const v2Container = _a.getV2ASN1ContainerWithoutSignature({
63576
- ...sharedBlockValues,
63577
- purpose: this.purpose,
63578
- version: this.version,
63579
- signer: this.signer
63580
- });
63581
- const baseContextTag = {
63582
- type: 'context',
63583
- kind: 'explicit',
63584
- value: versionTag
63585
- };
63586
- if (includeSignatures) {
63587
- let signatureContainer;
63588
- if (this.signatures.length > 1) {
63589
- signatureContainer = this.signatures;
63590
- }
63591
- else if (this.signatures.length === 1) {
63592
- signatureContainer = this.signatures[0];
63593
- }
63594
- else {
63595
- throw (new Error('Block has not been signed'));
63596
- }
63597
- container = { ...baseContextTag, contains: [...v2Container, signatureContainer] };
63598
- }
63599
- else {
63600
- container = { ...baseContextTag, contains: v2Container };
63601
- }
63602
- }
63603
- // We know the container is valid because of the container type, but the ASN1.JStoASN1 function does not handle recursive types well
63604
- // @ts-ignore
63605
- const retval = ASN1.JStoASN1(container).toBER(false);
63606
- if (includeSignatures) {
63607
- __classPrivateFieldSet(this, _Block_valueBytes, retval, "f");
63608
- }
63609
- return (retval);
63625
+ return (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_toBytesInternal).call(this, includeSignatures));
63610
63626
  }
63611
63627
  static getV1ASN1ContainerWithoutSignature(input) {
63612
63628
  let outputAccount;
@@ -63678,32 +63694,32 @@ class Block {
63678
63694
  if (options?.addBinary) {
63679
63695
  additionalFields['$binary'] = Buffer.from(this.toBytes()).toString('base64');
63680
63696
  }
63681
- const signatures = this.signatures.map(function (signature) {
63682
- return (signature.toString('hex').toUpperCase());
63683
- });
63684
- if (this.version === 1) {
63685
- additionalFields.signature = signatures[0];
63686
- }
63687
- else {
63688
- additionalFields.signatures = signatures;
63697
+ if (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f")) {
63698
+ const signatures = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get).map(function (signature) {
63699
+ return (signature.toString('hex').toUpperCase());
63700
+ });
63701
+ if (this.version === 1) {
63702
+ additionalFields.signature = signatures[0];
63703
+ }
63704
+ else {
63705
+ additionalFields.signatures = signatures;
63706
+ }
63689
63707
  }
63690
- return ({
63708
+ return ((0, conversion_1.toJSONSerializable)({
63691
63709
  version: this.version,
63692
63710
  idempotent: this.idempotent?.toString('base64'),
63693
63711
  date: this.date,
63694
63712
  previous: this.previous,
63695
63713
  account: this.account,
63696
63714
  purpose: this.purpose,
63697
- // XXX:TODO We need to use a type assertion here because toJSONSerializable does not support recursive types
63698
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63699
63715
  signer: this.signer,
63700
63716
  network: this.network,
63701
63717
  subnet: this.subnet,
63702
- operations: Operations.ExportOperationsJSON(this.operations),
63718
+ operations: this.operations,
63703
63719
  $hash: this.hash,
63704
63720
  $opening: this.$opening,
63705
63721
  ...additionalFields
63706
- });
63722
+ }));
63707
63723
  }
63708
63724
  /**
63709
63725
  * Hash of the block minus the signature
@@ -63714,48 +63730,32 @@ class Block {
63714
63730
  * signature (which isn't signed)
63715
63731
  */
63716
63732
  get hash() {
63717
- if (__classPrivateFieldGet(this, _Block_valueHash, "f") !== undefined) {
63718
- return (__classPrivateFieldGet(this, _Block_valueHash, "f"));
63733
+ if (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_valueHash, "f") !== undefined) {
63734
+ return (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_valueHash, "f"));
63719
63735
  }
63720
- const retval = new BlockHash((0, hash_1.Hash)(Buffer.from(this.toBytes(false))));
63721
- __classPrivateFieldSet(this, _Block_valueHash, retval, "f");
63736
+ const retval = new BlockHash((0, hash_1.Hash)(Buffer.from(__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_toBytesInternal).call(this, false))));
63737
+ __classPrivateFieldSet(this, _PossiblyUnsignedBlock_valueHash, retval, "f");
63722
63738
  return (retval);
63723
63739
  }
63724
63740
  }
63725
- exports.Block = Block;
63726
- _a = Block, _Block_valueBytes = new WeakMap(), _Block_valueHash = new WeakMap(), _Block_instances = new WeakSet(), _Block_getSortedRequiredSigners = function _Block_getSortedRequiredSigners(input) {
63727
- const queue = [input];
63728
- const visited = new account_1.default.Set();
63729
- const out = [];
63730
- while (queue.length > 0) {
63731
- // We can assume that the signerFieldQueue is not empty here since the loop condition checks it
63732
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
63733
- const cur = queue.shift();
63734
- if (account_1.default.isInstance(cur)) {
63735
- if (visited.has(cur)) {
63736
- continue;
63737
- }
63738
- visited.add(cur);
63739
- out.push(cur);
63740
- }
63741
- else {
63742
- queue.unshift(...cur[1]);
63743
- }
63741
+ _a = PossiblyUnsignedBlock, _PossiblyUnsignedBlock_valueBytes = new WeakMap(), _PossiblyUnsignedBlock_valueHash = new WeakMap(), _PossiblyUnsignedBlock_hasSignature = new WeakMap(), _PossiblyUnsignedBlock_instances = new WeakSet(), _PossiblyUnsignedBlock_nonNullableSignatures_get = function _PossiblyUnsignedBlock_nonNullableSignatures_get() {
63742
+ if (!this.signatures) {
63743
+ throw (new Error('No signature field input found on block'));
63744
63744
  }
63745
- return (out);
63746
- }, _Block_validateBytes = function _Block_validateBytes() {
63747
- const existingBytes = __classPrivateFieldGet(this, _Block_valueBytes, "f");
63745
+ return (this.signatures);
63746
+ }, _PossiblyUnsignedBlock_validateRecalculatedBytes = function _PossiblyUnsignedBlock_validateRecalculatedBytes() {
63747
+ const existingBytes = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_valueBytes, "f");
63748
63748
  if (existingBytes === undefined) {
63749
63749
  return;
63750
63750
  }
63751
- const recalculatedBytesBuffer = Buffer.from(this.toBytes(true, false));
63751
+ const recalculatedBytesBuffer = Buffer.from(__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "m", _PossiblyUnsignedBlock_toBytesInternal).call(this, __classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f"), false));
63752
63752
  const existingBytesBuffer = Buffer.from(existingBytes);
63753
63753
  if (!recalculatedBytesBuffer.equals(existingBytesBuffer)) {
63754
63754
  const existingBytesHash = Buffer.from((0, hash_1.Hash)(existingBytesBuffer)).toString('hex').toUpperCase();
63755
63755
  const recalculatedBytesHash = Buffer.from((0, hash_1.Hash)(recalculatedBytesBuffer)).toString('hex').toUpperCase();
63756
63756
  throw (new block_1.default('BLOCK_INVALID_SIGNATURE', `Block signed bytes (${existingBytesHash}) do not match calculated bytes (${recalculatedBytesHash})`));
63757
63757
  }
63758
- }, _Block_validateOperationsPurpose = function _Block_validateOperationsPurpose() {
63758
+ }, _PossiblyUnsignedBlock_validateOperationsPurpose = function _PossiblyUnsignedBlock_validateOperationsPurpose() {
63759
63759
  /**
63760
63760
  * Do not allow blocks to contain invalid constructions
63761
63761
  */
@@ -63772,7 +63772,7 @@ _a = Block, _Block_valueBytes = new WeakMap(), _Block_valueHash = new WeakMap(),
63772
63772
  operation.validate(context);
63773
63773
  context.operationIndex++;
63774
63774
  }
63775
- }, _Block_validateSignerField = function _Block_validateSignerField() {
63775
+ }, _PossiblyUnsignedBlock_validateSignerField = function _PossiblyUnsignedBlock_validateSignerField() {
63776
63776
  if (!Array.isArray(this.signer)) {
63777
63777
  return;
63778
63778
  }
@@ -63801,26 +63801,172 @@ _a = Block, _Block_valueBytes = new WeakMap(), _Block_valueHash = new WeakMap(),
63801
63801
  }
63802
63802
  }
63803
63803
  }
63804
- }, _Block_validateSignatures = function _Block_validateSignatures() {
63805
- const signers = __classPrivateFieldGet(_a, _a, "m", _Block_getSortedRequiredSigners).call(_a, this.signer);
63806
- if (this.signatures.length !== signers.length) {
63804
+ }, _PossiblyUnsignedBlock_validateSignatures = function _PossiblyUnsignedBlock_validateSignatures() {
63805
+ if (!__classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f")) {
63806
+ throw (new block_1.default('BLOCK_SIGNATURE_REQUIRED', 'Block has not been signed'));
63807
+ }
63808
+ const signers = _a.getSortedRequiredSigners(this.signer);
63809
+ const signatureArray = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get);
63810
+ if (signatureArray.length !== signers.length) {
63807
63811
  throw (new block_1.default('BLOCK_INVALID_SIGNER', 'Signer count does not match signature count'));
63808
63812
  }
63809
63813
  for (let i = 0; i < signers.length; i++) {
63810
- const signature = new buffer_1.BufferStorage(this.signatures[i], 64);
63814
+ const signature = new buffer_1.BufferStorage(signatureArray[i], 64);
63811
63815
  const valid = signers[i].verify(this.hash.get(), signature.get());
63812
63816
  if (valid !== true) {
63813
- throw (new block_1.default('BLOCK_INVALID_SIGNATURE', `Unable to validate signature of ${this.hash.toString()} against signature ${this.signatures[i].toString('hex')} for account ${signers[i].publicKeyString.get()}`));
63817
+ throw (new block_1.default('BLOCK_INVALID_SIGNATURE', `Unable to validate signature of ${this.hash.toString()} against signature ${__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get)[i].toString('hex')} for account ${signers[i].publicKeyString.get()}`));
63818
+ }
63819
+ }
63820
+ }, _PossiblyUnsignedBlock_validateIdempotent = function _PossiblyUnsignedBlock_validateIdempotent() {
63821
+ if (this.idempotent === undefined) {
63822
+ return;
63823
+ }
63824
+ validateIdempotentKeyLength(this.idempotent, this.network);
63825
+ }, _PossiblyUnsignedBlock_toBytesInternal = function _PossiblyUnsignedBlock_toBytesInternal(includeSignatures, useCached = true) {
63826
+ const isCacheable = includeSignatures || !__classPrivateFieldGet(this, _PossiblyUnsignedBlock_hasSignature, "f");
63827
+ if (useCached && __classPrivateFieldGet(this, _PossiblyUnsignedBlock_valueBytes, "f") !== undefined && isCacheable) {
63828
+ return (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_valueBytes, "f"));
63829
+ }
63830
+ const sharedBlockValues = {
63831
+ previous: this.previous,
63832
+ operations: this.operations,
63833
+ account: this.account,
63834
+ network: this.network,
63835
+ subnet: this.subnet,
63836
+ date: this.date,
63837
+ idempotent: this.idempotent
63838
+ };
63839
+ let container;
63840
+ if (this.version === 1) {
63841
+ if (Array.isArray(this.signer)) {
63842
+ throw (new Error('Block v1 only supports single signer'));
63843
+ }
63844
+ container = _a.getV1ASN1ContainerWithoutSignature({
63845
+ ...sharedBlockValues,
63846
+ version: 1,
63847
+ signer: this.signer
63848
+ });
63849
+ if (includeSignatures) {
63850
+ if (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get).length !== 1) {
63851
+ throw (new Error('Block v1 only supports single signature'));
63852
+ }
63853
+ container.push(__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get)[0]);
63814
63854
  }
63815
63855
  }
63856
+ else {
63857
+ const versionTag = this.version - 1;
63858
+ if (versionTag !== 1) {
63859
+ // We only support version 2
63860
+ throw (new block_1.default('BLOCK_INVALID_VERSION', 'We only support version 1/2 blocks'));
63861
+ }
63862
+ const v2Container = _a.getV2ASN1ContainerWithoutSignature({
63863
+ ...sharedBlockValues,
63864
+ purpose: this.purpose,
63865
+ version: this.version,
63866
+ signer: this.signer
63867
+ });
63868
+ const baseContextTag = {
63869
+ type: 'context',
63870
+ kind: 'explicit',
63871
+ value: versionTag
63872
+ };
63873
+ if (includeSignatures) {
63874
+ let signatureContainer;
63875
+ if (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get).length > 1) {
63876
+ signatureContainer = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get);
63877
+ }
63878
+ else if (__classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get).length === 1) {
63879
+ signatureContainer = __classPrivateFieldGet(this, _PossiblyUnsignedBlock_instances, "a", _PossiblyUnsignedBlock_nonNullableSignatures_get)[0];
63880
+ }
63881
+ else {
63882
+ throw (new Error('Block has not been signed'));
63883
+ }
63884
+ container = { ...baseContextTag, contains: [...v2Container, signatureContainer] };
63885
+ }
63886
+ else {
63887
+ container = { ...baseContextTag, contains: v2Container };
63888
+ }
63889
+ }
63890
+ // We know the container is valid because of the container type, but the ASN1.JStoASN1 function does not handle recursive types well
63891
+ // @ts-ignore
63892
+ const retval = ASN1.JStoASN1(container).toBER(false);
63893
+ if (isCacheable) {
63894
+ __classPrivateFieldSet(this, _PossiblyUnsignedBlock_valueBytes, retval, "f");
63895
+ }
63896
+ return (retval);
63816
63897
  };
63817
- Block.isInstance = (0, helper_1.checkableGenerator)(_a);
63818
- Block.Hash = BlockHash;
63819
- Block.OperationType = Operations.OperationType;
63820
- Block.Operation = Operations.Operation;
63821
- Block.NO_PREVIOUS = NO_PREVIOUS;
63822
- Block.AdjustMethod = AdjustMethod;
63823
- Block.Purpose = BlockPurpose;
63898
+ PossiblyUnsignedBlock.Hash = BlockHash;
63899
+ PossiblyUnsignedBlock.OperationType = Operations.OperationType;
63900
+ PossiblyUnsignedBlock.Operation = Operations.Operation;
63901
+ PossiblyUnsignedBlock.NO_PREVIOUS = NO_PREVIOUS;
63902
+ PossiblyUnsignedBlock.AdjustMethod = AdjustMethod;
63903
+ PossiblyUnsignedBlock.Purpose = BlockPurpose;
63904
+ class UnsignedBlock extends PossiblyUnsignedBlock {
63905
+ constructor(input) {
63906
+ super(input, false);
63907
+ }
63908
+ static isValidJSON(block, version) {
63909
+ return (super.isValidJSONSignedOrUnsigned(false, block, version));
63910
+ }
63911
+ static async fromUnsignedJSON(input) {
63912
+ return (new this(input));
63913
+ }
63914
+ async seal() {
63915
+ const signers = UnsignedBlock.getSortedRequiredSigners(this.signer);
63916
+ const hash = this.hash;
63917
+ const signatures = await Promise.all(signers.map(async function (signer) {
63918
+ const signature = await signer.sign(hash.getBuffer());
63919
+ return (signature.getBuffer());
63920
+ }));
63921
+ const shared = {
63922
+ idempotent: this.idempotent,
63923
+ date: this.date,
63924
+ previous: this.previous,
63925
+ account: this.account,
63926
+ network: this.network,
63927
+ subnet: this.subnet,
63928
+ signer: this.signer,
63929
+ operations: this.operations
63930
+ };
63931
+ let blockInput;
63932
+ if (this.version === 1) {
63933
+ if (Array.isArray(this.signer)) {
63934
+ throw (new Error('Block v1 only supports single signer'));
63935
+ }
63936
+ blockInput = { ...shared, version: this.version, signer: this.signer, signature: signatures[0] };
63937
+ }
63938
+ else if (this.version === 2) {
63939
+ blockInput = { ...shared, version: this.version, purpose: this.purpose, signatures };
63940
+ }
63941
+ else {
63942
+ throw (new block_1.default('BLOCK_INVALID_VERSION', 'Invalid Version'));
63943
+ }
63944
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
63945
+ return (new Block(blockInput));
63946
+ }
63947
+ }
63948
+ exports.UnsignedBlock = UnsignedBlock;
63949
+ UnsignedBlock.isInstance = (0, helper_1.checkableGenerator)(UnsignedBlock);
63950
+ class Block extends PossiblyUnsignedBlock {
63951
+ constructor(input) {
63952
+ super(input, true);
63953
+ }
63954
+ static isValidJSON(block, version) {
63955
+ return (super.isValidJSONSignedOrUnsigned(true, block, version));
63956
+ }
63957
+ static async fromUnsignedJSON(input) {
63958
+ const unsigned = new UnsignedBlock(input);
63959
+ return (await unsigned.seal());
63960
+ }
63961
+ getUnsignedBlock() {
63962
+ return (new UnsignedBlock({
63963
+ ...(this.toJSON({ addBinary: false })),
63964
+ signatures: undefined
63965
+ }));
63966
+ }
63967
+ }
63968
+ exports.Block = Block;
63969
+ Block.isInstance = (0, helper_1.checkableGenerator)(Block);
63824
63970
  class BlockBuilder {
63825
63971
  constructor(block) {
63826
63972
  _BlockBuilder_block.set(this, void 0);
@@ -63842,32 +63988,16 @@ class BlockBuilder {
63842
63988
  __classPrivateFieldSet(this, _BlockBuilder_block, new Block(block), "f");
63843
63989
  }
63844
63990
  else {
63845
- const incompleteBlockJSON = {
63846
- date: (new Date()).toISOString(),
63847
- version: 1,
63848
- ...block
63849
- };
63991
+ if (block === undefined) {
63992
+ __classPrivateFieldSet(this, _BlockBuilder_block, {}, "f");
63993
+ return;
63994
+ }
63850
63995
  /*
63851
- * Map input to our values
63996
+ * Validate input values
63852
63997
  */
63853
- let setPreviousNoBlock = false;
63854
- if (incompleteBlockJSON.previous === BlockBuilder.NO_PREVIOUS) {
63855
- setPreviousNoBlock = true;
63856
- }
63857
- let newBlockJSON;
63858
- if (incompleteBlockJSON.version === 1) {
63859
- // We have to use a type assertion here because the MapV1InputValues function does not support recursive types
63860
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63861
- newBlockJSON = MapV1InputValues({ ...incompleteBlockJSON, version: 1 });
63862
- }
63863
- else if (incompleteBlockJSON.version === 2) {
63864
- newBlockJSON = MapV2InputValues({ ...incompleteBlockJSON, version: 2 });
63865
- }
63866
- else {
63867
- throw (new Error('Cannot construct block, it is not a valid Block JSON object'));
63868
- }
63869
- if (setPreviousNoBlock) {
63870
- newBlockJSON.previous = BlockBuilder.NO_PREVIOUS;
63998
+ const newBlockJSON = __classPrivateFieldGet(_b, _b, "m", _BlockBuilder_ValidateInputs).call(_b, block);
63999
+ if (block.previous === _b.NO_PREVIOUS) {
64000
+ newBlockJSON.previous = _b.NO_PREVIOUS;
63871
64001
  }
63872
64002
  __classPrivateFieldSet(this, _BlockBuilder_block, newBlockJSON, "f");
63873
64003
  }
@@ -63896,7 +64026,7 @@ class BlockBuilder {
63896
64026
  if (opts?.addBinary) {
63897
64027
  throw (new Error('Cannot add binary within blockBuilder.toJSON'));
63898
64028
  }
63899
- return ({
64029
+ return ((0, conversion_1.toJSONSerializable)({
63900
64030
  version: this.version,
63901
64031
  idempotent: this.idempotent,
63902
64032
  date: this.date,
@@ -63908,23 +64038,22 @@ class BlockBuilder {
63908
64038
  operations: this.operations,
63909
64039
  purpose: this.purpose,
63910
64040
  ['$opening']: this.$opening
63911
- });
64041
+ }));
63912
64042
  }
63913
- async seal() {
63914
- if (this.version === undefined) {
64043
+ async getUnsignedBlock() {
64044
+ const input = __classPrivateFieldGet(_b, _b, "m", _BlockBuilder_ValidateInputs).call(_b, this);
64045
+ if (input.version === undefined) {
63915
64046
  throw (new Error('Cannot seal block without version'));
63916
64047
  }
63917
- let input;
63918
- // There is no clean way to tell the compiler which version `this` is, so we have to use a type assertion
63919
- if (this.version === 1) {
63920
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63921
- input = MapV1InputValues(this);
63922
- }
63923
- else {
63924
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
63925
- input = MapV2InputValues(this);
64048
+ // Date is required for a sealed block, so added it if it wasn't provided
64049
+ if (input.date === undefined) {
64050
+ input.date = new Date();
63926
64051
  }
63927
- const block = await Block.fromUnsignedJSON(input);
64052
+ return (new UnsignedBlock(input));
64053
+ }
64054
+ async seal() {
64055
+ const unsigned = await this.getUnsignedBlock();
64056
+ const block = await unsigned.seal();
63928
64057
  __classPrivateFieldSet(this, _BlockBuilder_block, block, "f");
63929
64058
  return (block);
63930
64059
  }
@@ -64040,7 +64169,7 @@ class BlockBuilder {
64040
64169
  if (BlockHash.isInstance(previous)) {
64041
64170
  return (previous);
64042
64171
  }
64043
- if (previous === BlockBuilder.NO_PREVIOUS) {
64172
+ if (previous === _b.NO_PREVIOUS) {
64044
64173
  if (this.account !== undefined) {
64045
64174
  return (BlockHash.getAccountOpeningHash(this.account));
64046
64175
  }
@@ -64061,7 +64190,7 @@ class BlockBuilder {
64061
64190
  if (previous === undefined) {
64062
64191
  return (undefined);
64063
64192
  }
64064
- if (previous === BlockBuilder.NO_PREVIOUS) {
64193
+ if (previous === _b.NO_PREVIOUS) {
64065
64194
  return (true);
64066
64195
  }
64067
64196
  const sentinel = Block.getAccountOpeningHash(account);
@@ -64166,8 +64295,41 @@ class BlockBuilder {
64166
64295
  }
64167
64296
  }
64168
64297
  exports.BlockBuilder = BlockBuilder;
64169
- _BlockBuilder_block = new WeakMap();
64170
- BlockBuilder.isInstance = (0, helper_1.checkableGenerator)(BlockBuilder);
64298
+ _b = BlockBuilder, _BlockBuilder_block = new WeakMap(), _BlockBuilder_ValidateInputs = function _BlockBuilder_ValidateInputs(blockInput) {
64299
+ let block = blockInput;
64300
+ // Keep the signer as the original object so we can seal the block
64301
+ if (_b.isInstance(blockInput)) {
64302
+ block = {
64303
+ ...blockInput.toJSON(),
64304
+ signer: blockInput.signer
64305
+ };
64306
+ }
64307
+ let validatedBlockJSON;
64308
+ if (block.version === undefined || block.version === 1) {
64309
+ if (block.signer && typeof block.signer !== 'string' && !account_1.default.isInstance(block.signer)) {
64310
+ throw (new block_1.default('BLOCK_INVALID_SIGNER', 'V1 Blocks Cannot use MultiSig Signers'));
64311
+ }
64312
+ if (block.purpose !== undefined && block.purpose !== BlockPurpose.GENERIC) {
64313
+ throw (new block_1.default('BLOCK_INVALID_PURPOSE_VALIDATION', 'V1 Block Purpose should be undefined'));
64314
+ }
64315
+ // Create narrowed block input
64316
+ const blockV1 = {
64317
+ ...block,
64318
+ version: 1,
64319
+ signer: block.signer,
64320
+ purpose: block.purpose
64321
+ };
64322
+ validatedBlockJSON = MapV1InputValues(blockV1);
64323
+ }
64324
+ else if (block.version === 2) {
64325
+ validatedBlockJSON = MapV2InputValues({ ...block, version: 2 });
64326
+ }
64327
+ else {
64328
+ throw (new block_1.default('BLOCK_INVALID_VERSION', `Cannot construct block, expected version: 1 | 2, received: ${block.version}`));
64329
+ }
64330
+ return (validatedBlockJSON);
64331
+ };
64332
+ BlockBuilder.isInstance = (0, helper_1.checkableGenerator)(_b);
64171
64333
  BlockBuilder.OperationType = Block.OperationType;
64172
64334
  BlockBuilder.AdjustMethod = Block.AdjustMethod;
64173
64335
  BlockBuilder.Operation = Block.Operation;
@@ -64235,11 +64397,11 @@ const account_1 = __importStar(__webpack_require__(9415));
64235
64397
  const permissions_1 = __webpack_require__(5860);
64236
64398
  const block_1 = __importDefault(__webpack_require__(7412));
64237
64399
  const conversion_1 = __webpack_require__(2360);
64238
- const _1 = __webpack_require__(6158);
64239
- const _2 = __importStar(__webpack_require__(6158));
64400
+ const _1 = __importStar(__webpack_require__(6158));
64240
64401
  const config_1 = __webpack_require__(1491);
64241
64402
  const certificate_1 = __webpack_require__(5661);
64242
64403
  const common_1 = __webpack_require__(5663);
64404
+ const util_1 = __webpack_require__(9023);
64243
64405
  /**
64244
64406
  * All supported operations
64245
64407
  */
@@ -64397,11 +64559,10 @@ class BlockOperation {
64397
64559
  if (amount === undefined || amount === null) {
64398
64560
  throw (new Error('internal error: "amount" is invalid'));
64399
64561
  }
64400
- const bigintAmount = BigInt(amount);
64401
- if (bigintAmount < 0n) {
64402
- throw (new block_1.default('BLOCK_AMOUNT_BELOW_ZERO', 'value cannot be negative'));
64562
+ if (typeof amount === 'bigint') {
64563
+ return (amount);
64403
64564
  }
64404
- return (bigintAmount);
64565
+ return ((0, conversion_1.parseHexBigIntString)(amount));
64405
64566
  }
64406
64567
  }
64407
64568
  BlockOperation.isInstance = (0, helper_1.checkableGenerator)(BlockOperation);
@@ -64442,6 +64603,7 @@ class BlockOperationSEND extends BlockOperation {
64442
64603
  validate(context) {
64443
64604
  const { block } = context;
64444
64605
  const account = block.account;
64606
+ (0, common_1.validateNumericValue)(this.amount, block, 'amount');
64445
64607
  // Only allow tokens to use send if they are the token being sent
64446
64608
  if (account.keyType === account_1.AccountKeyAlgorithm.TOKEN && this.token.comparePublicKey(account) === false) {
64447
64609
  throw (new block_1.default('BLOCK_NO_TOKEN_OP', 'Tokens cannot use SEND, did you mean to use TOKEN_ADMIN_MODIFY_BALANCE'));
@@ -64471,13 +64633,13 @@ class BlockOperationSEND extends BlockOperation {
64471
64633
  }
64472
64634
  }
64473
64635
  toJSON() {
64474
- return ({
64636
+ return ((0, conversion_1.toJSONSerializable)({
64475
64637
  type: this.type,
64476
64638
  to: this.to,
64477
64639
  amount: this.amount,
64478
64640
  external: this.external,
64479
64641
  token: this.token
64480
- });
64642
+ }));
64481
64643
  }
64482
64644
  }
64483
64645
  _BlockOperationSEND_to = new WeakMap(), _BlockOperationSEND_amount = new WeakMap(), _BlockOperationSEND_token = new WeakMap(), _BlockOperationSEND_instances = new WeakSet(), _BlockOperationSEND_computeToken = function _BlockOperationSEND_computeToken(token) {
@@ -64540,6 +64702,7 @@ class BlockOperationRECEIVE extends BlockOperation {
64540
64702
  validate(context) {
64541
64703
  const { block } = context;
64542
64704
  const account = block.account;
64705
+ (0, common_1.validateNumericValue)(this.amount, block, 'amount');
64543
64706
  if (account.isToken()) {
64544
64707
  throw (new block_1.default('BLOCK_NO_TOKEN_OP', 'Token addresses cannot use RECEIVE'));
64545
64708
  }
@@ -64556,14 +64719,14 @@ class BlockOperationRECEIVE extends BlockOperation {
64556
64719
  }
64557
64720
  }
64558
64721
  toJSON() {
64559
- return ({
64722
+ return ((0, conversion_1.toJSONSerializable)({
64560
64723
  type: this.type,
64561
64724
  amount: this.amount,
64562
64725
  token: this.token,
64563
64726
  from: this.from,
64564
64727
  exact: this.exact,
64565
64728
  forward: this.forward
64566
- });
64729
+ }));
64567
64730
  }
64568
64731
  }
64569
64732
  _BlockOperationRECEIVE_amount = new WeakMap(), _BlockOperationRECEIVE_token = new WeakMap(), _BlockOperationRECEIVE_from = new WeakMap(), _BlockOperationRECEIVE_forward = new WeakMap(), _BlockOperationRECEIVE_exact = new WeakMap(), _BlockOperationRECEIVE_instances = new WeakSet(), _BlockOperationRECEIVE_computeExact = function _BlockOperationRECEIVE_computeExact(exact) {
@@ -64619,17 +64782,18 @@ class BlockOperationTOKEN_ADMIN_MODIFY_BALANCE extends BlockOperation {
64619
64782
  }
64620
64783
  validate(context) {
64621
64784
  const { block } = context;
64785
+ (0, common_1.validateNumericValue)(__classPrivateFieldGet(this, _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_amount, "f"), block, 'amount');
64622
64786
  if (block.account.keyType === account_1.AccountKeyAlgorithm.TOKEN) {
64623
64787
  throw (new block_1.default('BLOCK_NO_TOKEN_OP', 'You cannot use TOKEN_ADMIN_MODIFY_BALANCE on a token account'));
64624
64788
  }
64625
64789
  }
64626
64790
  toJSON() {
64627
- return ({
64791
+ return ((0, conversion_1.toJSONSerializable)({
64628
64792
  type: this.type,
64629
64793
  token: this.token,
64630
64794
  amount: this.amount,
64631
64795
  method: this.method
64632
- });
64796
+ }));
64633
64797
  }
64634
64798
  }
64635
64799
  _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_token = new WeakMap(), _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_method = new WeakMap(), _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_amount = new WeakMap(), _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_instances = new WeakSet(), _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_computeToken = function _BlockOperationTOKEN_ADMIN_MODIFY_BALANCE_computeToken(token) {
@@ -64672,10 +64836,10 @@ class BlockOperationSET_REP extends BlockOperation {
64672
64836
  }
64673
64837
  }
64674
64838
  toJSON() {
64675
- return ({
64839
+ return ((0, conversion_1.toJSONSerializable)({
64676
64840
  type: this.type,
64677
64841
  to: this.to
64678
- });
64842
+ }));
64679
64843
  }
64680
64844
  }
64681
64845
  _BlockOperationSET_REP_to = new WeakMap();
@@ -64744,11 +64908,11 @@ class BlockOperationCREATE_IDENTIFIER extends BlockOperation {
64744
64908
  }
64745
64909
  }
64746
64910
  toJSON() {
64747
- return ({
64911
+ return ((0, conversion_1.toJSONSerializable)({
64748
64912
  type: this.type,
64749
64913
  identifier: this.identifier,
64750
64914
  createArguments: __classPrivateFieldGet(this, _BlockOperationCREATE_IDENTIFIER_createArguments, "f")
64751
- });
64915
+ }));
64752
64916
  }
64753
64917
  }
64754
64918
  _BlockOperationCREATE_IDENTIFIER_identifier = new WeakMap(), _BlockOperationCREATE_IDENTIFIER_createArguments = new WeakMap(), _BlockOperationCREATE_IDENTIFIER_instances = new WeakSet(), _BlockOperationCREATE_IDENTIFIER_computeIdentifier = function _BlockOperationCREATE_IDENTIFIER_computeIdentifier(identifierStr) {
@@ -64863,7 +65027,7 @@ class BlockOperationSET_INFO extends BlockOperation {
64863
65027
  if (this.defaultPermission !== undefined) {
64864
65028
  val.defaultPermission = this.defaultPermission;
64865
65029
  }
64866
- return (val);
65030
+ return ((0, conversion_1.toJSONSerializable)(val));
64867
65031
  }
64868
65032
  }
64869
65033
  _BlockOperationSET_INFO_name = new WeakMap(), _BlockOperationSET_INFO_description = new WeakMap(), _BlockOperationSET_INFO_metadata = new WeakMap(), _BlockOperationSET_INFO_defaultPermission = new WeakMap(), _BlockOperationSET_INFO_instances = new WeakSet(), _BlockOperationSET_INFO_validateNameDesc = function _BlockOperationSET_INFO_validateNameDesc(field, value, network) {
@@ -64923,7 +65087,7 @@ class BlockOperationMODIFY_PERMISSIONS extends BlockOperation {
64923
65087
  validate(context) {
64924
65088
  const { block } = context;
64925
65089
  if (this.permissions === null) {
64926
- if (this.method !== _2.AdjustMethod.SET) {
65090
+ if (this.method !== _1.AdjustMethod.SET) {
64927
65091
  throw (new Error('Method must be SET when permissions = null'));
64928
65092
  }
64929
65093
  }
@@ -64949,7 +65113,7 @@ class BlockOperationMODIFY_PERMISSIONS extends BlockOperation {
64949
65113
  if (this.target !== undefined && settingAdminOrHigher) {
64950
65114
  throw (new block_1.default('BLOCK_NO_ADMIN_ON_TARGET', 'Cannot set admin or higher with a target specified'));
64951
65115
  }
64952
- if (this.method !== _2.default.AdjustMethod.SET && !this.permissions.canUseDelegation) {
65116
+ if (this.method !== _1.default.AdjustMethod.SET && !this.permissions.canUseDelegation) {
64953
65117
  throw (new block_1.default('BLOCK_NO_DELEGATE_ADMIN', `Cannot use delegation for ${baseFlagsString}`));
64954
65118
  }
64955
65119
  }
@@ -64970,19 +65134,19 @@ class BlockOperationMODIFY_PERMISSIONS extends BlockOperation {
64970
65134
  if (foundMethod === undefined) {
64971
65135
  continue;
64972
65136
  }
64973
- if (method === _2.default.AdjustMethod.SET) {
65137
+ if (method === _1.default.AdjustMethod.SET) {
64974
65138
  throw (new block_1.default('BLOCK_NO_MODIFY_PERMISSION_DUPE', 'Cannot have a SET operation after any other change with the same target in MODIFY_PERMISSIONS'));
64975
65139
  }
64976
65140
  }
64977
65141
  }
64978
65142
  toJSON() {
64979
- return ({
65143
+ return ((0, conversion_1.toJSONSerializable)({
64980
65144
  type: this.type,
64981
65145
  principal: this.principal,
64982
65146
  method: this.method,
64983
65147
  permissions: this.permissions,
64984
65148
  target: this.target
64985
- });
65149
+ }));
64986
65150
  }
64987
65151
  }
64988
65152
  _BlockOperationMODIFY_PERMISSIONS_principal = new WeakMap(), _BlockOperationMODIFY_PERMISSIONS_target = new WeakMap(), _BlockOperationMODIFY_PERMISSIONS_method = new WeakMap(), _BlockOperationMODIFY_PERMISSIONS_permissions = new WeakMap(), _BlockOperationMODIFY_PERMISSIONS_instances = new WeakSet(), _BlockOperationMODIFY_PERMISSIONS_computePermissions = function _BlockOperationMODIFY_PERMISSIONS_computePermissions(permissions) {
@@ -65019,22 +65183,23 @@ class BlockOperationTOKEN_ADMIN_SUPPLY extends BlockOperation {
65019
65183
  }
65020
65184
  validate(context) {
65021
65185
  const { block } = context;
65186
+ (0, common_1.validateNumericValue)(__classPrivateFieldGet(this, _BlockOperationTOKEN_ADMIN_SUPPLY_amount, "f"), block, 'amount');
65022
65187
  if (block.account.keyType !== account_1.AccountKeyAlgorithm.TOKEN) {
65023
65188
  throw (new block_1.default('BLOCK_ONLY_TOKEN_OP', 'Only token accounts can use TOKEN_ADMIN_SUPPLY'));
65024
65189
  }
65025
65190
  (0, common_1.validateSupply)(__classPrivateFieldGet(this, _BlockOperationTOKEN_ADMIN_SUPPLY_amount, "f"), block.network);
65026
65191
  }
65027
65192
  toJSON() {
65028
- return ({
65193
+ return ((0, conversion_1.toJSONSerializable)({
65029
65194
  type: this.type,
65030
65195
  amount: this.amount,
65031
65196
  method: this.method
65032
- });
65197
+ }));
65033
65198
  }
65034
65199
  }
65035
65200
  _BlockOperationTOKEN_ADMIN_SUPPLY_amount = new WeakMap(), _BlockOperationTOKEN_ADMIN_SUPPLY_method = new WeakMap(), _BlockOperationTOKEN_ADMIN_SUPPLY_instances = new WeakSet(), _BlockOperationTOKEN_ADMIN_SUPPLY_computeSupplyMethod = function _BlockOperationTOKEN_ADMIN_SUPPLY_computeSupplyMethod(method) {
65036
65201
  const numericMethod = (0, _1.toAdjustMethod)(method);
65037
- if (numericMethod === _2.default.AdjustMethod.SET) {
65202
+ if (numericMethod === _1.default.AdjustMethod.SET) {
65038
65203
  throw (new Error('Cannot use AdjustMethod.SET on a TOKEN_ADMIN_SUPPLY operation'));
65039
65204
  }
65040
65205
  return (numericMethod);
@@ -65053,10 +65218,10 @@ class BlockOperationMANAGE_CERTIFICATE extends BlockOperation {
65053
65218
  }
65054
65219
  __classPrivateFieldSet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, __classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_instances, "m", _BlockOperationMANAGE_CERTIFICATE_asCertificate).call(this, input.certificateOrHash), "f");
65055
65220
  __classPrivateFieldSet(this, _BlockOperationMANAGE_CERTIFICATE_method, __classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_instances, "m", _BlockOperationMANAGE_CERTIFICATE_computeCertificateMethod).call(this, input.method), "f");
65056
- if ((input.intermediateCertificates === undefined) === (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.ADD)) {
65221
+ if ((input.intermediateCertificates === undefined) === (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _1.default.AdjustMethod.ADD)) {
65057
65222
  throw (new block_1.default('BLOCK_INTERMEDIATE_CERTIFICATES_ONLY_ADD', 'Must provide intermediate certificates with a MANAGE_CERTIFICATE operation that is an ADD operation'));
65058
65223
  }
65059
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.ADD) {
65224
+ if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _1.default.AdjustMethod.ADD) {
65060
65225
  __classPrivateFieldSet(this, _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates, __classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_instances, "m", _BlockOperationMANAGE_CERTIFICATE_asIntermediateCertificates).call(this, input.intermediateCertificates), "f");
65061
65226
  }
65062
65227
  else {
@@ -65064,7 +65229,7 @@ class BlockOperationMANAGE_CERTIFICATE extends BlockOperation {
65064
65229
  }
65065
65230
  }
65066
65231
  get intermediateCertificates() {
65067
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.SUBTRACT) {
65232
+ if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _1.default.AdjustMethod.SUBTRACT) {
65068
65233
  return (undefined);
65069
65234
  }
65070
65235
  return (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates, "f"));
@@ -65074,12 +65239,12 @@ class BlockOperationMANAGE_CERTIFICATE extends BlockOperation {
65074
65239
  }
65075
65240
  get certificateOrHash() {
65076
65241
  if (certificate_1.CertificateHash.isInstance(__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"))) {
65077
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.ADD) {
65242
+ if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _1.default.AdjustMethod.ADD) {
65078
65243
  throw (new block_1.default('BLOCK_INVALID_CERTIFICATE_VALUE', 'Cannot add a certificate by hash, you must provide the full certificate'));
65079
65244
  }
65080
65245
  return (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"));
65081
65246
  }
65082
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.SUBTRACT && !certificate_1.CertificateHash.isInstance(__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"))) {
65247
+ if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _1.default.AdjustMethod.SUBTRACT && !certificate_1.CertificateHash.isInstance(__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"))) {
65083
65248
  return (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f").hash());
65084
65249
  }
65085
65250
  return (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"));
@@ -65094,7 +65259,7 @@ class BlockOperationMANAGE_CERTIFICATE extends BlockOperation {
65094
65259
  return (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f"));
65095
65260
  }
65096
65261
  validate(context) {
65097
- if (this.method === _2.default.AdjustMethod.ADD) {
65262
+ if (this.method === _1.default.AdjustMethod.ADD) {
65098
65263
  if (certificate_1.CertificateHash.isInstance(__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_certificateOrHash, "f"))) {
65099
65264
  throw (new block_1.default('BLOCK_INVALID_CERTIFICATE_VALUE', 'Cannot add a certificate by hash, you must provide the full certificate'));
65100
65265
  }
@@ -65130,35 +65295,12 @@ class BlockOperationMANAGE_CERTIFICATE extends BlockOperation {
65130
65295
  }
65131
65296
  }
65132
65297
  toJSON() {
65133
- let intermediateCertificates;
65134
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.SUBTRACT) {
65135
- intermediateCertificates = undefined;
65136
- }
65137
- else {
65138
- intermediateCertificates = null;
65139
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates, "f") && __classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates, "f").bundleSize > 0) {
65140
- intermediateCertificates = __classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates, "f").getDERBuffer().toString('base64');
65141
- }
65142
- }
65143
- let serializedCertificate;
65144
- if (__classPrivateFieldGet(this, _BlockOperationMANAGE_CERTIFICATE_method, "f") === _2.default.AdjustMethod.SUBTRACT) {
65145
- if (!certificate_1.CertificateHash.isInstance(this.certificateOrHash)) {
65146
- throw (new Error('Invalid response from get certificate, expected a CertificateHash'));
65147
- }
65148
- serializedCertificate = this.certificateOrHash.toString();
65149
- }
65150
- else {
65151
- if (!certificate_1.Certificate.isCertificate(this.certificateOrHash)) {
65152
- throw (new Error('Invalid response from get certificate, expected a Certificate'));
65153
- }
65154
- serializedCertificate = this.certificateOrHash.toPEM();
65155
- }
65156
- return ({
65298
+ return ((0, conversion_1.toJSONSerializable)({
65157
65299
  type: this.type,
65158
- certificateOrHash: serializedCertificate,
65300
+ certificateOrHash: this.certificateOrHash,
65159
65301
  method: this.method,
65160
- intermediateCertificates: intermediateCertificates
65161
- });
65302
+ intermediateCertificates: this.intermediateCertificates
65303
+ }));
65162
65304
  }
65163
65305
  }
65164
65306
  _BlockOperationMANAGE_CERTIFICATE_certificateOrHash = new WeakMap(), _BlockOperationMANAGE_CERTIFICATE_intermediateCertificates = new WeakMap(), _BlockOperationMANAGE_CERTIFICATE_method = new WeakMap(), _BlockOperationMANAGE_CERTIFICATE_instances = new WeakSet(), _BlockOperationMANAGE_CERTIFICATE_asCertificate = function _BlockOperationMANAGE_CERTIFICATE_asCertificate(certificate) {
@@ -65174,6 +65316,10 @@ _BlockOperationMANAGE_CERTIFICATE_certificateOrHash = new WeakMap(), _BlockOpera
65174
65316
  catch {
65175
65317
  /* Ignore Errors */
65176
65318
  }
65319
+ if (!util_1.types.isArrayBuffer(certificate) && !Buffer.isBuffer(certificate) && typeof certificate === 'object') {
65320
+ // We still have an object that should have created a certificate but it failed
65321
+ throw (new Error('Could not reconstruct Certificate from JSON'));
65322
+ }
65177
65323
  try {
65178
65324
  return (new certificate_1.CertificateHash(certificate));
65179
65325
  }
@@ -65192,7 +65338,7 @@ _BlockOperationMANAGE_CERTIFICATE_certificateOrHash = new WeakMap(), _BlockOpera
65192
65338
  return (bundleObject);
65193
65339
  }, _BlockOperationMANAGE_CERTIFICATE_computeCertificateMethod = function _BlockOperationMANAGE_CERTIFICATE_computeCertificateMethod(method) {
65194
65340
  const numericMethod = (0, _1.toAdjustMethod)(method);
65195
- if (numericMethod === _2.default.AdjustMethod.SET) {
65341
+ if (numericMethod === _1.default.AdjustMethod.SET) {
65196
65342
  throw (new Error('Cannot use AdjustMethod.SET on a MANAGE_CERTIFICATE operation.'));
65197
65343
  }
65198
65344
  return (numericMethod);
@@ -65226,9 +65372,9 @@ function isBlockOperation(input) {
65226
65372
  * serialized to JSON
65227
65373
  */
65228
65374
  function ExportOperationsJSON(operations) {
65229
- return ((0, conversion_1.toJSONSerializable)(operations.map(function (operation) {
65375
+ return (operations.map(function (operation) {
65230
65376
  return (operation.toJSON());
65231
- })));
65377
+ }));
65232
65378
  }
65233
65379
  function ImportOperationsJSON(operations) {
65234
65380
  const newOperations = [];
@@ -65389,10 +65535,10 @@ function ImportOperationsASN1(input, network) {
65389
65535
  else if ((0, helper_1.isBuffer)(keyValueIn)) {
65390
65536
  if (type === OperationType.MANAGE_CERTIFICATE && key === 'certificateOrHash') {
65391
65537
  const method = (0, _1.toAdjustMethod)(operation['method']);
65392
- if (method === _2.AdjustMethod.SUBTRACT) {
65538
+ if (method === _1.AdjustMethod.SUBTRACT) {
65393
65539
  keyValueOut = new certificate_1.CertificateHash(keyValueIn);
65394
65540
  }
65395
- else if (method === _2.AdjustMethod.ADD) {
65541
+ else if (method === _1.AdjustMethod.ADD) {
65396
65542
  keyValueOut = new certificate_1.Certificate(keyValueIn);
65397
65543
  }
65398
65544
  else {
@@ -65584,7 +65730,9 @@ exports.BlockErrorCodes = [
65584
65730
  'PERMISSIONS_INVALID_TARGET',
65585
65731
  'PREVIOUS_SELF',
65586
65732
  'SUPPLY_INVALID',
65587
- 'TOKEN_RECEIVE_DIFFERS'
65733
+ 'TOKEN_RECEIVE_DIFFERS',
65734
+ 'SIGNATURE_REQUIRED',
65735
+ 'SIGNATURE_PARAMETER_DIFFERS'
65588
65736
  ];
65589
65737
  exports.FullBlockErrorCodes = exports.BlockErrorCodes.map(code => `${BlockErrorType}_${code}`);
65590
65738
  class KeetaNetBlockError extends base_1.KeetaNetErrorBase {
@@ -66492,6 +66640,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true }));
66492
66640
  exports.LedgerStorageBase = void 0;
66493
66641
  exports.findPermissionMatch = findPermissionMatch;
66494
66642
  exports.validateSupply = validateSupply;
66643
+ exports.validateNumericValue = validateNumericValue;
66495
66644
  exports.validateBlockSignerCount = validateBlockSignerCount;
66496
66645
  exports.validateBlockSignerDepth = validateBlockSignerDepth;
66497
66646
  exports.computeLedgerEffect = computeLedgerEffect;
@@ -66533,6 +66682,16 @@ function validateSupply(amount, network) {
66533
66682
  throw (new block_2.default('BLOCK_SUPPLY_INVALID', `supply does not fit proper format -- GOT: '${amount}' MaxValue: ${maxValue}`));
66534
66683
  }
66535
66684
  }
66685
+ function validateNumericValue(value, block, fieldName, context) {
66686
+ if (value >= 0n) {
66687
+ return;
66688
+ }
66689
+ const config = (0, config_1.getValidation)(block.network).blockOperations.validateNumericValues;
66690
+ if (BigInt(block.date.valueOf()) < config.cutoffEpoch) {
66691
+ return;
66692
+ }
66693
+ throw (new block_2.default('BLOCK_AMOUNT_BELOW_ZERO', `${fieldName ?? 'value'} cannot be negative`));
66694
+ }
66536
66695
  function validateBlockSignerCount(amount, network) {
66537
66696
  const { maxValue } = (0, config_1.getValidation)(network).accountInfoFieldRules['blockSignerCount'];
66538
66697
  if (amount > maxValue || amount < 1n) {
@@ -67386,9 +67545,6 @@ function updateAccountInfoInState(state, account, info) {
67386
67545
  * Compute the effect of a SEND operation
67387
67546
  */
67388
67547
  function computeEffectOfOperationSEND(state, block, operation) {
67389
- if (operation.amount < 0n) {
67390
- throw (new Error('Internal error: SEND operation with negative amount'));
67391
- }
67392
67548
  // Decrement sender balance
67393
67549
  const senderChange = {
67394
67550
  state,
@@ -67416,9 +67572,6 @@ function computeEffectOfOperationSEND(state, block, operation) {
67416
67572
  * Compute the effect of a RECEIVE operation
67417
67573
  */
67418
67574
  function computeEffectOfOperationRECEIVE(state, block, operation) {
67419
- if (operation.amount < 0n) {
67420
- throw (new Error('Internal error: RECEIVE operation with negative amount'));
67421
- }
67422
67575
  // Increment recipient balance
67423
67576
  const recipientChange = {
67424
67577
  state,
@@ -67454,9 +67607,6 @@ function computeEffectOfOperationRECEIVE(state, block, operation) {
67454
67607
  }
67455
67608
  }
67456
67609
  function computeEffectOfOperationTOKEN_ADMIN_MODIFY_BALANCE(state, block, operation) {
67457
- if (operation.amount < 0n) {
67458
- throw (new Error('Internal error: TOKEN_ADMIN_MODIFY_BALANCE operation with negative amount'));
67459
- }
67460
67610
  if (operation.method === block_1.Block.AdjustMethod.SET) {
67461
67611
  const setChange = {
67462
67612
  state,
@@ -67570,9 +67720,6 @@ function computeEffectOfOperationMODIFY_PERMISSIONS(state, block, operation) {
67570
67720
  });
67571
67721
  }
67572
67722
  function computeEffectOfOperationTOKEN_ADMIN_SUPPLY(state, block, operation) {
67573
- if (operation.amount < 0n) {
67574
- throw (new Error('Internal error: TOKEN_ADMIN_SUPPLY operation with negative amount'));
67575
- }
67576
67723
  const tokenPubKey = block.account.publicKeyString.get();
67577
67724
  let value = 0n;
67578
67725
  switch (operation.method) {
@@ -68970,6 +69117,13 @@ _LedgerAtomicInterface_network = new WeakMap(), _LedgerAtomicInterface_subnet =
68970
69117
  for (const block of blocks) {
68971
69118
  for (const operation of block.operations) {
68972
69119
  switch (operation.type) {
69120
+ case block_1.Block.OperationType.RECEIVE:
69121
+ case block_1.Block.OperationType.SEND:
69122
+ case block_1.Block.OperationType.TOKEN_ADMIN_SUPPLY:
69123
+ if (operation.amount < 0n) {
69124
+ throw (new Error(`Operation amount cannot be negative: ${operation.amount}`));
69125
+ }
69126
+ break;
68973
69127
  case block_1.Block.OperationType.SET_REP:
68974
69128
  if (__classPrivateFieldGet(this, _LedgerAtomicInterface_operations, "f").setRep !== undefined) {
68975
69129
  const validRep = await __classPrivateFieldGet(this, _LedgerAtomicInterface_operations, "f").setRep(block.account, operation.to);
@@ -68982,6 +69136,9 @@ _LedgerAtomicInterface_network = new WeakMap(), _LedgerAtomicInterface_subnet =
68982
69136
  if (!__classPrivateFieldGet(this, _LedgerAtomicInterface_operations, "f").enableTokenAdminModifyBalance) {
68983
69137
  throw (new ledger_1.KeetaNetLedgerError('LEDGER_OPERATION_NOT_SUPPORTED', 'TOKEN_ADMIN_MODIFY_BALANCE operation not supported'));
68984
69138
  }
69139
+ if (operation.amount < 0n) {
69140
+ throw (new Error(`Operation amount cannot be negative: ${operation.amount}`));
69141
+ }
68985
69142
  break;
68986
69143
  default:
68987
69144
  break;
@@ -69821,6 +69978,10 @@ class Log {
69821
69978
  * The maximum number of log entries to send to each target at a time
69822
69979
  */
69823
69980
  this.batchSize = 10;
69981
+ /**
69982
+ * Parent logger, if any -- used for creating hierarchical loggers
69983
+ */
69984
+ this.parent = null;
69824
69985
  if (options?.logDebugTracing !== undefined) {
69825
69986
  __classPrivateFieldSet(this, _Log_logDebugTracing, options.logDebugTracing, "f");
69826
69987
  }
@@ -69853,9 +70014,15 @@ class Log {
69853
70014
  if (__classPrivateFieldGet(this, _Log_destroyed, "f")) {
69854
70015
  throw (new Error('Cannot register target on destroyed Log instance'));
69855
70016
  }
69856
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
69857
- const id = Symbol('LogTargetID');
69858
- __classPrivateFieldGet(this, _Log_targets, "f").set(id, target);
70017
+ let id;
70018
+ if (this.parent) {
70019
+ id = this.parent.registerTarget(target);
70020
+ }
70021
+ else {
70022
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
70023
+ id = Symbol('LogTargetID');
70024
+ __classPrivateFieldGet(this, _Log_targets, "f").set(id, target);
70025
+ }
69859
70026
  return (id);
69860
70027
  }
69861
70028
  /**
@@ -69875,7 +70042,46 @@ class Log {
69875
70042
  if (__classPrivateFieldGet(this, _Log_destroyed, "f")) {
69876
70043
  return;
69877
70044
  }
69878
- __classPrivateFieldGet(this, _Log_targets, "f").delete(id);
70045
+ if (this.parent) {
70046
+ this.parent.unregisterTarget(id);
70047
+ }
70048
+ else {
70049
+ __classPrivateFieldGet(this, _Log_targets, "f").delete(id);
70050
+ }
70051
+ }
70052
+ /**
70053
+ * Get the currently registered log targets.
70054
+ *
70055
+ * If this is a child logger, this will return the parent's targets
70056
+ * because child loggers share the same targets as their parent.
70057
+ */
70058
+ get targets() {
70059
+ if (__classPrivateFieldGet(this, _Log_destroyed, "f")) {
70060
+ return ([]);
70061
+ }
70062
+ if (this.parent) {
70063
+ return (this.parent.targets);
70064
+ }
70065
+ return (Array.from(__classPrivateFieldGet(this, _Log_targets, "f").values()));
70066
+ }
70067
+ /**
70068
+ * Create a child logger instance that shares the same targets as this instance
70069
+ * but has its own log queue, this is useful for creating hierarchical loggers
70070
+ * which can call sync independently.
70071
+ *
70072
+ * Since the child shares the same targets, registering or unregistering targets
70073
+ * from either the parent or child will affect both.
70074
+ */
70075
+ createChild() {
70076
+ const child = new Log({
70077
+ logDebugTracing: __classPrivateFieldGet(this, _Log_logDebugTracing, "f")
70078
+ });
70079
+ /**
70080
+ * Attach child nodes to our own parent to collapse
70081
+ * chains of loggers
70082
+ */
70083
+ child.parent = this.parent ?? this;
70084
+ return (child);
69879
70085
  }
69880
70086
  /**
69881
70087
  * Emit a set of logs to all registered targets
@@ -69921,7 +70127,7 @@ class Log {
69921
70127
  * in case a target is added later; However, if there are
69922
70128
  * too many logs, drop the oldest ones
69923
70129
  */
69924
- if (__classPrivateFieldGet(this, _Log_targets, "f").size === 0) {
70130
+ if (this.targets.length === 0) {
69925
70131
  if (__classPrivateFieldGet(this, _Log_logs, "f").length > MAX_LOGS_TO_ENQUEUE_WITH_NO_TARGETS) {
69926
70132
  __classPrivateFieldGet(this, _Log_logs, "f").splice(0, __classPrivateFieldGet(this, _Log_logs, "f").length - MAX_LOGS_TO_ENQUEUE_WITH_NO_TARGETS);
69927
70133
  }
@@ -69944,7 +70150,7 @@ class Log {
69944
70150
  * while a sync is in progress -- they will continue to be sent
69945
70151
  * to the registered targets at the time of the sync
69946
70152
  */
69947
- const targets = Array.from(__classPrivateFieldGet(this, _Log_targets, "f").values());
70153
+ const targets = [...this.targets];
69948
70154
  do {
69949
70155
  try {
69950
70156
  __classPrivateFieldSet(this, _Log_shouldSyncAgain, false, "f");
@@ -70055,6 +70261,7 @@ class LogTargetConsole {
70055
70261
  this.logLevel = config?.logLevel ?? 'ALL';
70056
70262
  __classPrivateFieldSet(this, _LogTargetConsole_console, config?.console ?? console, "f");
70057
70263
  this.filter = config?.filter ?? null;
70264
+ this.context = config?.context;
70058
70265
  }
70059
70266
  async emitLogs(logs) {
70060
70267
  for (const rawLog of logs) {
@@ -70080,9 +70287,10 @@ class LogTargetConsole {
70080
70287
  (0, never_1.assertNever)(log.level);
70081
70288
  }
70082
70289
  const requestID = log.options.currentRequestInfo.id;
70083
- __classPrivateFieldGet(this, _LogTargetConsole_console, "f")[method](`[${requestID}] ${log.level} ${log.from}:`, ...log.args);
70290
+ const contextPrefix = this.context ? Object.entries(this.context).map(([k, v]) => `${k}=${v}`).join(' ') + ' ' : '';
70291
+ __classPrivateFieldGet(this, _LogTargetConsole_console, "f")[method](`[${requestID}] ${contextPrefix}${log.level} ${log.from}:`, ...log.args);
70084
70292
  if (log.trace !== undefined) {
70085
- __classPrivateFieldGet(this, _LogTargetConsole_console, "f")[method](`[${requestID}] ${log.level} ${log.from} TRACE:`, log.trace);
70293
+ __classPrivateFieldGet(this, _LogTargetConsole_console, "f")[method](`[${requestID}] ${contextPrefix}${log.level} ${log.from} TRACE:`, log.trace);
70086
70294
  }
70087
70295
  }
70088
70296
  }
@@ -70640,7 +70848,6 @@ const asn1_1 = __webpack_require__(6045);
70640
70848
  const helper_1 = __webpack_require__(3208);
70641
70849
  const kv_memory_1 = __importDefault(__webpack_require__(1557));
70642
70850
  const vote_1 = __webpack_require__(1130);
70643
- const effects_1 = __webpack_require__(7346);
70644
70851
  const version_1 = __webpack_require__(5672);
70645
70852
  const defaultP2PConfig = {
70646
70853
  timeoutIdle: 10 /* s */ * 1000 /* ms */,
@@ -71851,12 +72058,34 @@ class P2PSwitch {
71851
72058
  const seenMessageIDPromise = this.config.kv.set('seenMessageIDs', id, Date.now(), {
71852
72059
  ttl: this.config.seenMessageTTL
71853
72060
  });
72061
+ /**
72062
+ * For 'add' messages, parse VoteStaple for filtering.
72063
+ * Data can be a VoteStaple object (already parsed with trustedValues from PubSub)
72064
+ * or a binary string that needs parsing.
72065
+ */
72066
+ let voteStaple;
72067
+ let sendData = data;
72068
+ if (type === 'add') {
72069
+ if (vote_1.VoteStaple.isInstance(data)) {
72070
+ voteStaple = data;
72071
+ // Convert back to binary for sending over the wire
72072
+ sendData = voteStaple.toString();
72073
+ }
72074
+ else if (typeof data === 'string') {
72075
+ voteStaple = new vote_1.VoteStaple(data);
72076
+ sendData = data;
72077
+ }
72078
+ else {
72079
+ this._log.error(`[${id}]`, 'Invalid data for add message, must be VoteStaple or string, received: ', typeof data);
72080
+ return (false);
72081
+ }
72082
+ }
71854
72083
  /**
71855
72084
  * Construct the message JSON
71856
72085
  */
71857
72086
  const messageString = JSON.stringify({
71858
72087
  id: id,
71859
- [type]: data,
72088
+ [type]: sendData,
71860
72089
  ttl: ttl
71861
72090
  });
71862
72091
  /**
@@ -71901,10 +72130,13 @@ class P2PSwitch {
71901
72130
  else {
71902
72131
  target = to;
71903
72132
  }
71904
- const passesFilter = await __classPrivateFieldGet(this, _P2PSwitch_instances, "m", _P2PSwitch_passesFilter).call(this, target, data);
71905
- if (!passesFilter) {
71906
- __classPrivateFieldGet(this, _P2PSwitch_localNode, "f").stats.incr('p2p', 'outgoingMessagesPeerFiltered');
71907
- return (false);
72133
+ // Only apply filter for 'add' messages with a VoteStaple
72134
+ if (voteStaple !== undefined) {
72135
+ const passesFilter = await __classPrivateFieldGet(this, _P2PSwitch_instances, "m", _P2PSwitch_passesFilter).call(this, target, voteStaple);
72136
+ if (!passesFilter) {
72137
+ __classPrivateFieldGet(this, _P2PSwitch_localNode, "f").stats.incr('p2p', 'outgoingMessagesPeerFiltered');
72138
+ return (false);
72139
+ }
71908
72140
  }
71909
72141
  /**
71910
72142
  * Allow greetings to be sent prior to identification of a peer
@@ -72142,18 +72374,22 @@ class P2PSwitch {
72142
72374
  return (false);
72143
72375
  }
72144
72376
  /**
72377
+ * Check if any registered filter matches the VoteStaple's touched accounts.
72378
+ * Uses the VoteStaple's touchedAccounts getter which may be pre-computed via trustedValues.
72379
+ *
72145
72380
  * TODO - make this private after refactoring websockets to handle higher load
72146
72381
  * https://github.com/KeetaNetwork/node/issues/785
72147
72382
  */
72148
- async haveAnyFilter(data) {
72383
+ async haveAnyFilter(voteStaple) {
72149
72384
  const kvFilters = await this.config.kv.getAll('messageFilters');
72385
+ const touched = voteStaple.touchedAccounts;
72150
72386
  for (const key in kvFilters) {
72151
72387
  const kvFilter = kvFilters[key];
72152
72388
  if (kvFilter && typeof kvFilter === 'string') {
72153
- const filter = account_1.default.fromPublicKeyAndType(kvFilter);
72154
- const voteStaple = new vote_1.VoteStaple(data);
72155
- const { touched } = (0, effects_1.computeEffectOfBlocks)(voteStaple.blocks);
72156
- return (touched.has(filter));
72389
+ const filterAccount = account_1.default.fromPublicKeyAndType(kvFilter);
72390
+ if (touched.has(filterAccount)) {
72391
+ return (true);
72392
+ }
72157
72393
  }
72158
72394
  }
72159
72395
  return (false);
@@ -72397,7 +72633,12 @@ async function _P2PSwitch_relayActiveState(conn) {
72397
72633
  * Perform peer exchange
72398
72634
  */
72399
72635
  promises.push(__classPrivateFieldGet(this, _P2PSwitch_instances, "m", _P2PSwitch_relayActiveState).call(this, from));
72400
- await Promise.allSettled(promises);
72636
+ const promiseResults = await Promise.allSettled(promises);
72637
+ for (const result of promiseResults) {
72638
+ if (result.status === 'rejected') {
72639
+ this._log.error('Error during greeting handling:', result.reason);
72640
+ }
72641
+ }
72401
72642
  return (true);
72402
72643
  }, _P2PSwitch_updateConnTimeout = function _P2PSwitch_updateConnTimeout(conn) {
72403
72644
  if (conn.peer) {
@@ -72450,7 +72691,12 @@ async function _P2PSwitch_relayActiveState(conn) {
72450
72691
  this._log.error('Failed to add peer:', addPeerError);
72451
72692
  }
72452
72693
  return (p2pConnection);
72453
- }, _P2PSwitch_passesFilter = async function _P2PSwitch_passesFilter(target, data) {
72694
+ }, _P2PSwitch_passesFilter =
72695
+ /**
72696
+ * Check if the VoteStaple passes the filter for the target connection.
72697
+ * Uses the VoteStaple's touchedAccounts getter which may be pre-computed via trustedValues.
72698
+ */
72699
+ async function _P2PSwitch_passesFilter(target, voteStaple) {
72454
72700
  let filter = __classPrivateFieldGet(this, _P2PSwitch_messageFilterCache, "f")[target.connString];
72455
72701
  if (filter === undefined) {
72456
72702
  const kvFilter = await this.config.kv.get('messageFilters', target.connString);
@@ -72461,9 +72707,7 @@ async function _P2PSwitch_relayActiveState(conn) {
72461
72707
  }
72462
72708
  // If there is a filter, only send effected accounts matching the filter
72463
72709
  if (filter) {
72464
- const voteStaple = new vote_1.VoteStaple(data);
72465
- const { touched } = (0, effects_1.computeEffectOfBlocks)(voteStaple.blocks);
72466
- return (touched.has(filter));
72710
+ return (voteStaple.touchedAccounts.has(filter));
72467
72711
  }
72468
72712
  return (true);
72469
72713
  };
@@ -73372,6 +73616,7 @@ const util_2 = __importDefault(__webpack_require__(9023));
73372
73616
  * native bindings.
73373
73617
  */
73374
73618
  const ASN1_ENCODE_DECODE_PARANOID = process.env['KEETANET_NODE_ASN1_ENCODE_DECODE_PARANOID'] === '1';
73619
+ const MAXIMUM_BIGINT_BYTE_LENGTH = 1024;
73375
73620
  function jsBigIntToBuffer(value) {
73376
73621
  /**
73377
73622
  * Convert value to Hex
@@ -73391,38 +73636,80 @@ function jsBigIntToBuffer(value) {
73391
73636
  if (valueStr.length % 2 !== 0) {
73392
73637
  valueStr = '0' + valueStr;
73393
73638
  }
73394
- /*
73395
- * Pad with a leading 0 byte if the MSB is 1 to avoid writing a
73396
- * negative number
73397
- */
73398
- const leader = valueStr.slice(0, 2);
73399
- const leaderValue = Number(`0x${leader}`);
73400
- if (!isNegative) {
73401
- if (leaderValue > 127) {
73402
- valueStr = '00' + valueStr;
73639
+ if (isNegative) {
73640
+ // Convert to minimal two's complement
73641
+ let n = BigInt('0x' + valueStr);
73642
+ n = -n;
73643
+ // Find minimal byte length
73644
+ const leader = Number('0x' + valueStr.slice(0, 2));
73645
+ let extraByteLength = 0;
73646
+ if (leader > 0x80) {
73647
+ extraByteLength = 1;
73648
+ }
73649
+ const byteLength = valueStr.length / 2 + extraByteLength;
73650
+ // Compute two's complement
73651
+ const mod = 1n << (BigInt(8 * byteLength));
73652
+ const twos = mod + n;
73653
+ let hex = twos.toString(16);
73654
+ if (hex.length % 2 !== 0) {
73655
+ hex = '0' + hex;
73403
73656
  }
73657
+ // Remove redundant leading ff bytes
73658
+ while (hex.length > 2 && hex.startsWith('ff') && Number.parseInt(hex.slice(2, 4), 16) >= 0x80) {
73659
+ hex = hex.slice(2);
73660
+ }
73661
+ valueStr = hex;
73404
73662
  }
73405
73663
  else {
73406
- if (leaderValue <= 127) {
73407
- valueStr = 'FF' + valueStr;
73664
+ const leader = valueStr.slice(0, 2);
73665
+ const leaderValue = Number(`0x${leader}`);
73666
+ if (leaderValue > 127) {
73667
+ valueStr = '00' + valueStr;
73408
73668
  }
73409
73669
  }
73670
+ if (valueStr.length / 2 >= MAXIMUM_BIGINT_BYTE_LENGTH) {
73671
+ throw (new Error(`jsBigIntToBuffer: Unable to encode bigint, too large, goes over maximum byte length of ${MAXIMUM_BIGINT_BYTE_LENGTH}`));
73672
+ }
73410
73673
  /*
73411
73674
  * Convert to a buffer
73412
73675
  */
73413
73676
  const valueBuffer = Buffer.from(valueStr, 'hex');
73414
73677
  return (valueBuffer);
73415
73678
  }
73416
- /* XXX:TODO: This does not correctly deal with negative values */
73679
+ function assertDERInteger(data) {
73680
+ const buf = Buffer.from(data.valueBlock.valueHex);
73681
+ // Check for zero-length integer
73682
+ if (buf.length === 0) {
73683
+ throw (new Error('Invalid DER: Integer has zero length'));
73684
+ }
73685
+ // Check for unnecessary leading zeros (positive numbers)
73686
+ // Only check multi-byte integers
73687
+ if (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0) {
73688
+ throw (new Error('Invalid DER: Integer has unnecessary leading zero byte'));
73689
+ }
73690
+ // Check for unnecessary leading 0xFF (negative numbers)
73691
+ // Only check multi-byte integers
73692
+ if (buf.length > 1 && buf[0] === 0xFF && (buf[1] & 0x80) !== 0) {
73693
+ throw (new Error('Invalid DER: Integer has unnecessary leading 0xFF byte'));
73694
+ }
73695
+ }
73417
73696
  function jsIntegerToBigInt(value) {
73418
- let valueStr;
73419
- if (value instanceof asn1js.Integer) {
73420
- valueStr = value.toString().split(':')[1].trim();
73697
+ if (typeof value === 'number') {
73698
+ return (BigInt(value));
73699
+ }
73700
+ assertDERInteger(value);
73701
+ const buf = Buffer.from(value.valueBlock.valueHex);
73702
+ const isNegative = (buf[0] & 0x80) !== 0;
73703
+ if (!isNegative) {
73704
+ return (BigInt('0x' + buf.toString('hex')));
73421
73705
  }
73422
73706
  else {
73423
- valueStr = value;
73707
+ // Two's complement: value = unsigned - 2^(8*len)
73708
+ const unsigned = BigInt('0x' + buf.toString('hex'));
73709
+ const bits = BigInt(buf.length * 8);
73710
+ const twosComp = unsigned - (1n << bits);
73711
+ return (twosComp);
73424
73712
  }
73425
- return (BigInt(valueStr));
73426
73713
  }
73427
73714
  function isASN1Object(input) {
73428
73715
  if (input === null || input === undefined || typeof input !== 'object') {
@@ -75425,7 +75712,9 @@ exports.Buffer = exports.BufferStorage = void 0;
75425
75712
  exports.DecodeBase32 = DecodeBase32;
75426
75713
  exports.EncodeBase32 = EncodeBase32;
75427
75714
  exports.DecodeBase64 = DecodeBase64;
75715
+ exports.DecodeBase64URL = DecodeBase64URL;
75428
75716
  exports.EncodeBase64 = EncodeBase64;
75717
+ exports.EncodeBase64URL = EncodeBase64URL;
75429
75718
  exports.ZlibInflate = ZlibInflate;
75430
75719
  exports.ZlibDeflate = ZlibDeflate;
75431
75720
  exports.ZlibInflateAsync = ZlibInflateAsync;
@@ -75445,8 +75734,10 @@ function DecodeBase32(data, length) {
75445
75734
  const retval = rfc4648_1.base32.parse(data, {
75446
75735
  loose: true
75447
75736
  });
75448
- if (retval.length !== length) {
75449
- throw (new Error(`Expected ${length} bytes, got ${retval.length}`));
75737
+ if (length !== undefined) {
75738
+ if (retval.length !== length) {
75739
+ throw (new Error(`Expected ${length} bytes, got ${retval.length}`));
75740
+ }
75450
75741
  }
75451
75742
  return (retval);
75452
75743
  }
@@ -75462,9 +75753,26 @@ function EncodeBase32(data) {
75462
75753
  function DecodeBase64(data) {
75463
75754
  return ((0, helper_1.bufferToArrayBuffer)(buffer_1.Buffer.from(data, 'base64')));
75464
75755
  }
75756
+ function DecodeBase64URL(data) {
75757
+ switch (data.length % 4) {
75758
+ case 2:
75759
+ data += '==';
75760
+ break;
75761
+ case 3:
75762
+ data += '=';
75763
+ break;
75764
+ }
75765
+ data = data.replace(/-/g, '+').replace(/_/g, '/');
75766
+ return (DecodeBase64(data));
75767
+ }
75465
75768
  function EncodeBase64(data) {
75466
75769
  return (buffer_1.Buffer.from(data).toString('base64'));
75467
75770
  }
75771
+ function EncodeBase64URL(data) {
75772
+ let output = EncodeBase64(data);
75773
+ output = output.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
75774
+ return (output);
75775
+ }
75468
75776
  function ZlibInflate(data, options) {
75469
75777
  return ((0, helper_1.bufferToArrayBuffer)(zlib_1.default.inflateSync(buffer_1.Buffer.from(data), options)));
75470
75778
  }
@@ -75480,34 +75788,65 @@ async function ZlibDeflateAsync(data, options = {}) {
75480
75788
  return ((0, helper_1.bufferToArrayBuffer)(buffer));
75481
75789
  }
75482
75790
  class BufferStorage {
75483
- constructor(key, length) {
75484
- _BufferStorage_key.set(this, void 0);
75485
- this.storageKind = 'GenericBuffer';
75791
+ static decodeKey(key, length) {
75792
+ if (key instanceof Uint8Array) {
75793
+ key = buffer_1.Buffer.from(key);
75794
+ }
75795
+ if (buffer_1.Buffer.isBuffer(key)) {
75796
+ if (length !== undefined && key.length !== length) {
75797
+ throw (new Error(`When decoding Buffer we got different number of bytes than expected (${key.length} expected ${length})`));
75798
+ }
75799
+ return ((0, helper_1.bufferToArrayBuffer)(key));
75800
+ }
75801
+ if (key instanceof ArrayBuffer) {
75802
+ if (length !== undefined && key.byteLength !== length) {
75803
+ throw (new Error(`When decoding ArrayBuffer we got different number of bytes than expected (${key.byteLength} expected ${length})`));
75804
+ }
75805
+ return (key);
75806
+ }
75486
75807
  if (typeof (key) === 'string') {
75487
75808
  /*
75488
75809
  * Convert from a hex-encoded string into a buffer
75489
75810
  */
75490
- const buffer_key = buffer_1.Buffer.from(key, 'hex');
75491
- if (buffer_key.length !== length) {
75492
- throw (new Error(`When decoding buffer we got different number of bytes than expected (${buffer_key.length} expected ${length})`));
75811
+ const keyBuffer = buffer_1.Buffer.from(key, 'hex');
75812
+ const keyUint8 = new Uint8Array(keyBuffer);
75813
+ const keyArrayBuffer = keyUint8.buffer;
75814
+ if (length !== undefined && keyBuffer.length !== length) {
75815
+ throw (new Error(`When decoding hex string we got different number of bytes than expected (${keyBuffer.length} expected ${length})`));
75493
75816
  }
75494
- __classPrivateFieldSet(this, _BufferStorage_key, buffer_key, "f");
75817
+ return (keyArrayBuffer);
75495
75818
  }
75496
75819
  else if (typeof key === 'bigint') {
75820
+ if (length === undefined) {
75821
+ throw (new Error('When decoding BigInt we need to know the expected length of the buffer'));
75822
+ }
75497
75823
  let value = key.toString(16);
75824
+ if (value.length % 2 !== 0) {
75825
+ value = '0' + value;
75826
+ }
75827
+ // Pad with zeros to length specified
75498
75828
  if (value.length > (length * 2)) {
75499
- throw (new Error(`When decoding BigInt we got different number of bytes than expected (${value.length} expected ${length * 2})`));
75829
+ throw (new Error(`When decoding BigInt we got different number of bytes than expected (${value.length / 2} expected ${length})`));
75500
75830
  }
75501
75831
  value = '0'.repeat(length * 2) + value;
75502
75832
  value = value.slice(length * 2 * -1);
75503
- __classPrivateFieldSet(this, _BufferStorage_key, buffer_1.Buffer.from(value, 'hex'), "f");
75833
+ const keyBuffer = buffer_1.Buffer.from(value, 'hex');
75834
+ const keyUint8 = new Uint8Array(keyBuffer);
75835
+ const keyArrayBuffer = keyUint8.buffer;
75836
+ return (keyArrayBuffer);
75504
75837
  }
75505
75838
  else {
75506
- if (buffer_1.Buffer.from(key).length !== length) {
75507
- throw (new Error(`When storing buffer we got different number of bytes than expected (${buffer_1.Buffer.from(key).length} expected ${length})`));
75508
- }
75509
- __classPrivateFieldSet(this, _BufferStorage_key, key, "f");
75839
+ return (key);
75840
+ }
75841
+ }
75842
+ constructor(key, length) {
75843
+ _BufferStorage_key.set(this, void 0);
75844
+ this.storageKind = 'GenericBuffer';
75845
+ const keyDecoded = BufferStorage.decodeKey(key, length);
75846
+ if (buffer_1.Buffer.from(keyDecoded).length !== length) {
75847
+ throw (new Error(`When storing buffer we got different number of bytes than expected (${buffer_1.Buffer.from(keyDecoded).length} expected ${length})`));
75510
75848
  }
75849
+ __classPrivateFieldSet(this, _BufferStorage_key, keyDecoded, "f");
75511
75850
  }
75512
75851
  get() {
75513
75852
  return (__classPrivateFieldGet(this, _BufferStorage_key, "f"));
@@ -75530,6 +75869,9 @@ class BufferStorage {
75530
75869
  throw (new Error(`Unsupported conversion: ${encoding}`));
75531
75870
  }
75532
75871
  }
75872
+ toJSON() {
75873
+ return (this.toString('hex'));
75874
+ }
75533
75875
  toBigInt() {
75534
75876
  const hex_value = `0x${this.toString('hex')}`;
75535
75877
  const value = BigInt(hex_value);
@@ -75606,7 +75948,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
75606
75948
  var __importDefault = (this && this.__importDefault) || function (mod) {
75607
75949
  return (mod && mod.__esModule) ? mod : { "default": mod };
75608
75950
  };
75609
- var _CertificateBuilder_params, _CertificateBundle_raw, _CertificateBundle_contents, _Certificate_instances, _Certificate_raw, _Certificate_hash, _Certificate_extensionsRaw, _Certificate_extensionsProcessed, _Certificate_finalizeConstructionCalled, _Certificate_processExtensionsInternal, _Certificate_processBaseExtensions, _Certificate_processBaseExtension, _Certificate_assertAllCriticalExtensionsProcessed, _Certificate_checkValid, _Certificate_checkIssued;
75951
+ var _CertificateBuilder_params, _CertificateBuilder_caPathLen, _CertificateBundle_raw, _CertificateBundle_contents, _Certificate_instances, _Certificate_raw, _Certificate_hash, _Certificate_extensionsRaw, _Certificate_extensionsProcessed, _Certificate_finalizeConstructionCalled, _Certificate_isSelfSigned, _Certificate_processExtensionsInternal, _Certificate_processBaseExtensions, _Certificate_parseKeyUsage, _Certificate_processBaseExtension, _Certificate_assertAllCriticalExtensionsProcessed, _Certificate_checkValid, _Certificate_checkIssued;
75610
75952
  Object.defineProperty(exports, "__esModule", ({ value: true }));
75611
75953
  exports.Certificate = exports.CertificateBundle = exports.CertificateHash = exports.CertificateBuilder = void 0;
75612
75954
  const ASN1 = __importStar(__webpack_require__(6045));
@@ -75616,7 +75958,9 @@ const helper_1 = __webpack_require__(3208);
75616
75958
  const HashLib = __importStar(__webpack_require__(7908));
75617
75959
  const crypto_1 = __importDefault(__webpack_require__(6982));
75618
75960
  const buffer_1 = __webpack_require__(3310);
75961
+ const conversion_1 = __webpack_require__(2360);
75619
75962
  const certificate_1 = __importDefault(__webpack_require__(9890));
75963
+ const util_1 = __webpack_require__(9023);
75620
75964
  /** @internal */
75621
75965
  const CertificateSchemaInternal = [
75622
75966
  /* TBS Certificate */
@@ -75744,6 +76088,7 @@ const defaultHashName = HashLib.HashFunctionName;
75744
76088
  class CertificateBuilder {
75745
76089
  constructor(params) {
75746
76090
  _CertificateBuilder_params.set(this, void 0);
76091
+ _CertificateBuilder_caPathLen.set(this, void 0);
75747
76092
  __classPrivateFieldSet(this, _CertificateBuilder_params, {
75748
76093
  ...params
75749
76094
  }, "f");
@@ -75803,6 +76148,12 @@ class CertificateBuilder {
75803
76148
  account.publicKeyAndType
75804
76149
  ]), 20)));
75805
76150
  }
76151
+ /**
76152
+ * Set the CA path length
76153
+ */
76154
+ setCAPathLen(pathLen) {
76155
+ __classPrivateFieldSet(this, _CertificateBuilder_caPathLen, pathLen, "f");
76156
+ }
75806
76157
  /**
75807
76158
  * Produce the extensions to include in this certificate
75808
76159
  */
@@ -75825,13 +76176,17 @@ class CertificateBuilder {
75825
76176
  isCertificateAuthority = params.isCA;
75826
76177
  }
75827
76178
  if (isCertificateAuthority) {
76179
+ const basicConstraints = [true];
76180
+ if (__classPrivateFieldGet(this, _CertificateBuilder_caPathLen, "f") !== undefined) {
76181
+ basicConstraints.push(__classPrivateFieldGet(this, _CertificateBuilder_caPathLen, "f"));
76182
+ }
75828
76183
  extensions.push(
75829
76184
  /** Extension: Basic Constraints (CA) */
75830
- CertificateBuilder.extension('2.5.29.19', [true], true),
76185
+ CertificateBuilder.extension('2.5.29.19', basicConstraints, true),
75831
76186
  /** Extension: Key Usage */
75832
76187
  CertificateBuilder.extension('2.5.29.15', {
75833
76188
  type: 'bitstring',
75834
- value: Buffer.from([0
76189
+ value: Buffer.from([0 /* encipherOnly and decipherOnly */
75835
76190
  | (1 << 1) /* CRL Sign */
75836
76191
  | (1 << 2) /* Cert Sign */
75837
76192
  | (0 << 3) /* Key Agreement */
@@ -75847,7 +76202,7 @@ class CertificateBuilder {
75847
76202
  /** Extension: Key Usage */
75848
76203
  CertificateBuilder.extension('2.5.29.15', {
75849
76204
  type: 'bitstring',
75850
- value: Buffer.from([0
76205
+ value: Buffer.from([0 /* encipherOnly and decipherOnly */
75851
76206
  | (0 << 1) /* CRL Sign */
75852
76207
  | (0 << 2) /* Cert Sign */
75853
76208
  | (0 << 3) /* Key Agreement */
@@ -76048,7 +76403,7 @@ class CertificateBuilder {
76048
76403
  }
76049
76404
  }
76050
76405
  exports.CertificateBuilder = CertificateBuilder;
76051
- _CertificateBuilder_params = new WeakMap();
76406
+ _CertificateBuilder_params = new WeakMap(), _CertificateBuilder_caPathLen = new WeakMap();
76052
76407
  /**
76053
76408
  * Certificate hash
76054
76409
  */
@@ -76084,6 +76439,10 @@ class CertificateBundle {
76084
76439
  constructor(input) {
76085
76440
  _CertificateBundle_raw.set(this, void 0);
76086
76441
  _CertificateBundle_contents.set(this, void 0);
76442
+ // If input is toJSON output
76443
+ if (typeof input === 'object' && 'certificates' in input) {
76444
+ input = input.certificates;
76445
+ }
76087
76446
  if (CertificateBundle.isInstance(input)) {
76088
76447
  __classPrivateFieldSet(this, _CertificateBundle_raw, input.getDER(), "f");
76089
76448
  }
@@ -76155,6 +76514,17 @@ class CertificateBundle {
76155
76514
  exports.CertificateBundle = CertificateBundle;
76156
76515
  _CertificateBundle_raw = new WeakMap(), _CertificateBundle_contents = new WeakMap();
76157
76516
  CertificateBundle.isInstance = (0, helper_1.checkableGenerator)(CertificateBundle);
76517
+ const keyUsageBits = [
76518
+ 'digitalSignature',
76519
+ 'nonRepudiation',
76520
+ 'keyEncipherment',
76521
+ 'dataEncipherment',
76522
+ 'keyAgreement',
76523
+ 'keyCertSign',
76524
+ 'cRLSign',
76525
+ 'encipherOnly',
76526
+ 'decipherOnly'
76527
+ ];
76158
76528
  class Certificate {
76159
76529
  /**
76160
76530
  * Is a certificate object?
@@ -76190,6 +76560,10 @@ class Certificate {
76190
76560
  * Has finalizeConstruction been called?
76191
76561
  */
76192
76562
  _Certificate_finalizeConstructionCalled.set(this, false);
76563
+ /**
76564
+ * Cached value for isSelfSigned
76565
+ */
76566
+ _Certificate_isSelfSigned.set(this, void 0);
76193
76567
  /*
76194
76568
  * If a certificate is provided, then extract the raw
76195
76569
  * certificate and process it -- do not merge any of
@@ -76199,6 +76573,18 @@ class Certificate {
76199
76573
  // For use in browser, have to use toDER instead of accessing #raw directly
76200
76574
  input = input.toDER();
76201
76575
  }
76576
+ else if (!util_1.types.isArrayBuffer(input) && !Buffer.isBuffer(input) && typeof input === 'object') {
76577
+ /**
76578
+ * If certificate input is output from toJSON then reconstruct from $binary
76579
+ * $binary is PEM format which will get parsed later
76580
+ */
76581
+ if ('$binary' in input && input.$binary !== undefined) {
76582
+ input = input.$binary;
76583
+ }
76584
+ else {
76585
+ throw (new Error('Certificate from JSON should include $binary'));
76586
+ }
76587
+ }
76202
76588
  /*
76203
76589
  * Define an object type ID as an un-enumerable property to
76204
76590
  * ensure that we can identify this object as an instance of
@@ -76365,7 +76751,11 @@ class Certificate {
76365
76751
  * Verifies that a certificate is self-signed
76366
76752
  */
76367
76753
  isSelfSigned() {
76368
- return (this.checkIssued(this));
76754
+ if (__classPrivateFieldGet(this, _Certificate_isSelfSigned, "f") !== undefined) {
76755
+ return (__classPrivateFieldGet(this, _Certificate_isSelfSigned, "f"));
76756
+ }
76757
+ __classPrivateFieldSet(this, _Certificate_isSelfSigned, this.checkIssued(this), "f");
76758
+ return (__classPrivateFieldGet(this, _Certificate_isSelfSigned, "f"));
76369
76759
  }
76370
76760
  /**
76371
76761
  * Verifies that the certificate is was signed by the given account or certificate
@@ -76430,6 +76820,54 @@ class Certificate {
76430
76820
  });
76431
76821
  return (verified);
76432
76822
  }
76823
+ /**
76824
+ * Verify that a given chain meets the depth requirements
76825
+ */
76826
+ static verifyChainDepth(chain) {
76827
+ if (chain.length === 0) {
76828
+ return ({ valid: false, reason: 'Empty chain' });
76829
+ }
76830
+ const depthByIssuer = new Map();
76831
+ // Traverse from root to leaf
76832
+ for (let i = 0; i < chain.length; i++) {
76833
+ const certificate = chain[i];
76834
+ // Leaf certificates are still validated for total depth but excluded from other checks
76835
+ const isLeaf = i === chain.length - 1;
76836
+ const basicConstraints = certificate.baseExtensions?.basicConstraints;
76837
+ // basicConstraints are required for CA if it's not a leaf
76838
+ if (!isLeaf && !basicConstraints) {
76839
+ return ({ valid: false, reason: `Missing basicConstraints in certificate: ${certificate.subject}` });
76840
+ }
76841
+ const [isCA, pathLenConstraint] = basicConstraints ?? [false, undefined];
76842
+ // Root and intermediates should be a CA
76843
+ if (!isLeaf && !isCA) {
76844
+ return ({ valid: false, reason: `Non-CA certificate in chain: ${certificate.subject}` });
76845
+ }
76846
+ // CA should have usage set to be able to sign
76847
+ const keyUsage = certificate.baseExtensions?.keyUsage;
76848
+ if (!isLeaf && keyUsage && !keyUsage.keyCertSign) {
76849
+ return ({ valid: false, reason: `CA certificate missing keyCertSign in keyUsage: ${certificate.subject}` });
76850
+ }
76851
+ // Skip constraint checks if self-signed
76852
+ if (!certificate.isSelfSigned()) {
76853
+ // Validate against all existing constraints
76854
+ for (const [issuer, remainingDepth] of depthByIssuer.entries()) {
76855
+ if (remainingDepth < 0n) {
76856
+ return ({
76857
+ valid: false,
76858
+ reason: `Path length constraint exceeded for CA: ${issuer.subject} on Certificate: ${certificate.subject}`
76859
+ });
76860
+ }
76861
+ depthByIssuer.set(issuer, remainingDepth - 1n);
76862
+ }
76863
+ }
76864
+ // If this cert is a CA and has a pathLenConstraint, track it
76865
+ if (pathLenConstraint !== undefined) {
76866
+ depthByIssuer.set(certificate, pathLenConstraint);
76867
+ }
76868
+ }
76869
+ return ({ valid: true });
76870
+ }
76433
76871
  /**
76434
76872
  * Asserts provided certificates can construct a valid graph with no loops or orphans, and that all provided certificates can reach the root, or current certificate
76435
76873
  * @param certificates Additional intermediate certificates to verify
@@ -76490,9 +76928,6 @@ class Certificate {
76490
76928
  }
76491
76929
  }
76492
76930
  }
76493
- /**
76494
- * Verify against a given certificate store
76495
- */
76496
76931
  verifyChain(store, _ignore_seenCerts /* XXX:TODO */) {
76497
76932
  /*
76498
76933
  * Check to see if the certificate is signed by any of the Root CAs
@@ -76505,10 +76940,15 @@ class Certificate {
76505
76940
  if (retval !== null) {
76506
76941
  return;
76507
76942
  }
76508
- const checkIssued = this.checkIssued(rootCertificate, true);
76943
+ const checkIssued = __classPrivateFieldGet(this, _Certificate_instances, "m", _Certificate_checkIssued).call(this, rootCertificate);
76509
76944
  if (checkIssued.issued) {
76510
76945
  if (rootCertificate.checkValid(this.moment)) {
76511
- retval = [rootCertificate];
76946
+ const checkRetval = [rootCertificate];
76947
+ const validChain = Certificate.verifyChainDepth([...checkRetval, this]);
76948
+ if (validChain.valid) {
76949
+ retval = checkRetval;
76950
+ return;
76951
+ }
76512
76952
  }
76513
76953
  }
76514
76954
  });
@@ -76523,12 +76963,17 @@ class Certificate {
76523
76963
  if (retval !== null) {
76524
76964
  return;
76525
76965
  }
76526
- if (this.checkIssued(intermediateCertificate)) {
76966
+ const checkIssued = __classPrivateFieldGet(this, _Certificate_instances, "m", _Certificate_checkIssued).call(this, intermediateCertificate);
76967
+ if (checkIssued.issued) {
76527
76968
  if (intermediateCertificate.checkValid(this.moment)) {
76528
- const moreChain = intermediateCertificate.verifyChain(store /* , seenCerts XXX:TODO */);
76969
+ const moreChain = intermediateCertificate.verifyChain(store, undefined /* seenCerts XXX:TODO */);
76529
76970
  if (moreChain !== null) {
76530
- retval = [...moreChain, intermediateCertificate];
76531
- return;
76971
+ const checkRetval = [...moreChain, intermediateCertificate];
76972
+ const validChain = Certificate.verifyChainDepth([...checkRetval, this]);
76973
+ if (validChain.valid) {
76974
+ retval = checkRetval;
76975
+ return;
76976
+ }
76532
76977
  }
76533
76978
  }
76534
76979
  }
@@ -76689,7 +77134,8 @@ class Certificate {
76689
77134
  this.assertConstructed();
76690
77135
  // XXX:TODO Fix this type
76691
77136
  const additionalFields = {};
76692
- if (options?.addBinary) {
77137
+ // Default to including $binary so we can reconstruct this cert from PEM
77138
+ if (options === undefined || options.addBinary !== false) {
76693
77139
  additionalFields['$binary'] = this.toPEM();
76694
77140
  }
76695
77141
  if (includeChain && this.chain !== undefined) {
@@ -76697,7 +77143,7 @@ class Certificate {
76697
77143
  return (chainCert.toJSON({ ...options, addBinary: false }, false));
76698
77144
  });
76699
77145
  }
76700
- return ({
77146
+ return ((0, conversion_1.toJSONSerializable)({
76701
77147
  serial: this.serial,
76702
77148
  notBefore: this.notBefore,
76703
77149
  notAfter: this.notAfter,
@@ -76709,11 +77155,11 @@ class Certificate {
76709
77155
  issuerDN: fromDNSequence(this.issuerDNSet),
76710
77156
  $hash: this.hash(),
76711
77157
  ...additionalFields
76712
- });
77158
+ }));
76713
77159
  }
76714
77160
  }
76715
77161
  exports.Certificate = Certificate;
76716
- _Certificate_raw = new WeakMap(), _Certificate_hash = new WeakMap(), _Certificate_extensionsRaw = new WeakMap(), _Certificate_extensionsProcessed = new WeakMap(), _Certificate_finalizeConstructionCalled = new WeakMap(), _Certificate_instances = new WeakSet(), _Certificate_processExtensionsInternal = function _Certificate_processExtensionsInternal(extensions, processedSet, handleExtension) {
77162
+ _Certificate_raw = new WeakMap(), _Certificate_hash = new WeakMap(), _Certificate_extensionsRaw = new WeakMap(), _Certificate_extensionsProcessed = new WeakMap(), _Certificate_finalizeConstructionCalled = new WeakMap(), _Certificate_isSelfSigned = new WeakMap(), _Certificate_instances = new WeakSet(), _Certificate_processExtensionsInternal = function _Certificate_processExtensionsInternal(extensions, processedSet, handleExtension) {
76717
77163
  if (extensions === undefined) {
76718
77164
  return;
76719
77165
  }
@@ -76753,6 +77199,32 @@ _Certificate_raw = new WeakMap(), _Certificate_hash = new WeakMap(), _Certificat
76753
77199
  seenExtensions.add(id);
76754
77200
  }
76755
77201
  __classPrivateFieldGet(this, _Certificate_instances, "m", _Certificate_processExtensionsInternal).call(this, extensions, __classPrivateFieldGet(this, _Certificate_extensionsProcessed, "f"), __classPrivateFieldGet(this, _Certificate_instances, "m", _Certificate_processBaseExtension).bind(this));
77202
+ }, _Certificate_parseKeyUsage = function _Certificate_parseKeyUsage(buffer, unusedBits = 0) {
77203
+ const result = {};
77204
+ let bitIndex = 0;
77205
+ for (let byteIndex = 0; byteIndex < buffer.length; byteIndex++) {
77206
+ const byte = buffer[byteIndex];
77207
+ let bitsToRead = 8;
77208
+ // If it's the last byte, subtract unused bits
77209
+ if (byteIndex === buffer.length - 1 && unusedBits > 0) {
77210
+ bitsToRead -= unusedBits;
77211
+ }
77212
+ for (let bit = 7; bit >= 8 - bitsToRead; bit--) {
77213
+ if (bitIndex >= keyUsageBits.length) {
77214
+ break;
77215
+ }
77216
+ const usageName = keyUsageBits[bitIndex];
77217
+ const isSet = (byte & (1 << bit)) !== 0;
77218
+ result[usageName] = isSet;
77219
+ bitIndex++;
77220
+ }
77221
+ }
77222
+ // Fill in remaining with false
77223
+ while (bitIndex < keyUsageBits.length) {
77224
+ result[keyUsageBits[bitIndex]] = false;
77225
+ bitIndex++;
77226
+ }
77227
+ return (result);
76756
77228
  }, _Certificate_processBaseExtension = function _Certificate_processBaseExtension(id, value) {
76757
77229
  if (this.baseExtensions === undefined) {
76758
77230
  throw (new Error('internal error: baseExtensions not defined'));
@@ -76771,9 +77243,12 @@ _Certificate_raw = new WeakMap(), _Certificate_hash = new WeakMap(), _Certificat
76771
77243
  return (true);
76772
77244
  }
76773
77245
  /** Extension: Key Usage */
76774
- case '2.5.29.15':
77246
+ case '2.5.29.15': {
76775
77247
  /* XXX:TODO */
77248
+ const bits = new ASN1.BufferStorageASN1(value, ASN1.ValidateASN1.IsBitString).getASN1();
77249
+ this.baseExtensions.keyUsage = __classPrivateFieldGet(this, _Certificate_instances, "m", _Certificate_parseKeyUsage).call(this, bits.value, bits.unusedBits);
76776
77250
  return (true);
77251
+ }
76777
77252
  /** Extension: Authority Key Identifier */
76778
77253
  case '2.5.29.35':
76779
77254
  this.baseExtensions.authorityKeyIdentifier = new ASN1.BufferStorageASN1(value, [{ choice: [
@@ -76865,13 +77340,22 @@ _Certificate_raw = new WeakMap(), _Certificate_hash = new WeakMap(), _Certificat
76865
77340
  * Verify that the issuer has the authority to issue the
76866
77341
  * certificate (basic constraints)
76867
77342
  */
76868
- /* XXX:TODO */
77343
+ if (issuer.baseExtensions?.basicConstraints === undefined) {
77344
+ return ({ issued: false, reason: 'Issuer certificate lacks the ability to sign certificates (missing basicConstraints)' });
77345
+ }
77346
+ if (!issuer.baseExtensions.basicConstraints[0]) {
77347
+ return ({ issued: false, reason: 'Issuer certificate lacks the ability to sign certificates (basicConstraints is false)' });
77348
+ }
76869
77349
  /**
76870
77350
  * If the key usage extension is present, then check that the
76871
77351
  * issuer key usage is consistent with the certificate being
76872
77352
  * a CA
76873
77353
  */
76874
77354
  /* XXX:TODO */
77355
+ const keyUsage = issuer.baseExtensions?.keyUsage;
77356
+ if (keyUsage && !keyUsage.keyCertSign) {
77357
+ return ({ issued: false, reason: `CA certificate missing keyCertSign in keyUsage` });
77358
+ }
76875
77359
  /**
76876
77360
  * Verify the signature
76877
77361
  */
@@ -78185,7 +78669,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
78185
78669
  var __importDefault = (this && this.__importDefault) || function (mod) {
78186
78670
  return (mod && mod.__esModule) ? mod : { "default": mod };
78187
78671
  };
78188
- var _VoteBlockHashMap_instances, _VoteBlockHashMap_valueMap, _VoteBlockHashMap_keyMap, _VoteBlockHashMap_getLookupKey, _a, _VoteLikeBase_vote, _VoteLikeBase_options, _VoteLikeBase__hash, _VoteLikeBase__blocksHash, _VoteBlockBundle_value, _VoteBlockBundle_valueCompressed, _VoteBlockBundle__hash, _VoteBlockBundle__blocksHash, _BaseVoteBuilder_account, _BaseVoteBuilder_blocks, _BaseVoteBuilder_fee;
78672
+ var _VoteBlockHashMap_instances, _VoteBlockHashMap_valueMap, _VoteBlockHashMap_keyMap, _VoteBlockHashMap_getLookupKey, _a, _VoteLikeBase_vote, _VoteLikeBase_options, _VoteLikeBase__hash, _VoteLikeBase__blocksHash, _VoteBlockBundle_instances, _VoteBlockBundle_value, _VoteBlockBundle_valueCompressed, _VoteBlockBundle__hash, _VoteBlockBundle__blocksHash, _VoteBlockBundle__blockHashes, _VoteBlockBundle__votes, _VoteBlockBundle__blocks, _VoteBlockBundle__touchedAccounts, _VoteBlockBundle_votesRaw, _VoteBlockBundle_blocksRaw, _VoteBlockBundle_options, _VoteBlockBundle__asn1Validated, _VoteBlockBundle__blocksAndVotesRaw_get, _VoteBlockBundle__blocksRaw_get, _VoteBlockBundle__votesRaw_get, _VoteBlockBundle_blockHashes_get, _BaseVoteBuilder_account, _BaseVoteBuilder_blocks, _BaseVoteBuilder_fee;
78189
78673
  Object.defineProperty(exports, "__esModule", ({ value: true }));
78190
78674
  exports.Testing = exports.VoteQuoteBuilder = exports.VoteBuilder = exports.BaseVoteBuilder = exports.VoteStaple = exports.VoteBlockBundle = exports.VoteQuote = exports.Vote = exports.PossiblyExpiredVote = exports.VoteBlockHash = exports.VoteBlockHashMap = void 0;
78191
78675
  /*
@@ -78200,9 +78684,11 @@ const account_1 = __importStar(__webpack_require__(9415));
78200
78684
  const asn1_1 = __webpack_require__(6045);
78201
78685
  const helper_1 = __webpack_require__(3208);
78202
78686
  const zlib_1 = __importDefault(__webpack_require__(3106));
78687
+ const conversion_1 = __webpack_require__(2360);
78203
78688
  const buffer_1 = __webpack_require__(3310);
78204
78689
  const util_1 = __webpack_require__(9023);
78205
78690
  const vote_1 = __importDefault(__webpack_require__(3689));
78691
+ const effects_1 = __webpack_require__(7346);
78206
78692
  class VoteHash extends buffer_1.BufferStorage {
78207
78693
  constructor(blockhash) {
78208
78694
  super(blockhash, 32);
@@ -78935,7 +79421,7 @@ class VoteLikeBase {
78935
79421
  if (this.quote !== undefined) {
78936
79422
  additionalFields['quote'] = this.quote;
78937
79423
  }
78938
- return ({
79424
+ return ((0, conversion_1.toJSONSerializable)({
78939
79425
  issuer: this.issuer,
78940
79426
  serial: this.serial,
78941
79427
  blocks: this.blocks,
@@ -78947,7 +79433,7 @@ class VoteLikeBase {
78947
79433
  $uid: this.$uid,
78948
79434
  $id: this.$id,
78949
79435
  ...additionalFields
78950
- });
79436
+ }));
78951
79437
  }
78952
79438
  expirationCheckMoment() {
78953
79439
  let now;
@@ -79093,7 +79579,16 @@ class VoteBlockBundle {
79093
79579
  ]);
79094
79580
  const buffer = Buffer.from(encoded.toBER(false));
79095
79581
  const compressedBuffer = zlib_1.default.deflateSync(buffer);
79096
- return (new this(compressedBuffer, voteOptions));
79582
+ return (new this(compressedBuffer, {
79583
+ trustedValues: {
79584
+ blocksMap: Object.fromEntries(blocks.map(function (block) {
79585
+ return ([block.hash.toString(), block]);
79586
+ })),
79587
+ blocks: blocksOrdered,
79588
+ votes: votesOrdered
79589
+ },
79590
+ ...voteOptions
79591
+ }));
79097
79592
  }
79098
79593
  /**
79099
79594
  * Convert a list of Votes and Blocks into a VoteStaple
@@ -79225,10 +79720,39 @@ class VoteBlockBundle {
79225
79720
  * Construct a new staple from a message buffer
79226
79721
  */
79227
79722
  constructor(votesStapled, voteOptions = {}) {
79723
+ _VoteBlockBundle_instances.add(this);
79228
79724
  _VoteBlockBundle_value.set(this, void 0);
79229
79725
  _VoteBlockBundle_valueCompressed.set(this, void 0);
79230
79726
  _VoteBlockBundle__hash.set(this, void 0);
79231
79727
  _VoteBlockBundle__blocksHash.set(this, void 0);
79728
+ _VoteBlockBundle__blockHashes.set(this, void 0);
79729
+ _VoteBlockBundle__votes.set(this, void 0);
79730
+ _VoteBlockBundle__blocks.set(this, void 0);
79731
+ _VoteBlockBundle__touchedAccounts.set(this, void 0);
79732
+ _VoteBlockBundle_votesRaw.set(this, void 0);
79733
+ _VoteBlockBundle_blocksRaw.set(this, void 0);
79734
+ _VoteBlockBundle_options.set(this, void 0);
79735
+ _VoteBlockBundle__asn1Validated.set(this, false);
79736
+ this._votesValidated = false;
79737
+ if (voteOptions.trustedValues?.blocksMap) {
79738
+ __classPrivateFieldSet(this, _VoteBlockBundle__blockHashes, voteOptions.trustedValues.blocksMap, "f");
79739
+ }
79740
+ if (voteOptions.trustedValues?.blocks) {
79741
+ __classPrivateFieldSet(this, _VoteBlockBundle__blocks, voteOptions.trustedValues.blocks, "f");
79742
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f") && __classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f").length === 0) {
79743
+ throw (new vote_1.default('VOTE_STAPLE_INVALID_CONSTRUCTION', 'Vote Staples must contain at least one block'));
79744
+ }
79745
+ }
79746
+ if (voteOptions.trustedValues?.votes) {
79747
+ __classPrivateFieldSet(this, _VoteBlockBundle__votes, voteOptions.trustedValues.votes, "f");
79748
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__votes, "f") && __classPrivateFieldGet(this, _VoteBlockBundle__votes, "f").length === 0) {
79749
+ throw (new vote_1.default('VOTE_STAPLE_INVALID_CONSTRUCTION', 'Vote Staples must contain at least one vote'));
79750
+ }
79751
+ }
79752
+ if (voteOptions.trustedValues?.touchedAccounts) {
79753
+ __classPrivateFieldSet(this, _VoteBlockBundle__touchedAccounts, voteOptions.trustedValues.touchedAccounts, "f");
79754
+ }
79755
+ __classPrivateFieldSet(this, _VoteBlockBundle_options, voteOptions, "f");
79232
79756
  if (typeof votesStapled === 'string') {
79233
79757
  votesStapled = Buffer.from(votesStapled, 'base64');
79234
79758
  }
@@ -79260,83 +79784,21 @@ class VoteBlockBundle {
79260
79784
  __classPrivateFieldSet(this, _VoteBlockBundle_value, votesStapled, "f");
79261
79785
  }
79262
79786
  /**
79263
- * Parse BER encoded data into objects
79264
- */
79265
- const data = (0, asn1_1.ASN1toJS)(__classPrivateFieldGet(this, _VoteBlockBundle_value, "f"));
79266
- if (!Array.isArray(data)) {
79267
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must be a Sequence'));
79268
- }
79269
- if (data.length !== 2) {
79270
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must contain exactly 2 elements (votes, and blocks)'));
79271
- }
79272
- const [blocksRaw, votesRaw] = data;
79273
- if (!Array.isArray(blocksRaw) || !Array.isArray(votesRaw)) {
79274
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must contain exactly 2 elements (votes, and blocks)'));
79275
- }
79276
- if (blocksRaw.length < 1) {
79277
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE_BLOCKS_AT_LEAST_ONE', 'There must be at least 1 block'));
79278
- }
79279
- /**
79280
- * List of blocks
79281
- */
79282
- const blocksUnsorted = blocksRaw.map(function (blockData) {
79283
- if (!(Buffer.isBuffer(blockData))) {
79284
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE_BLOCKS', 'Each block must be an Octet String'));
79285
- }
79286
- return (new block_1.Block(blockData));
79287
- });
79288
- if (votesRaw.length < 1) {
79289
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE_VOTES_AT_LEAST_ONE', 'There must be at least one vote'));
79290
- }
79291
- /**
79292
- * Get a list of every block hash
79293
- */
79294
- const blockHashes = {};
79295
- for (const block of blocksUnsorted) {
79296
- blockHashes[block.hash.toString()] = block;
79297
- }
79298
- /*
79299
- * Ensure blocks are sorted the same way as the vote
79300
- */
79301
- this.votes = votesRaw.map(function (voteData) {
79302
- if (!(Buffer.isBuffer(voteData))) {
79303
- throw (new vote_1.default('VOTE_MALFORMED_STAPLE_VOTES', 'Each vote must be an Octet String'));
79304
- }
79305
- const vote = new Vote(voteData, voteOptions);
79306
- if (vote.blocks.length !== blocksUnsorted.length) {
79307
- throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_COUNT', `Each vote must vote on the exact set of blocks being stapled (same number) (vote: ${vote.blocks.length}; blocks: ${blocksUnsorted.length})`));
79308
- }
79309
- for (const voteBlockHash of vote.blocks) {
79310
- const voteBlockHashCheck = blockHashes[voteBlockHash.toString()];
79311
- if (voteBlockHashCheck === undefined) {
79312
- throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_MISSING', `Each vote must be on the exact set of blocks being stapled (missing ${voteBlockHash.toString()})`));
79313
- }
79314
- }
79315
- return (vote);
79316
- });
79317
- /**
79318
- * Order blocks by the vote ordering
79319
- */
79320
- this.blocks = this.votes[0].blocks.map(function (blockHash) {
79321
- return (blockHashes[blockHash.toString()]);
79322
- });
79323
- /**
79324
- * Ensure every vote has the block hashes in the same order
79787
+ * Force evaluation of votes and blocks unless lazy loading is specified
79325
79788
  */
79326
- for (const vote of this.votes) {
79327
- for (let blockHashIndex = 0; blockHashIndex < vote.blocks.length; blockHashIndex++) {
79328
- const voteBlockHash = vote.blocks[blockHashIndex];
79329
- const stapleBlockHash = this.blocks[blockHashIndex];
79330
- if (voteBlockHash.toString() !== stapleBlockHash.hash.toString()) {
79331
- throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_ORDER', 'All votes must list blocks in the same order'));
79332
- }
79333
- }
79789
+ if (voteOptions.lazy !== true) {
79790
+ void this.votes;
79791
+ void this.blocks;
79792
+ void __classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__blocksAndVotesRaw_get);
79334
79793
  }
79335
79794
  }
79336
79795
  /**
79337
79796
  * Get the serialized version
79338
79797
  */
79339
79798
  toBytes(uncompressed) {
79799
+ if (!__classPrivateFieldGet(this, _VoteBlockBundle__asn1Validated, "f")) {
79800
+ void __classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__blocksAndVotesRaw_get);
79801
+ }
79340
79802
  if (uncompressed) {
79341
79803
  return (__classPrivateFieldGet(this, _VoteBlockBundle_value, "f"));
79342
79804
  }
@@ -79355,7 +79817,7 @@ class VoteBlockBundle {
79355
79817
  */
79356
79818
  get hash() {
79357
79819
  if (!__classPrivateFieldGet(this, _VoteBlockBundle__hash, "f")) {
79358
- const canonicalVoteStaple = VoteBlockBundle.fromVotesAndBlocks(this.votes, this.blocks);
79820
+ const canonicalVoteStaple = VoteBlockBundle.fromVotesAndBlocks(this.votes, this.blocks, { lazy: true });
79359
79821
  const hash = (0, hash_1.Hash)(Buffer.from(canonicalVoteStaple.toBytes(true)));
79360
79822
  __classPrivateFieldSet(this, _VoteBlockBundle__hash, new VoteStapleHash(hash), "f");
79361
79823
  }
@@ -79420,21 +79882,163 @@ class VoteBlockBundle {
79420
79882
  ...additionalFields
79421
79883
  });
79422
79884
  }
79885
+ get votes() {
79886
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__votes, "f") !== undefined && this._votesValidated) {
79887
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__votes, "f"));
79888
+ }
79889
+ const voteOptions = __classPrivateFieldGet(this, _VoteBlockBundle_options, "f");
79890
+ const blocksUnsorted = Object.values(__classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle_blockHashes_get));
79891
+ /*
79892
+ * If votes are already known, use them otherwise parse from raw data
79893
+ */
79894
+ const newVotes = __classPrivateFieldGet(this, _VoteBlockBundle__votes, "f") ?? __classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__votesRaw_get).map((voteData) => {
79895
+ if (!(Buffer.isBuffer(voteData))) {
79896
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE_VOTES', 'Each vote must be an Octet String'));
79897
+ }
79898
+ const vote = new Vote(voteData, voteOptions);
79899
+ return (vote);
79900
+ });
79901
+ /**
79902
+ * Validate each vote and ensure they all vote on the same block hashes in order
79903
+ */
79904
+ let stapleBlockHashes;
79905
+ for (const vote of newVotes) {
79906
+ if (vote.blocks.length !== blocksUnsorted.length) {
79907
+ throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_COUNT', `Each vote must vote on the exact set of blocks being stapled (same number) (vote: ${vote.blocks.length}; blocks: ${blocksUnsorted.length})`));
79908
+ }
79909
+ for (const voteBlockHash of vote.blocks) {
79910
+ const voteBlockHashCheck = __classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle_blockHashes_get)[voteBlockHash.toString()];
79911
+ if (voteBlockHashCheck === undefined) {
79912
+ throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_MISSING', `Each vote must be on the exact set of blocks being stapled (missing ${voteBlockHash.toString()})`));
79913
+ }
79914
+ }
79915
+ if (stapleBlockHashes === undefined) {
79916
+ stapleBlockHashes = vote.blocks;
79917
+ continue;
79918
+ }
79919
+ for (let blockHashIndex = 0; blockHashIndex < vote.blocks.length; blockHashIndex++) {
79920
+ const voteBlocksHash = vote.blocks[blockHashIndex];
79921
+ const stapleBlockHash = stapleBlockHashes[blockHashIndex];
79922
+ if (voteBlocksHash.toString() !== stapleBlockHash.toString()) {
79923
+ throw (new vote_1.default('VOTE_STAPLE_ALL_VOTES_MUST_HAVE_SAME_BLOCKS_ORDER', 'All votes must list blocks in the same order'));
79924
+ }
79925
+ }
79926
+ }
79927
+ __classPrivateFieldSet(this, _VoteBlockBundle__votes, newVotes, "f");
79928
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__votes, "f"));
79929
+ }
79930
+ get blocks() {
79931
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f") !== undefined && this._votesValidated) {
79932
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f"));
79933
+ }
79934
+ /**
79935
+ * Order blocks by the vote ordering
79936
+ */
79937
+ __classPrivateFieldSet(this, _VoteBlockBundle__blocks, this.votes[0].blocks.map((blockHash) => {
79938
+ return (__classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle_blockHashes_get)[blockHash.toString()]);
79939
+ }), "f");
79940
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f"));
79941
+ }
79942
+ get touchedAccounts() {
79943
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__touchedAccounts, "f") !== undefined) {
79944
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__touchedAccounts, "f"));
79945
+ }
79946
+ const { touched } = (0, effects_1.computeEffectOfBlocks)(this.blocks);
79947
+ __classPrivateFieldSet(this, _VoteBlockBundle__touchedAccounts, touched, "f");
79948
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__touchedAccounts, "f"));
79949
+ }
79423
79950
  }
79424
79951
  exports.VoteBlockBundle = VoteBlockBundle;
79425
- _VoteBlockBundle_value = new WeakMap(), _VoteBlockBundle_valueCompressed = new WeakMap(), _VoteBlockBundle__hash = new WeakMap(), _VoteBlockBundle__blocksHash = new WeakMap();
79952
+ _VoteBlockBundle_value = new WeakMap(), _VoteBlockBundle_valueCompressed = new WeakMap(), _VoteBlockBundle__hash = new WeakMap(), _VoteBlockBundle__blocksHash = new WeakMap(), _VoteBlockBundle__blockHashes = new WeakMap(), _VoteBlockBundle__votes = new WeakMap(), _VoteBlockBundle__blocks = new WeakMap(), _VoteBlockBundle__touchedAccounts = new WeakMap(), _VoteBlockBundle_votesRaw = new WeakMap(), _VoteBlockBundle_blocksRaw = new WeakMap(), _VoteBlockBundle_options = new WeakMap(), _VoteBlockBundle__asn1Validated = new WeakMap(), _VoteBlockBundle_instances = new WeakSet(), _VoteBlockBundle__blocksAndVotesRaw_get = function _VoteBlockBundle__blocksAndVotesRaw_get() {
79953
+ /**
79954
+ * Parse BER encoded data into objects
79955
+ */
79956
+ const data = (0, asn1_1.ASN1toJS)(__classPrivateFieldGet(this, _VoteBlockBundle_value, "f"));
79957
+ if (!Array.isArray(data)) {
79958
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must be a Sequence'));
79959
+ }
79960
+ if (data.length !== 2) {
79961
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must contain exactly 2 elements (votes, and blocks)'));
79962
+ }
79963
+ const [blocksRaw, votesRaw] = data;
79964
+ if (!Array.isArray(blocksRaw) || !Array.isArray(votesRaw)) {
79965
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE', 'Vote staple must contain exactly 2 elements (votes, and blocks)'));
79966
+ }
79967
+ if (blocksRaw.length < 1) {
79968
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE_BLOCKS_AT_LEAST_ONE', 'There must be at least 1 block'));
79969
+ }
79970
+ if (votesRaw.length < 1) {
79971
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE_VOTES_AT_LEAST_ONE', 'There must be at least one vote'));
79972
+ }
79973
+ __classPrivateFieldSet(this, _VoteBlockBundle_votesRaw, votesRaw, "f");
79974
+ __classPrivateFieldSet(this, _VoteBlockBundle_blocksRaw, blocksRaw, "f");
79975
+ __classPrivateFieldSet(this, _VoteBlockBundle__asn1Validated, true, "f");
79976
+ return ({
79977
+ blocksRaw: __classPrivateFieldGet(this, _VoteBlockBundle_blocksRaw, "f"),
79978
+ votesRaw: __classPrivateFieldGet(this, _VoteBlockBundle_votesRaw, "f")
79979
+ });
79980
+ }, _VoteBlockBundle__blocksRaw_get = function _VoteBlockBundle__blocksRaw_get() {
79981
+ if (__classPrivateFieldGet(this, _VoteBlockBundle_blocksRaw, "f") !== undefined) {
79982
+ return (__classPrivateFieldGet(this, _VoteBlockBundle_blocksRaw, "f"));
79983
+ }
79984
+ return (__classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__blocksAndVotesRaw_get).blocksRaw);
79985
+ }, _VoteBlockBundle__votesRaw_get = function _VoteBlockBundle__votesRaw_get() {
79986
+ if (__classPrivateFieldGet(this, _VoteBlockBundle_votesRaw, "f") !== undefined) {
79987
+ return (__classPrivateFieldGet(this, _VoteBlockBundle_votesRaw, "f"));
79988
+ }
79989
+ return (__classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__blocksAndVotesRaw_get).votesRaw);
79990
+ }, _VoteBlockBundle_blockHashes_get = function _VoteBlockBundle_blockHashes_get() {
79991
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__blockHashes, "f") !== undefined) {
79992
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__blockHashes, "f"));
79993
+ }
79994
+ /**
79995
+ * List of blocks
79996
+ * If blocks are already known, use them otherwise parse from raw data
79997
+ */
79998
+ let blocksUnsorted = [];
79999
+ if (__classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f") !== undefined) {
80000
+ blocksUnsorted = __classPrivateFieldGet(this, _VoteBlockBundle__blocks, "f");
80001
+ }
80002
+ else {
80003
+ blocksUnsorted = __classPrivateFieldGet(this, _VoteBlockBundle_instances, "a", _VoteBlockBundle__blocksRaw_get).map(function (blockData) {
80004
+ if (!(Buffer.isBuffer(blockData))) {
80005
+ throw (new vote_1.default('VOTE_MALFORMED_STAPLE_BLOCKS', 'Each block must be an Octet String'));
80006
+ }
80007
+ return (new block_1.Block(blockData));
80008
+ });
80009
+ }
80010
+ /**
80011
+ * Get a list of every block hash
80012
+ */
80013
+ const blockHashes = {};
80014
+ for (const block of blocksUnsorted) {
80015
+ blockHashes[block.hash.toString()] = block;
80016
+ }
80017
+ __classPrivateFieldSet(this, _VoteBlockBundle__blockHashes, blockHashes, "f");
80018
+ return (__classPrivateFieldGet(this, _VoteBlockBundle__blockHashes, "f"));
80019
+ };
79426
80020
  VoteBlockBundle.VoteBlockHash = VoteBlockHash;
79427
80021
  VoteBlockBundle.isInstance = (0, helper_1.checkableGenerator)(VoteBlockBundle);
79428
80022
  class VoteStaple extends VoteBlockBundle {
79429
80023
  constructor(votesStapled, voteOptions = {}) {
79430
80024
  super(votesStapled, voteOptions);
80025
+ if (voteOptions.lazy !== true) {
80026
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
80027
+ this.votes;
80028
+ }
80029
+ }
80030
+ get votes() {
80031
+ const votes = super.votes;
80032
+ if (this._votesValidated) {
80033
+ return (votes);
80034
+ }
79431
80035
  /**
79432
80036
  * Ensure no representative has more than 1 vote in the bundle
79433
80037
  * and that every vote has the same level of permanence
79434
80038
  */
79435
80039
  const seenReps = new account_1.default.Set();
79436
80040
  let votesPermanence = undefined;
79437
- for (const vote of this.votes) {
80041
+ for (const vote of votes) {
79438
80042
  if (seenReps.has(vote.issuer)) {
79439
80043
  throw (new vote_1.default('VOTE_STAPLE_DUPLICATE_VOTE_ISSUER', `Unable to parse vote information since account ${vote.issuer.publicKeyString.get()} has voted more than once`));
79440
80044
  }
@@ -79446,6 +80050,8 @@ class VoteStaple extends VoteBlockBundle {
79446
80050
  throw (new vote_1.default('VOTE_STAPLE_PERMANENCE_MISMATCH', `Only votes with permanent set to ${votesPermanence} are permissible in a bundle, however we found a vote that expires on ${vote.validityTo.toISOString()}`));
79447
80051
  }
79448
80052
  }
80053
+ this._votesValidated = true;
80054
+ return (votes);
79449
80055
  }
79450
80056
  }
79451
80057
  exports.VoteStaple = VoteStaple;
@@ -79766,7 +80372,7 @@ exports.Testing = { findRDN, blockHashesFromVote, feeFromVote };
79766
80372
 
79767
80373
  Object.defineProperty(exports, "__esModule", ({ value: true }));
79768
80374
  exports.version = void 0;
79769
- exports.version = '0.14.13+g566b8de2c01660608e6eb5257113db271d7fc075';
80375
+ exports.version = '0.16.0+g906ddd004c65d7e5d33559183bed9119e681c5ae';
79770
80376
  exports["default"] = exports.version;
79771
80377
 
79772
80378