trac-msb 0.2.17 → 0.2.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -2
- package/SECURITY.md +9 -6
- package/cli/commandHandler.js +272 -0
- package/cli/handlers.js +210 -0
- package/cli/interactive.js +182 -0
- package/msb.mjs +7 -8
- package/package.json +33 -11
- package/rpc/create_server.js +44 -44
- package/rpc/handlers.js +43 -56
- package/rpc/routes/index.js +8 -8
- package/rpc/rpc_server.js +6 -2
- package/rpc/utils/helpers.js +46 -66
- package/scripts/pear-runner.js +170 -0
- package/src/config/args.js +60 -13
- package/src/config/config.js +163 -14
- package/src/config/env.js +57 -25
- package/src/core/network/Network.js +121 -56
- package/src/core/network/protocols/LegacyProtocol.js +21 -11
- package/src/core/network/protocols/NetworkMessages.js +38 -17
- package/src/core/network/protocols/ProtocolInterface.js +15 -3
- package/src/core/network/protocols/ProtocolSession.js +144 -17
- package/src/core/network/protocols/V1Protocol.js +37 -18
- package/src/core/network/protocols/connectionPolicies.js +174 -0
- package/src/core/network/protocols/legacy/NetworkMessageRouter.js +26 -20
- package/src/core/network/protocols/{shared/handlers/base/BaseOperationHandler.js → legacy/handlers/BaseStateOperationHandler.js} +25 -14
- package/src/core/network/protocols/legacy/handlers/{GetRequestHandler.js → LegacyGetRequestHandler.js} +9 -9
- package/src/core/network/protocols/legacy/handlers/LegacyResponseHandler.js +23 -0
- package/src/core/network/protocols/{shared/handlers/RoleOperationHandler.js → legacy/handlers/LegacyRoleOperationHandler.js} +19 -12
- package/src/core/network/protocols/{shared/handlers/SubnetworkOperationHandler.js → legacy/handlers/LegacySubnetworkOperationHandler.js} +29 -18
- package/src/core/network/protocols/{shared/handlers/TransferOperationHandler.js → legacy/handlers/LegacyTransferOperationHandler.js} +18 -12
- package/src/core/network/protocols/legacy/validators/base/BaseResponse.js +7 -10
- package/src/core/network/protocols/shared/validators/{PartialBootstrapDeployment.js → PartialBootstrapDeploymentValidator.js} +9 -4
- package/src/core/network/protocols/shared/validators/{base/PartialOperation.js → PartialOperationValidator.js} +53 -31
- package/src/core/network/protocols/shared/validators/{PartialRoleAccess.js → PartialRoleAccessValidator.js} +51 -17
- package/src/core/network/protocols/shared/validators/{PartialTransaction.js → PartialTransactionValidator.js} +21 -7
- package/src/core/network/protocols/shared/validators/{PartialTransfer.js → PartialTransferValidator.js} +32 -14
- package/src/core/network/protocols/v1/NetworkMessageRouter.js +91 -7
- package/src/core/network/protocols/v1/V1ProtocolError.js +27 -0
- package/src/core/network/protocols/v1/handlers/V1BaseOperationHandler.js +66 -0
- package/src/core/network/protocols/v1/handlers/V1BroadcastTransactionOperationHandler.js +272 -0
- package/src/core/network/protocols/v1/handlers/V1LivenessOperationHandler.js +88 -0
- package/src/core/network/protocols/v1/handlers/broadcastTransaction/BroadcastTransactionErrorMapper.js +84 -0
- package/src/core/network/protocols/v1/handlers/broadcastTransaction/BroadcastTransactionOperationStrategies.js +128 -0
- package/src/core/network/protocols/v1/handlers/broadcastTransaction/BroadcastTransactionPayloadUtils.js +26 -0
- package/src/core/network/protocols/v1/validators/V1BaseOperation.js +212 -0
- package/src/core/network/protocols/v1/validators/V1BroadcastTransactionRequest.js +28 -0
- package/src/core/network/protocols/v1/validators/V1BroadcastTransactionResponse.js +260 -0
- package/src/core/network/protocols/v1/validators/V1LivenessRequest.js +15 -0
- package/src/core/network/protocols/v1/validators/V1LivenessResponse.js +17 -0
- package/src/core/network/protocols/v1/validators/V1ValidationSchema.js +210 -0
- package/src/core/network/services/ConnectionManager.js +149 -96
- package/src/core/network/services/MessageOrchestrator.js +197 -37
- package/src/core/network/services/PendingRequestService.js +175 -0
- package/src/core/network/services/TransactionCommitService.js +149 -0
- package/src/core/network/services/TransactionPoolService.js +129 -18
- package/src/core/network/services/TransactionRateLimiterService.js +57 -35
- package/src/core/network/services/ValidatorHealthCheckService.js +127 -0
- package/src/core/network/services/ValidatorObserverService.js +400 -121
- package/src/core/state/State.js +259 -156
- package/src/core/state/utils/address.js +4 -9
- package/src/core/state/utils/balance.js +7 -7
- package/src/core/state/utils/roles.js +1 -1
- package/src/index.js +320 -278
- package/src/messages/network/v1/NetworkMessageBuilder.js +71 -100
- package/src/messages/network/v1/NetworkMessageDirector.js +16 -50
- package/src/messages/network/v1/networkMessageFactory.js +1 -1
- package/src/messages/state/ApplyStateMessageBuilder.js +6 -6
- package/src/messages/state/applyStateMessageFactory.js +1 -1
- package/src/utils/Scheduler.js +0 -8
- package/src/utils/buffer.js +1 -1
- package/src/utils/check.js +12 -13
- package/src/utils/constants.js +78 -5
- package/src/utils/deepEqualApplyPayload.js +40 -0
- package/src/utils/errors.js +20 -0
- package/src/utils/fileUtils.js +12 -3
- package/src/utils/helpers.js +10 -1
- package/src/utils/logger.js +25 -0
- package/src/utils/migrationUtils.js +3 -3
- package/src/utils/normalizers.js +38 -0
- package/src/utils/protobuf/networkV1.generated.cjs +2460 -0
- package/src/utils/protobuf/operationHelpers.js +24 -3
- package/.dockerignore +0 -16
- package/.github/workflows/acceptance-tests.yml +0 -38
- package/.github/workflows/lint-pr-title.yml +0 -26
- package/.github/workflows/publish.yml +0 -33
- package/.github/workflows/unit-tests.yml +0 -34
- package/CODE_OF_CONDUCT.md +0 -128
- package/docker-compose.yml +0 -17
- package/dockerfile +0 -41
- package/docs/fee_distribution.md +0 -89
- package/docs/trac_network_http_api.openapi.yaml +0 -889
- package/migration/.gitkeep +0 -0
- package/proto/applyOperations.proto +0 -117
- package/proto/network.proto +0 -74
- package/rpc/rpc_services.js +0 -163
- package/scripts/generate-protobufs.js +0 -42
- package/src/core/network/identity/NetworkWalletFactory.js +0 -77
- package/src/core/network/protocols/legacy/handlers/ResponseHandler.js +0 -37
- package/src/utils/cli.js +0 -130
- package/src/utils/cliCommands.js +0 -280
- package/src/utils/protobuf/network.cjs +0 -840
- package/tests/acceptance/v1/account/account.test.mjs +0 -123
- package/tests/acceptance/v1/balance/balance.test.mjs +0 -54
- package/tests/acceptance/v1/broadcast-transaction/broadcast-transaction.test.mjs +0 -116
- package/tests/acceptance/v1/confirmed-length/confirmed-length.test.mjs +0 -19
- package/tests/acceptance/v1/fee/fee.test.mjs +0 -11
- package/tests/acceptance/v1/health/health.test.mjs +0 -33
- package/tests/acceptance/v1/rpc.test.mjs +0 -95
- package/tests/acceptance/v1/tx/tx.test.mjs +0 -111
- package/tests/acceptance/v1/tx-details/tx-details.test.mjs +0 -213
- package/tests/acceptance/v1/tx-hashes/tx-hashes.test.mjs +0 -72
- package/tests/acceptance/v1/tx-payloads-bulk/tx-payloads-bulk.test.mjs +0 -27
- package/tests/acceptance/v1/txv/txv.test.mjs +0 -11
- package/tests/acceptance/v1/unconfirmed-length/unconfirmed-length.test.mjs +0 -11
- package/tests/fixtures/apply.fixtures.js +0 -77
- package/tests/fixtures/assembleMessage.fixtures.js +0 -41
- package/tests/fixtures/check.fixtures.js +0 -428
- package/tests/fixtures/networkV1.fixtures.js +0 -85
- package/tests/fixtures/protobuf.fixtures.js +0 -388
- package/tests/helpers/StateNetworkFactory.js +0 -155
- package/tests/helpers/address.js +0 -6
- package/tests/helpers/autobaseTestHelpers.js +0 -419
- package/tests/helpers/config.js +0 -4
- package/tests/helpers/createTestSignature.js +0 -13
- package/tests/helpers/regexHelper.js +0 -3
- package/tests/helpers/setupApplyTests.js +0 -587
- package/tests/helpers/transactionPayloads.mjs +0 -92
- package/tests/helpers/wrapper.js +0 -28
- package/tests/unit/messages/messages.test.js +0 -12
- package/tests/unit/messages/network/NetworkMessageBuilder.test.js +0 -276
- package/tests/unit/messages/network/NetworkMessageDirector.test.js +0 -201
- package/tests/unit/messages/state/applyStateMessageBuilder.complete.test.js +0 -525
- package/tests/unit/messages/state/applyStateMessageBuilder.partial.test.js +0 -237
- package/tests/unit/network/ConnectionManager.test.js +0 -191
- package/tests/unit/network/NetworkWalletFactory.test.js +0 -156
- package/tests/unit/network/networkModule.test.js +0 -10
- package/tests/unit/state/State.test.js +0 -80
- package/tests/unit/state/apply/addAdmin/addAdminHappyPathScenario.js +0 -42
- package/tests/unit/state/apply/addAdmin/addAdminScenarioHelpers.js +0 -276
- package/tests/unit/state/apply/addAdmin/adminEntryEncodingFailureScenario.js +0 -30
- package/tests/unit/state/apply/addAdmin/adminEntryExistsScenario.js +0 -78
- package/tests/unit/state/apply/addAdmin/nodeEntryInitializationFailureScenario.js +0 -30
- package/tests/unit/state/apply/addAdmin/nonBootstrapNodeScenario.js +0 -68
- package/tests/unit/state/apply/addAdmin/state.apply.addAdmin.test.js +0 -159
- package/tests/unit/state/apply/addIndexer/addIndexerHappyPathScenario.js +0 -39
- package/tests/unit/state/apply/addIndexer/addIndexerMultipleIndexersInTheNetworkScenario.js +0 -167
- package/tests/unit/state/apply/addIndexer/addIndexerPretenderAlreadyIndexerScenario.js +0 -21
- package/tests/unit/state/apply/addIndexer/addIndexerPretenderNotWriterScenario.js +0 -21
- package/tests/unit/state/apply/addIndexer/addIndexerRemoveAndReAddScenario.js +0 -186
- package/tests/unit/state/apply/addIndexer/addIndexerScenarioHelpers.js +0 -443
- package/tests/unit/state/apply/addIndexer/addIndexerWriterKeyAlreadyRegisteredScenario.js +0 -32
- package/tests/unit/state/apply/addIndexer/state.apply.addIndexer.test.js +0 -297
- package/tests/unit/state/apply/addWriter/addWriterHappyPathScenario.js +0 -41
- package/tests/unit/state/apply/addWriter/addWriterInvalidValidatorSignatureScenario.js +0 -32
- package/tests/unit/state/apply/addWriter/addWriterNewWkScenario.js +0 -149
- package/tests/unit/state/apply/addWriter/addWriterRequesterAlreadyWriterScenario.js +0 -21
- package/tests/unit/state/apply/addWriter/addWriterRequesterBalanceInsufficientScenario.js +0 -21
- package/tests/unit/state/apply/addWriter/addWriterRequesterEntryDecodeFailureScenario.js +0 -19
- package/tests/unit/state/apply/addWriter/addWriterRequesterEntryMissingScenario.js +0 -19
- package/tests/unit/state/apply/addWriter/addWriterRequesterIndexerScenario.js +0 -21
- package/tests/unit/state/apply/addWriter/addWriterRequesterNotWhitelistedScenario.js +0 -21
- package/tests/unit/state/apply/addWriter/addWriterScenarioHelpers.js +0 -766
- package/tests/unit/state/apply/addWriter/addWriterStakeBalanceUpdateFailureScenario.js +0 -50
- package/tests/unit/state/apply/addWriter/addWriterStakeInsufficientBalanceScenario.js +0 -29
- package/tests/unit/state/apply/addWriter/addWriterStakeInvalidBalanceScenario.js +0 -29
- package/tests/unit/state/apply/addWriter/addWriterStakeInvalidEntryScenario.js +0 -21
- package/tests/unit/state/apply/addWriter/addWriterStakeStakedBalanceFailureScenario.js +0 -37
- package/tests/unit/state/apply/addWriter/addWriterStakeSubtractFailureScenario.js +0 -42
- package/tests/unit/state/apply/addWriter/addWriterValidatorRewardScenario.js +0 -106
- package/tests/unit/state/apply/addWriter/addWriterWriterKeyMismatchScenario.js +0 -54
- package/tests/unit/state/apply/addWriter/addWriterWriterKeyOwnershipScenario.js +0 -54
- package/tests/unit/state/apply/addWriter/addWriterZeroWriterKeyScenario.js +0 -29
- package/tests/unit/state/apply/addWriter/state.apply.addWriter.test.js +0 -309
- package/tests/unit/state/apply/adminRecovery/adminRecoveryHappyPathScenario.js +0 -30
- package/tests/unit/state/apply/adminRecovery/adminRecoveryScenarioHelpers.js +0 -881
- package/tests/unit/state/apply/adminRecovery/state.apply.adminRecovery.test.js +0 -435
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistBanAndReapplyScenario.js +0 -78
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistExistingReaderHappyPathScenario.js +0 -98
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistFeeAfterDisableScenario.js +0 -66
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistHappyPathScenario.js +0 -55
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistInsufficientAdminBalanceScenario.js +0 -103
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistNodeAlreadyWhitelistedScenario.js +0 -60
- package/tests/unit/state/apply/appendWhitelist/appendWhitelistScenarioHelpers.js +0 -189
- package/tests/unit/state/apply/appendWhitelist/state.apply.appendWhitelist.test.js +0 -220
- package/tests/unit/state/apply/balanceInitialization/balanceInitializationHappyPathScenario.js +0 -82
- package/tests/unit/state/apply/balanceInitialization/balanceInitializationScenarioHelpers.js +0 -111
- package/tests/unit/state/apply/balanceInitialization/invalidAmountScenario.js +0 -45
- package/tests/unit/state/apply/balanceInitialization/nodeEntryBalanceUpdateFailureScenario.js +0 -82
- package/tests/unit/state/apply/balanceInitialization/state.apply.balanceInitialization.test.js +0 -189
- package/tests/unit/state/apply/banValidator/banValidatorBanAndReWhitelistScenario.js +0 -156
- package/tests/unit/state/apply/banValidator/banValidatorHappyPathScenario.js +0 -36
- package/tests/unit/state/apply/banValidator/banValidatorScenarioHelpers.js +0 -531
- package/tests/unit/state/apply/banValidator/banValidatorSequentialBansScenario.js +0 -74
- package/tests/unit/state/apply/banValidator/banValidatorTargetDecodeFailureScenario.js +0 -19
- package/tests/unit/state/apply/banValidator/banValidatorTargetIndexerScenario.js +0 -32
- package/tests/unit/state/apply/banValidator/banValidatorTargetNodeEntryMissingScenario.js +0 -19
- package/tests/unit/state/apply/banValidator/banValidatorTargetRoleUpdateFailureScenario.js +0 -19
- package/tests/unit/state/apply/banValidator/banValidatorWhitelistedNonWriterScenario.js +0 -38
- package/tests/unit/state/apply/banValidator/banValidatorWhitelistedZeroBalanceScenario.js +0 -91
- package/tests/unit/state/apply/banValidator/banValidatorWithdrawFailureScenario.js +0 -19
- package/tests/unit/state/apply/banValidator/state.apply.banValidator.test.js +0 -266
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentDuplicateRegistrationScenario.js +0 -143
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentHappyPathScenario.js +0 -26
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentIncompleteOperationScenario.js +0 -94
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentInvalidDeploymentEntryScenario.js +0 -37
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentMultipleBootstrapScenario.js +0 -86
- package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentScenarioHelpers.js +0 -347
- package/tests/unit/state/apply/bootstrapDeployment/invalidValidatorNodeEntryScenario.js +0 -57
- package/tests/unit/state/apply/bootstrapDeployment/state.apply.bootstrapDeployment.test.js +0 -429
- package/tests/unit/state/apply/common/access-control/adminConsistencyMismatchScenario.js +0 -120
- package/tests/unit/state/apply/common/access-control/adminEntryDecodeFailureScenario.js +0 -130
- package/tests/unit/state/apply/common/access-control/adminEntryExistsScenario.js +0 -93
- package/tests/unit/state/apply/common/access-control/adminEntryMissingScenario.js +0 -108
- package/tests/unit/state/apply/common/access-control/adminOnlyGuardScenario.js +0 -126
- package/tests/unit/state/apply/common/access-control/adminPublicKeyDecodeFailureScenario.js +0 -121
- package/tests/unit/state/apply/common/access-control/roleAccessOperationValidationScenario.js +0 -50
- package/tests/unit/state/apply/common/adminControlOperationValidationScenario.js +0 -56
- package/tests/unit/state/apply/common/balances/adminEntryUpdateFailureScenario.js +0 -52
- package/tests/unit/state/apply/common/balances/base/requesterBalanceScenarioBase.js +0 -198
- package/tests/unit/state/apply/common/balances/feeDecodeFailureScenario.js +0 -52
- package/tests/unit/state/apply/common/balances/requesterBalanceDecodeFailureScenario.js +0 -15
- package/tests/unit/state/apply/common/balances/requesterBalanceFeeApplicationFailureScenario.js +0 -11
- package/tests/unit/state/apply/common/balances/requesterBalanceInsufficientScenario.js +0 -15
- package/tests/unit/state/apply/common/balances/requesterBalanceUpdateFailureScenario.js +0 -11
- package/tests/unit/state/apply/common/balances/validatorEntryRewardFailureScenario.js +0 -11
- package/tests/unit/state/apply/common/balances/validatorEntryUpdateFailureScenario.js +0 -11
- package/tests/unit/state/apply/common/balances/validatorNodeEntryDecodeFailureScenario.js +0 -40
- package/tests/unit/state/apply/common/base/OperationValidationScenarioBase.js +0 -114
- package/tests/unit/state/apply/common/commonScenarioHelper.js +0 -103
- package/tests/unit/state/apply/common/indexer/indexerNodeEntryDecodeFailureScenario.js +0 -36
- package/tests/unit/state/apply/common/indexer/indexerNodeEntryMissingScenario.js +0 -36
- package/tests/unit/state/apply/common/indexer/indexerRoleUpdateFailureScenario.js +0 -29
- package/tests/unit/state/apply/common/indexer/indexerSequenceStateInvalidScenario.js +0 -66
- package/tests/unit/state/apply/common/invalidMessageComponentValidationScenario.js +0 -84
- package/tests/unit/state/apply/common/nodeEntryInitializationFailureScenario.js +0 -47
- package/tests/unit/state/apply/common/operationAlreadyAppliedScenario.js +0 -85
- package/tests/unit/state/apply/common/payload-structure/addressWithInvalidPublicKeyScenario.js +0 -52
- package/tests/unit/state/apply/common/payload-structure/initializationDisabledScenario.js +0 -54
- package/tests/unit/state/apply/common/payload-structure/invalidAddressValidationScenario.js +0 -73
- package/tests/unit/state/apply/common/payload-structure/invalidHashValidationScenario.js +0 -71
- package/tests/unit/state/apply/common/payload-structure/invalidPayloadValidationScenario.js +0 -31
- package/tests/unit/state/apply/common/payload-structure/invalidSignatureValidationScenario.js +0 -142
- package/tests/unit/state/apply/common/payload-structure/partialOperationValidationScenario.js +0 -87
- package/tests/unit/state/apply/common/requester/requesterNodeEntryBufferMissingScenario.js +0 -71
- package/tests/unit/state/apply/common/requester/requesterNodeEntryDecodeFailureScenario.js +0 -73
- package/tests/unit/state/apply/common/requester/requesterNodeEntryMissingScenario.js +0 -36
- package/tests/unit/state/apply/common/requesterAddressValidationScenario.js +0 -44
- package/tests/unit/state/apply/common/requesterPublicKeyValidationScenario.js +0 -25
- package/tests/unit/state/apply/common/transactionValidityMismatchScenario.js +0 -98
- package/tests/unit/state/apply/common/validatorConsistency/base/validatorConsistencyScenarioBase.js +0 -202
- package/tests/unit/state/apply/common/validatorConsistency/validatorEntryDecodeFailureScenario.js +0 -17
- package/tests/unit/state/apply/common/validatorConsistency/validatorEntryMissingScenario.js +0 -44
- package/tests/unit/state/apply/common/validatorConsistency/validatorInactiveScenario.js +0 -19
- package/tests/unit/state/apply/common/validatorConsistency/validatorWriterKeyMismatchScenario.js +0 -18
- package/tests/unit/state/apply/common/validatorEntryValidation/base/validatorEntryValidationScenarioBase.js +0 -315
- package/tests/unit/state/apply/common/validatorEntryValidation/validatorEntryInvalidBalanceScenario.js +0 -18
- package/tests/unit/state/apply/common/writerKeyExistsValidationScenario.js +0 -43
- package/tests/unit/state/apply/disableInitialization/disableInitializationAlreadyDisabledScenario.js +0 -53
- package/tests/unit/state/apply/disableInitialization/disableInitializationHappyPathScenario.js +0 -24
- package/tests/unit/state/apply/disableInitialization/disableInitializationScenarioHelpers.js +0 -204
- package/tests/unit/state/apply/disableInitialization/state.apply.disableInitialization.test.js +0 -161
- package/tests/unit/state/apply/missing-tests.md +0 -18
- package/tests/unit/state/apply/removeIndexer/removeIndexerHappyPathScenario.js +0 -58
- package/tests/unit/state/apply/removeIndexer/removeIndexerReAddAndRemoveAgainScenario.js +0 -98
- package/tests/unit/state/apply/removeIndexer/removeIndexerRemoveMultipleIndexersScenario.js +0 -167
- package/tests/unit/state/apply/removeIndexer/removeIndexerScenarioHelpers.js +0 -429
- package/tests/unit/state/apply/removeIndexer/removeIndexerTargetNotIndexerScenario.js +0 -22
- package/tests/unit/state/apply/removeIndexer/removeIndexerWriterKeyMissingScenario.js +0 -20
- package/tests/unit/state/apply/removeIndexer/state.apply.removeIndexer.test.js +0 -291
- package/tests/unit/state/apply/removeWriter/removeWriterAndAddWriterAgainScenario.js +0 -87
- package/tests/unit/state/apply/removeWriter/removeWriterHappyPathScenario.js +0 -38
- package/tests/unit/state/apply/removeWriter/removeWriterInvalidValidatorSignatureScenario.js +0 -32
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterBalanceInsufficientScenario.js +0 -21
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterEntryDecodeFailureScenario.js +0 -19
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterEntryMissingScenario.js +0 -19
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterIndexerScenario.js +0 -21
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterNotWriterScenario.js +0 -21
- package/tests/unit/state/apply/removeWriter/removeWriterRequesterRoleUpdateFailureScenario.js +0 -19
- package/tests/unit/state/apply/removeWriter/removeWriterScenarioHelpers.js +0 -348
- package/tests/unit/state/apply/removeWriter/removeWriterThroughWriterValidatorScenario.js +0 -113
- package/tests/unit/state/apply/removeWriter/removeWriterUnstakeFailureScenario.js +0 -33
- package/tests/unit/state/apply/removeWriter/removeWriterWriterKeyMismatchScenario.js +0 -21
- package/tests/unit/state/apply/removeWriter/removeWriterWriterKeyOwnershipScenario.js +0 -26
- package/tests/unit/state/apply/removeWriter/removeWriterWriterKeyRegistryMissingScenario.js +0 -22
- package/tests/unit/state/apply/removeWriter/state.apply.removeWriter.test.js +0 -307
- package/tests/unit/state/apply/state.apply.test.js +0 -24
- package/tests/unit/state/apply/transfer/state.apply.transfer.test.js +0 -819
- package/tests/unit/state/apply/transfer/transferContractSchemaValidationScenario.js +0 -22
- package/tests/unit/state/apply/transfer/transferDoubleSpendAcrossValidatorsScenario.js +0 -146
- package/tests/unit/state/apply/transfer/transferDoubleSpendSameBatchScenario.js +0 -63
- package/tests/unit/state/apply/transfer/transferDoubleSpendSingleValidatorScenario.js +0 -67
- package/tests/unit/state/apply/transfer/transferExistingRecipientAmountScenario.js +0 -31
- package/tests/unit/state/apply/transfer/transferExistingRecipientZeroAmountScenario.js +0 -31
- package/tests/unit/state/apply/transfer/transferHandlerGuardScenarios.js +0 -22
- package/tests/unit/state/apply/transfer/transferHappyPathScenario.js +0 -8
- package/tests/unit/state/apply/transfer/transferInvalidIncomingDataScenario.js +0 -66
- package/tests/unit/state/apply/transfer/transferNewRecipientAmountScenario.js +0 -31
- package/tests/unit/state/apply/transfer/transferNewRecipientZeroAmountScenario.js +0 -31
- package/tests/unit/state/apply/transfer/transferScenarioHelpers.js +0 -1170
- package/tests/unit/state/apply/transfer/transferSelfTransferAmountScenario.js +0 -38
- package/tests/unit/state/apply/transfer/transferSelfTransferZeroAmountScenario.js +0 -38
- package/tests/unit/state/apply/transfer/transferValidatorRecipientAmountScenario.js +0 -38
- package/tests/unit/state/apply/transfer/transferValidatorRecipientZeroAmountScenario.js +0 -38
- package/tests/unit/state/apply/txOperation/state.apply.txOperation.test.js +0 -318
- package/tests/unit/state/apply/txOperation/txOperationBootstrapNotRegisteredScenario.js +0 -70
- package/tests/unit/state/apply/txOperation/txOperationDifferentValidatorCreatorHappyPathScenario.js +0 -23
- package/tests/unit/state/apply/txOperation/txOperationInvalidDeploymentEntryScenario.js +0 -48
- package/tests/unit/state/apply/txOperation/txOperationInvalidFeeAmountScenario.js +0 -39
- package/tests/unit/state/apply/txOperation/txOperationInvalidSubnetCreatorAddressScenario.js +0 -46
- package/tests/unit/state/apply/txOperation/txOperationRequesterCreatorHappyPathScenario.js +0 -21
- package/tests/unit/state/apply/txOperation/txOperationScenarioHelpers.js +0 -432
- package/tests/unit/state/apply/txOperation/txOperationStandardHappyPathScenario.js +0 -21
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeAddCreatorBalanceFailureScenario.js +0 -26
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeAddValidatorBalanceFailureScenario.js +0 -25
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeAddValidatorBonusFailureScenario.js +0 -27
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeDecodeCreatorEntryScenario.js +0 -18
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeDecodeRequesterEntryScenario.js +0 -17
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeDecodeValidatorEntryScenario.js +0 -31
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeGuardBypassScenario.js +0 -49
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeGuardScenarioFactory.js +0 -93
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeInsufficientRequesterBalanceScenario.js +0 -28
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeInvalidCreatorBalanceScenario.js +0 -29
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeInvalidRequesterBalanceScenario.js +0 -28
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeInvalidRequesterEntryScenario.js +0 -17
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeInvalidValidatorBalanceScenario.js +0 -33
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeMissingCreatorEntryScenario.js +0 -18
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeSubtractFailureScenario.js +0 -25
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeUpdateCreatorBalanceFailureScenario.js +0 -26
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeUpdateFailureScenario.js +0 -25
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeUpdateValidatorBalanceFailureScenario.js +0 -26
- package/tests/unit/state/apply/txOperation/txOperationTransferFeeUpdateValidatorBonusFailureScenario.js +0 -27
- package/tests/unit/state/apply/txOperation/txOperationValidatorCreatorHappyPathScenario.js +0 -21
- package/tests/unit/state/stateModule.test.js +0 -23
- package/tests/unit/state/stateTestUtils.js +0 -32
- package/tests/unit/state/utils/address.test.js +0 -63
- package/tests/unit/state/utils/adminEntry.test.js +0 -52
- package/tests/unit/state/utils/balance.test.js +0 -320
- package/tests/unit/state/utils/lengthEntry.test.js +0 -54
- package/tests/unit/state/utils/nodeEntry.test.js +0 -298
- package/tests/unit/state/utils/roles.test.js +0 -44
- package/tests/unit/unit.test.js +0 -14
- package/tests/unit/utils/amountSerialization/amountSerialization.test.js +0 -237
- package/tests/unit/utils/buffer/buffer.test.js +0 -251
- package/tests/unit/utils/check/adminControlOperation.test.js +0 -156
- package/tests/unit/utils/check/balanceInitializationOperation.test.js +0 -54
- package/tests/unit/utils/check/bootstrapDeploymentOperation.test.js +0 -104
- package/tests/unit/utils/check/check.test.js +0 -17
- package/tests/unit/utils/check/common.test.js +0 -419
- package/tests/unit/utils/check/coreAdminOperation.test.js +0 -95
- package/tests/unit/utils/check/roleAccessOperation.test.js +0 -255
- package/tests/unit/utils/check/transactionOperation.test.js +0 -107
- package/tests/unit/utils/check/transferOperation.test.js +0 -102
- package/tests/unit/utils/fileUtils/readAddressesFromWhitelistFile.test.js +0 -95
- package/tests/unit/utils/fileUtils/readBalanceMigrationFile.test.js +0 -149
- package/tests/unit/utils/helpers/helpers.test.js +0 -11
- package/tests/unit/utils/helpers/isHexString.test.js +0 -12
- package/tests/unit/utils/helpers/normalizeHex.test.js +0 -82
- package/tests/unit/utils/migrationUtils/validateAddressFromIncomingFile.test.js +0 -100
- package/tests/unit/utils/normalizers/normalizers.test.js +0 -469
- package/tests/unit/utils/protobuf/applyOperations.test.js +0 -91
- package/tests/unit/utils/protobuf/operationHelpers.test.js +0 -305
- package/tests/unit/utils/protobuf/protobuf.test.js +0 -12
- package/tests/unit/utils/type/type.test.js +0 -25
- package/tests/unit/utils/utils.test.js +0 -20
- package/whitelist/.gitkeep +0 -0
|
@@ -1,37 +1,79 @@
|
|
|
1
1
|
// PoolService.js
|
|
2
2
|
import { BATCH_SIZE } from '../../../utils/constants.js';
|
|
3
3
|
import Scheduler from '../../../utils/Scheduler.js';
|
|
4
|
+
import Denque from "denque";
|
|
5
|
+
import b4a from "b4a";
|
|
6
|
+
|
|
7
|
+
export class TransactionPoolProofUnavailableError extends Error {
|
|
8
|
+
constructor(txHash, blockNumber, reason = 'unknown', timestamp = 0) {
|
|
9
|
+
const timestampValue = timestamp instanceof Date ? timestamp.getTime() : timestamp;
|
|
10
|
+
const safeTimestamp = Number.isSafeInteger(timestampValue) ? timestampValue : 0;
|
|
11
|
+
super(`Proof unavailable for txHash ${txHash} at block ${blockNumber} at ${safeTimestamp}. Reason: ${reason}`);
|
|
12
|
+
this.txHash = txHash;
|
|
13
|
+
this.blockNumber = blockNumber;
|
|
14
|
+
this.timestamp = safeTimestamp;
|
|
15
|
+
this.reason = reason;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class TransactionPoolMissingCommitReceiptError extends Error {
|
|
20
|
+
constructor(txHash) {
|
|
21
|
+
super(`Missing commit receipt for txHash ${txHash}`);
|
|
22
|
+
this.txHash = txHash;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class TransactionPoolInvalidIncomingDataError extends Error {
|
|
27
|
+
constructor(message = 'Invalid transaction pool incoming data') {
|
|
28
|
+
super(message);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class TransactionPoolFullError extends Error {
|
|
33
|
+
constructor(maxSize) {
|
|
34
|
+
super(`Transaction pool is full. Maximum size of ${maxSize} reached.`);
|
|
35
|
+
this.maxSize = maxSize
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class TransactionPoolAlreadyQueuedError extends Error {
|
|
41
|
+
constructor(txHash) {
|
|
42
|
+
super(`Transaction with hash ${txHash} is already queued in the transaction pool.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
4
45
|
|
|
5
46
|
class TransactionPoolService {
|
|
6
47
|
#state;
|
|
7
48
|
#address;
|
|
8
49
|
#config;
|
|
9
|
-
#
|
|
50
|
+
#txPool = new Denque();
|
|
51
|
+
#transactionCommitService
|
|
10
52
|
#scheduler = null;
|
|
53
|
+
#queuedTxHashes
|
|
11
54
|
|
|
12
55
|
/**
|
|
13
56
|
* @param {State} state
|
|
14
57
|
* @param {string} address
|
|
58
|
+
* @param {TransactionCommitService} transactionCommitService
|
|
15
59
|
* @param {Config} config
|
|
16
60
|
**/
|
|
17
|
-
constructor(state, address, config) {
|
|
61
|
+
constructor(state, address, transactionCommitService, config) {
|
|
18
62
|
this.#state = state;
|
|
19
63
|
this.#address = address;
|
|
64
|
+
this.#transactionCommitService = transactionCommitService;
|
|
65
|
+
this.#queuedTxHashes = new Set(); // to improve lookup performance when checking for duplicate transactions
|
|
20
66
|
this.#config = config;
|
|
21
67
|
}
|
|
22
68
|
|
|
23
|
-
get
|
|
24
|
-
return this.#
|
|
69
|
+
get txPool() {
|
|
70
|
+
return this.#txPool;
|
|
25
71
|
}
|
|
26
72
|
|
|
27
73
|
get state() {
|
|
28
74
|
return this.#state;
|
|
29
75
|
}
|
|
30
76
|
|
|
31
|
-
get address() {
|
|
32
|
-
return this.#address;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
77
|
async start() {
|
|
36
78
|
if (!this.#config.enableWallet) {
|
|
37
79
|
console.info('TransactionPoolService can not start. Wallet is not enabled');
|
|
@@ -49,7 +91,7 @@ class TransactionPoolService {
|
|
|
49
91
|
async #worker(next) {
|
|
50
92
|
try {
|
|
51
93
|
await this.#processTransactions();
|
|
52
|
-
if (this.#
|
|
94
|
+
if (this.#txPool.size() > 0) {
|
|
53
95
|
next(0);
|
|
54
96
|
} else {
|
|
55
97
|
next(this.#config.processIntervalMs);
|
|
@@ -65,35 +107,104 @@ class TransactionPoolService {
|
|
|
65
107
|
|
|
66
108
|
async #processTransactions() {
|
|
67
109
|
const canValidate = await this.#checkValidationPermissions();
|
|
68
|
-
if (canValidate
|
|
69
|
-
|
|
70
|
-
|
|
110
|
+
if (!canValidate || this.#txPool.size() === 0) return;
|
|
111
|
+
|
|
112
|
+
const batchItems = this.#prepareBatch();
|
|
113
|
+
const encodedBatch = batchItems.map(item => item.encodedTx);
|
|
114
|
+
const batchTxHashes = batchItems.map(item => item.txHash);
|
|
115
|
+
try {
|
|
116
|
+
const receipts = await this.#state.appendWithProofOfPublication(encodedBatch, batchTxHashes);
|
|
117
|
+
|
|
118
|
+
const receiptsByHash = new Map();
|
|
119
|
+
for (const receipt of receipts) {
|
|
120
|
+
if (receipt.txHash) receiptsByHash.set(receipt.txHash, receipt);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
for (const item of batchItems) {
|
|
124
|
+
const receipt = receiptsByHash.get(item.txHash);
|
|
125
|
+
|
|
126
|
+
if (!receipt) {
|
|
127
|
+
this.#transactionCommitService.rejectPendingCommit(
|
|
128
|
+
item.txHash,
|
|
129
|
+
new TransactionPoolMissingCommitReceiptError(item.txHash)
|
|
130
|
+
);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!receipt.proof) {
|
|
135
|
+
this.#transactionCommitService.rejectPendingCommit(
|
|
136
|
+
item.txHash,
|
|
137
|
+
new TransactionPoolProofUnavailableError(
|
|
138
|
+
item.txHash,
|
|
139
|
+
receipt.blockNumber,
|
|
140
|
+
receipt.proofError,
|
|
141
|
+
receipt.timestamp
|
|
142
|
+
)
|
|
143
|
+
);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
this.#transactionCommitService.resolvePendingCommit(item.txHash, receipt);
|
|
148
|
+
}
|
|
149
|
+
} catch (error) {
|
|
150
|
+
for (const item of batchItems) {
|
|
151
|
+
this.#transactionCommitService.rejectPendingCommit(item.txHash, error);
|
|
152
|
+
}
|
|
153
|
+
console.error(
|
|
154
|
+
`TransactionPoolService: failed to process batch (size=${batchItems.length}): ${error?.message ?? 'unknown error'}`
|
|
155
|
+
);
|
|
71
156
|
}
|
|
72
157
|
}
|
|
73
158
|
|
|
74
159
|
async #checkValidationPermissions() {
|
|
75
160
|
const isAdminAllowedToValidate = await this.state.isAdminAllowedToValidate();
|
|
76
|
-
const isNodeAllowedToValidate = await this.state.allowedToValidate(this
|
|
161
|
+
const isNodeAllowedToValidate = await this.state.allowedToValidate(this.#address);
|
|
77
162
|
return isNodeAllowedToValidate || isAdminAllowedToValidate;
|
|
78
163
|
}
|
|
79
164
|
|
|
80
165
|
#prepareBatch() {
|
|
81
|
-
const
|
|
82
|
-
const
|
|
83
|
-
|
|
166
|
+
const batch = [];
|
|
167
|
+
const batchSize = Math.min(this.#txPool.size(), BATCH_SIZE);
|
|
168
|
+
|
|
169
|
+
for (let i = 0; i < batchSize; i++) {
|
|
170
|
+
const tx = this.#txPool.shift();
|
|
171
|
+
this.#queuedTxHashes.delete(tx.txHash);
|
|
172
|
+
batch.push(tx);
|
|
173
|
+
}
|
|
84
174
|
return batch;
|
|
85
175
|
}
|
|
86
176
|
|
|
87
|
-
addTransaction(
|
|
88
|
-
this.
|
|
177
|
+
addTransaction(txHash, encodedTx) {
|
|
178
|
+
this.validateEnqueue();
|
|
179
|
+
if (!txHash || !encodedTx || typeof txHash !== 'string' || !b4a.isBuffer(encodedTx)) {
|
|
180
|
+
throw new TransactionPoolInvalidIncomingDataError()
|
|
181
|
+
}
|
|
182
|
+
if (this.hasTransaction(txHash)) {
|
|
183
|
+
throw new TransactionPoolAlreadyQueuedError(txHash);
|
|
184
|
+
}
|
|
185
|
+
this.#queuedTxHashes.add(txHash);
|
|
186
|
+
const txData = { txHash, encodedTx };
|
|
187
|
+
this.txPool.push(txData);
|
|
89
188
|
}
|
|
90
189
|
|
|
91
190
|
async stopPool(waitForCurrent = true) {
|
|
92
191
|
if (!this.#scheduler) return;
|
|
93
192
|
await this.#scheduler.stop(waitForCurrent);
|
|
94
193
|
this.#scheduler = null;
|
|
194
|
+
this.#queuedTxHashes.clear();
|
|
195
|
+
this.#txPool.clear();
|
|
95
196
|
console.info('TransactionPoolService: closing gracefully...');
|
|
96
197
|
}
|
|
198
|
+
|
|
199
|
+
validateEnqueue() {
|
|
200
|
+
if (this.#txPool.size() >= this.#config.txPoolSize) {
|
|
201
|
+
throw new TransactionPoolFullError(this.#config.txPoolSize);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
hasTransaction(txHash) {
|
|
206
|
+
return this.#queuedTxHashes.has(txHash);
|
|
207
|
+
}
|
|
97
208
|
}
|
|
98
209
|
|
|
99
210
|
export default TransactionPoolService;
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import b4a from 'b4a';
|
|
2
|
+
import {V1ProtocolError} from "../protocols/v1/V1ProtocolError.js";
|
|
3
|
+
import {ResultCode} from "../../../utils/constants.js";
|
|
4
|
+
import {publicKeyToAddress} from "../../../utils/helpers.js";
|
|
2
5
|
|
|
3
6
|
class TransactionRateLimiterService {
|
|
4
7
|
#lastCleanup;
|
|
@@ -14,19 +17,23 @@ class TransactionRateLimiterService {
|
|
|
14
17
|
}
|
|
15
18
|
|
|
16
19
|
/*
|
|
17
|
-
Checks if the peer has exceeded the rate limit.
|
|
20
|
+
Checks if the peer has exceeded the rate limit for the current 1-second window.
|
|
18
21
|
A peer is considered to have exceeded the rate limit if:
|
|
19
|
-
- The
|
|
20
|
-
- The number of transactions in
|
|
21
|
-
|
|
22
|
+
- The request belongs to the same 1-second window as previous requests (tracked per peer)
|
|
23
|
+
- The number of transactions already seen in this window is >= rateLimitMaxTransactionsPerSecond
|
|
24
|
+
|
|
25
|
+
Important:
|
|
26
|
+
- This method assumes the caller increments transactionCount AFTER calling this method.
|
|
27
|
+
(So exactly rateLimitMaxTransactionsPerSecond are allowed; the next one is blocked.)
|
|
22
28
|
*/
|
|
23
|
-
#hasExceededRateLimit(peer) {
|
|
29
|
+
#hasExceededRateLimit(peer, currentTime) {
|
|
24
30
|
const peerData = this.#connectionsStatistics.get(peer);
|
|
25
|
-
const currentSecond = Math.floor((
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
const currentSecond = Math.floor((currentTime - peerData.sessionStartTime) / 1000);
|
|
32
|
+
const lastResetSecond = Math.floor((peerData.lastCounterReset - peerData.sessionStartTime) / 1000);
|
|
33
|
+
|
|
34
|
+
if (currentSecond > lastResetSecond) {
|
|
28
35
|
peerData.transactionCount = 0;
|
|
29
|
-
peerData.lastCounterReset =
|
|
36
|
+
peerData.lastCounterReset = currentTime;
|
|
30
37
|
this.#connectionsStatistics.set(peer, peerData);
|
|
31
38
|
}
|
|
32
39
|
|
|
@@ -34,23 +41,18 @@ class TransactionRateLimiterService {
|
|
|
34
41
|
}
|
|
35
42
|
|
|
36
43
|
/*
|
|
37
|
-
Handles
|
|
38
|
-
If the peer has exceeded the rate limit, it disconnects the peer.
|
|
39
|
-
Otherwise, it updates the connection info with the current timestamp.
|
|
44
|
+
Handles rate limiting for a peer connection (legacy protocol).
|
|
45
|
+
If the peer has exceeded the rate limit, it disconnects the peer and returns true.
|
|
46
|
+
Otherwise, it updates the connection info with the current timestamp and returns false.
|
|
40
47
|
*/
|
|
41
|
-
|
|
48
|
+
legacyHandleRateLimit(connection) {
|
|
42
49
|
const peer = b4a.toString(connection.remotePublicKey, 'hex');
|
|
43
50
|
const currentTime = Date.now();
|
|
44
51
|
|
|
45
52
|
this.#cleanUpOldConnections(currentTime);
|
|
46
53
|
this.#initializePeerConnectionInfoEntry(peer, currentTime);
|
|
47
54
|
|
|
48
|
-
if (this.#
|
|
49
|
-
this.#connectionsStatistics.delete(peer);
|
|
50
|
-
return false;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
if (this.#hasExceededRateLimit(peer)) {
|
|
55
|
+
if (this.#hasExceededRateLimit(peer, currentTime)) {
|
|
54
56
|
console.warn(`Rate limit exceeded for peer ${peer}. Disconnecting...`);
|
|
55
57
|
this.#swarm.leavePeer(connection.remotePublicKey);
|
|
56
58
|
connection.end();
|
|
@@ -61,23 +63,42 @@ class TransactionRateLimiterService {
|
|
|
61
63
|
return false;
|
|
62
64
|
}
|
|
63
65
|
|
|
66
|
+
/*
|
|
67
|
+
Handles rate limiting for a peer connection (v1 protocol).
|
|
68
|
+
If the peer has exceeded the rate limit, it throws V1ProtocolError with RATE_LIMITED result code.
|
|
69
|
+
Otherwise, it updates the connection info with the current timestamp.
|
|
70
|
+
*/
|
|
71
|
+
v1HandleRateLimit(connection) {
|
|
72
|
+
const peer = b4a.toString(connection.remotePublicKey, 'hex');
|
|
73
|
+
const currentTime = Date.now();
|
|
74
|
+
|
|
75
|
+
this.#cleanUpOldConnections(currentTime);
|
|
76
|
+
this.#initializePeerConnectionInfoEntry(peer, currentTime);
|
|
77
|
+
|
|
78
|
+
if (this.#hasExceededRateLimit(peer, currentTime)) {
|
|
79
|
+
throw new V1ProtocolError(
|
|
80
|
+
ResultCode.RATE_LIMITED,
|
|
81
|
+
`Rate limit exceeded for peer ${publicKeyToAddress(connection.remotePublicKey, this.#config)}`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
this.#updatePeerConnectionInfo(peer, currentTime);
|
|
85
|
+
}
|
|
86
|
+
|
|
64
87
|
#shouldCleanupConnections(currentTime) {
|
|
65
88
|
return currentTime - this.#lastCleanup >= this.#config.rateLimitCleanupIntervalMs;
|
|
66
89
|
}
|
|
67
90
|
|
|
68
91
|
/**
|
|
69
|
-
Cleans up
|
|
70
|
-
|
|
71
|
-
- If the last cleanup was more than rateLimitCleanupIntervalMs ago
|
|
92
|
+
Cleans up per-peer statistics that have been inactive for more than rateLimitCleanupIntervalMs.
|
|
93
|
+
Runs at most once every rateLimitCleanupIntervalMs.
|
|
72
94
|
*/
|
|
73
95
|
#cleanUpOldConnections(currentTime) {
|
|
74
96
|
if (!this.#shouldCleanupConnections(currentTime)) {
|
|
75
97
|
return;
|
|
76
98
|
}
|
|
77
99
|
|
|
78
|
-
for (const [peer
|
|
79
|
-
if (this.#isConnectionExpired(peer)) {
|
|
80
|
-
//console.log(`Connection for peer ${peer} has expired. Removing...`);
|
|
100
|
+
for (const [peer] of this.#connectionsStatistics.entries()) {
|
|
101
|
+
if (this.#isConnectionExpired(peer, currentTime)) {
|
|
81
102
|
this.#connectionsStatistics.delete(peer);
|
|
82
103
|
}
|
|
83
104
|
}
|
|
@@ -87,19 +108,19 @@ class TransactionRateLimiterService {
|
|
|
87
108
|
|
|
88
109
|
/*
|
|
89
110
|
Initializes the connection statistics for a peer.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
sessionStartTime: timestamp,
|
|
93
|
-
lastActivityTime: timestamp,
|
|
94
|
-
|
|
111
|
+
Stored as a HashMap with the following structure:
|
|
112
|
+
peerPublicKeyHex: {
|
|
113
|
+
sessionStartTime: timestamp, // When we first saw this peer (start of local tracking session)
|
|
114
|
+
lastActivityTime: timestamp, // Timestamp of peer's most recent activity
|
|
115
|
+
lastCounterReset: timestamp, // Timestamp when the per-second counter was last reset
|
|
116
|
+
transactionCount: number // Transactions seen in the current 1-second window
|
|
95
117
|
}
|
|
96
|
-
|
|
97
118
|
*/
|
|
98
119
|
#initializePeerConnectionInfoEntry(peer, timestamp) {
|
|
99
120
|
if (!this.#connectionsStatistics.has(peer)) {
|
|
100
121
|
this.#connectionsStatistics.set(peer, {
|
|
101
122
|
sessionStartTime: timestamp,
|
|
102
|
-
lastActivityTime:
|
|
123
|
+
lastActivityTime: timestamp,
|
|
103
124
|
lastCounterReset: timestamp,
|
|
104
125
|
transactionCount: 0
|
|
105
126
|
});
|
|
@@ -118,11 +139,12 @@ class TransactionRateLimiterService {
|
|
|
118
139
|
}
|
|
119
140
|
|
|
120
141
|
/*
|
|
121
|
-
Checks if the
|
|
142
|
+
Checks if the stored statistics for a peer have expired due to inactivity.
|
|
143
|
+
Note: this is NOT a network-level connection timeout; it's only used to evict old Map entries.
|
|
122
144
|
*/
|
|
123
|
-
#isConnectionExpired(peer) {
|
|
145
|
+
#isConnectionExpired(peer, currentTime) {
|
|
124
146
|
const peerData = this.#connectionsStatistics.get(peer);
|
|
125
|
-
return
|
|
147
|
+
return currentTime - peerData.lastActivityTime >= this.#config.rateLimitConnectionTimeoutMs;
|
|
126
148
|
}
|
|
127
149
|
}
|
|
128
150
|
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import ReadyResource from 'ready-resource';
|
|
2
|
+
import b4a from 'b4a';
|
|
3
|
+
import { generateUUID } from '../../../utils/helpers.js';
|
|
4
|
+
import { EventType } from '../../../utils/constants.js';
|
|
5
|
+
import { Logger } from '../../../utils/logger.js';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_HEALTH_CHECK_INTERVAL_MS = 300000; // 5 minutes
|
|
8
|
+
class ValidatorHealthCheckService extends ReadyResource {
|
|
9
|
+
#config;
|
|
10
|
+
#intervalMs;
|
|
11
|
+
#timers;
|
|
12
|
+
#logger;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {object} config
|
|
16
|
+
*/
|
|
17
|
+
constructor(config = {}) {
|
|
18
|
+
super();
|
|
19
|
+
this.#config = config;
|
|
20
|
+
this.#timers = new Map();
|
|
21
|
+
this.#logger = new Logger(config);
|
|
22
|
+
|
|
23
|
+
const interval = this.#config.validatorHealthCheckInterval;
|
|
24
|
+
this.#intervalMs = interval ? this.#checkInterval(interval) : DEFAULT_HEALTH_CHECK_INTERVAL_MS;
|
|
25
|
+
|
|
26
|
+
this.#logger.debug(`initialized with intervalMs ${this.#intervalMs}`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
get size() {
|
|
30
|
+
return this.#timers.size;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async _open() {
|
|
34
|
+
this.#logger.debug('open: health check service ready');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async _close() {
|
|
38
|
+
this.#logger.debug('close: stopping all health checks');
|
|
39
|
+
this.#stopAll();
|
|
40
|
+
this.#timers.clear();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Start periodic health checks for a validator.
|
|
45
|
+
* @param {String} publicKey
|
|
46
|
+
*/
|
|
47
|
+
start(publicKey) {
|
|
48
|
+
if (!this.opened) {
|
|
49
|
+
throw new Error('start: service not ready. Call ready() before start().');
|
|
50
|
+
}
|
|
51
|
+
const publicKeyHex = this.#normalizePublicKey(publicKey);
|
|
52
|
+
if (this.#timers.has(publicKeyHex)) {
|
|
53
|
+
this.#logger.debug(`start: already scheduled for ${publicKey}`);
|
|
54
|
+
return false; // TODO: Implement better error handling
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const timerId = setInterval(() => {
|
|
58
|
+
this.#emitHealthCheck(publicKeyHex);
|
|
59
|
+
}, this.#intervalMs);
|
|
60
|
+
|
|
61
|
+
this.#timers.set(publicKeyHex, { timerId, intervalMs: this.#intervalMs });
|
|
62
|
+
this.#logger.debug(`start: scheduled health checks for ${publicKeyHex} every ${this.#intervalMs} ms`);
|
|
63
|
+
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Stop periodic health checks for a validator.
|
|
69
|
+
* @param {String} publicKey
|
|
70
|
+
* @returns {boolean} true if stopped, false if not scheduled
|
|
71
|
+
*/
|
|
72
|
+
stop(publicKey) {
|
|
73
|
+
const publicKeyHex = this.#normalizePublicKey(publicKey);
|
|
74
|
+
const entry = this.#timers.get(publicKeyHex);
|
|
75
|
+
if (!entry) {
|
|
76
|
+
this.#logger.debug(`stop: did not find scheduled health check for public key ${publicKey}. Aborting`);
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
clearInterval(entry.timerId);
|
|
80
|
+
this.#timers.delete(publicKeyHex);
|
|
81
|
+
this.#logger.debug(`stop: cancelled health checks for ${publicKeyHex}`);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Check if a validator is scheduled.
|
|
87
|
+
* @param {String} publicKey
|
|
88
|
+
* @returns {boolean}
|
|
89
|
+
*/
|
|
90
|
+
has(publicKey) {
|
|
91
|
+
return this.#timers.has(this.#normalizePublicKey(publicKey));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async #emitHealthCheck(publicKey) {
|
|
95
|
+
try {
|
|
96
|
+
const requestId = generateUUID();
|
|
97
|
+
this.emit(EventType.VALIDATOR_HEALTH_CHECK, publicKey, requestId);
|
|
98
|
+
this.#logger.debug(`Emitted health check event for ${publicKey} with requestId ${requestId}`);
|
|
99
|
+
} catch (error) {
|
|
100
|
+
this.#logger.error(`ValidatorHealthCheckService: Failed to emit health check for ${publicKey}: ${error?.message || error}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
#stopAll() {
|
|
105
|
+
this.#logger.debug(`stopAll: cancelling health checks for ${this.#timers.size} validators`);
|
|
106
|
+
for (const publicKey of this.#timers.keys()) {
|
|
107
|
+
this.stop(publicKey);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#checkInterval(intervalMs) {
|
|
112
|
+
const ms = Number(intervalMs);
|
|
113
|
+
if (!Number.isFinite(ms) || ms <= 0) {
|
|
114
|
+
throw new RangeError(`ValidatorHealthCheckService: invalid intervalMs value: ${intervalMs}`);
|
|
115
|
+
}
|
|
116
|
+
return ms;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// TODO: This method is used in multiple places. Consider moving it to a utility file or exposing it from PeerWallet.
|
|
120
|
+
#normalizePublicKey(publicKey) {
|
|
121
|
+
if (b4a.isBuffer(publicKey)) return publicKey.toString('hex');
|
|
122
|
+
if (typeof publicKey === 'string') return publicKey.toLowerCase();
|
|
123
|
+
throw new TypeError('ValidatorHealthCheckService: publicKey must be a Buffer or hex string');
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export default ValidatorHealthCheckService;
|