trac-msb 0.2.7 → 0.2.9

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 (187) hide show
  1. package/.github/workflows/publish.yml +8 -16
  2. package/msb.mjs +13 -25
  3. package/package.json +8 -4
  4. package/proto/network.proto +74 -0
  5. package/rpc/{create_server.mjs → create_server.js} +4 -4
  6. package/rpc/{handlers.mjs → handlers.js} +7 -7
  7. package/rpc/routes/{index.mjs → index.js} +1 -1
  8. package/rpc/routes/{v1.mjs → v1.js} +1 -1
  9. package/rpc/rpc_server.js +10 -0
  10. package/rpc/rpc_services.js +48 -7
  11. package/rpc/utils/{helpers.mjs → helpers.js} +1 -1
  12. package/src/config/config.js +137 -0
  13. package/src/config/env.js +63 -0
  14. package/src/core/network/Network.js +133 -119
  15. package/src/core/network/identity/NetworkWalletFactory.js +5 -6
  16. package/src/core/network/protocols/LegacyProtocol.js +67 -0
  17. package/src/core/network/protocols/NetworkMessages.js +48 -0
  18. package/src/core/network/protocols/ProtocolInterface.js +31 -0
  19. package/src/core/network/protocols/ProtocolSession.js +59 -0
  20. package/src/core/network/protocols/V1Protocol.js +64 -0
  21. package/src/core/network/protocols/legacy/NetworkMessageRouter.js +84 -0
  22. package/src/core/network/protocols/legacy/handlers/GetRequestHandler.js +53 -0
  23. package/src/core/network/protocols/legacy/handlers/ResponseHandler.js +37 -0
  24. package/src/core/network/{messaging → protocols/legacy}/validators/ValidatorResponse.js +2 -2
  25. package/src/core/network/{messaging → protocols/legacy}/validators/base/BaseResponse.js +13 -6
  26. package/src/core/network/protocols/shared/handlers/RoleOperationHandler.js +88 -0
  27. package/src/core/network/protocols/shared/handlers/SubnetworkOperationHandler.js +93 -0
  28. package/src/core/network/protocols/shared/handlers/TransferOperationHandler.js +57 -0
  29. package/src/core/network/{messaging → protocols/shared}/handlers/base/BaseOperationHandler.js +21 -26
  30. package/src/core/network/{messaging → protocols/shared}/validators/PartialBootstrapDeployment.js +3 -3
  31. package/src/core/network/{messaging → protocols/shared}/validators/PartialRoleAccess.js +15 -12
  32. package/src/core/network/{messaging → protocols/shared}/validators/PartialTransaction.js +10 -11
  33. package/src/core/network/{messaging → protocols/shared}/validators/PartialTransfer.js +10 -7
  34. package/src/core/network/{messaging → protocols/shared}/validators/base/PartialOperation.js +40 -22
  35. package/src/core/network/protocols/v1/NetworkMessageRouter.js +15 -0
  36. package/src/core/network/services/ConnectionManager.js +13 -19
  37. package/src/core/network/services/MessageOrchestrator.js +10 -22
  38. package/src/core/network/services/TransactionPoolService.js +10 -10
  39. package/src/core/network/services/TransactionRateLimiterService.js +5 -3
  40. package/src/core/network/services/ValidatorObserverService.js +46 -21
  41. package/src/core/state/State.js +137 -141
  42. package/src/core/state/utils/address.js +18 -16
  43. package/src/core/state/utils/adminEntry.js +17 -16
  44. package/src/core/state/utils/deploymentEntry.js +15 -15
  45. package/src/core/state/utils/transaction.js +3 -95
  46. package/src/index.js +250 -325
  47. package/src/messages/network/v1/NetworkMessageBuilder.js +325 -0
  48. package/src/messages/network/v1/NetworkMessageDirector.js +137 -0
  49. package/src/messages/network/v1/networkMessageFactory.js +12 -0
  50. package/src/messages/state/ApplyStateMessageBuilder.js +661 -0
  51. package/src/messages/state/ApplyStateMessageDirector.js +516 -0
  52. package/src/messages/state/applyStateMessageFactory.js +12 -0
  53. package/src/utils/buffer.js +53 -1
  54. package/src/utils/check.js +21 -17
  55. package/src/utils/cli.js +0 -8
  56. package/src/utils/cliCommands.js +11 -11
  57. package/src/utils/constants.js +36 -24
  58. package/src/utils/fileUtils.js +1 -4
  59. package/src/utils/helpers.js +9 -20
  60. package/src/utils/migrationUtils.js +2 -2
  61. package/src/utils/normalizers.js +94 -11
  62. package/src/utils/protobuf/network.cjs +840 -0
  63. package/src/utils/protobuf/operationHelpers.js +10 -0
  64. package/tests/acceptance/v1/account/account.test.mjs +2 -2
  65. package/tests/acceptance/v1/balance/balance.test.mjs +1 -1
  66. package/tests/acceptance/v1/broadcast-transaction/broadcast-transaction.test.mjs +11 -2
  67. package/tests/acceptance/v1/rpc.test.mjs +10 -10
  68. package/tests/acceptance/v1/tx/tx.test.mjs +4 -2
  69. package/tests/acceptance/v1/tx-details/tx-details.test.mjs +7 -3
  70. package/tests/fixtures/check.fixtures.js +42 -42
  71. package/tests/fixtures/networkV1.fixtures.js +84 -0
  72. package/tests/fixtures/protobuf.fixtures.js +110 -26
  73. package/tests/helpers/StateNetworkFactory.js +3 -5
  74. package/tests/helpers/autobaseTestHelpers.js +1 -2
  75. package/tests/helpers/config.js +3 -0
  76. package/tests/helpers/setupApplyTests.js +113 -99
  77. package/tests/helpers/transactionPayloads.mjs +26 -12
  78. package/tests/unit/messages/messages.test.js +12 -0
  79. package/tests/unit/messages/network/NetworkMessageBuilder.test.js +276 -0
  80. package/tests/unit/messages/network/NetworkMessageDirector.test.js +203 -0
  81. package/tests/unit/messages/state/applyStateMessageBuilder.complete.test.js +521 -0
  82. package/tests/unit/messages/state/applyStateMessageBuilder.partial.test.js +233 -0
  83. package/tests/unit/network/ConnectionManager.test.js +10 -7
  84. package/tests/unit/network/NetworkWalletFactory.test.js +14 -14
  85. package/tests/unit/network/networkModule.test.js +3 -2
  86. package/tests/unit/state/apply/addAdmin/addAdminHappyPathScenario.js +10 -6
  87. package/tests/unit/state/apply/addAdmin/addAdminScenarioHelpers.js +11 -8
  88. package/tests/unit/state/apply/addAdmin/state.apply.addAdmin.test.js +11 -7
  89. package/tests/unit/state/apply/addIndexer/addIndexerScenarioHelpers.js +18 -20
  90. package/tests/unit/state/apply/addWriter/addWriterScenarioHelpers.js +57 -48
  91. package/tests/unit/state/apply/addWriter/addWriterValidatorRewardScenario.js +2 -1
  92. package/tests/unit/state/apply/adminRecovery/adminRecoveryScenarioHelpers.js +72 -57
  93. package/tests/unit/state/apply/adminRecovery/state.apply.adminRecovery.test.js +3 -7
  94. package/tests/unit/state/apply/appendWhitelist/appendWhitelistScenarioHelpers.js +12 -14
  95. package/tests/unit/state/apply/balanceInitialization/balanceInitializationScenarioHelpers.js +18 -13
  96. package/tests/unit/state/apply/balanceInitialization/nodeEntryBalanceUpdateFailureScenario.js +2 -1
  97. package/tests/unit/state/apply/banValidator/banValidatorBanAndReWhitelistScenario.js +2 -1
  98. package/tests/unit/state/apply/banValidator/banValidatorScenarioHelpers.js +27 -30
  99. package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentDuplicateRegistrationScenario.js +2 -1
  100. package/tests/unit/state/apply/bootstrapDeployment/bootstrapDeploymentScenarioHelpers.js +24 -21
  101. package/tests/unit/state/apply/common/access-control/adminConsistencyMismatchScenario.js +5 -4
  102. package/tests/unit/state/apply/common/access-control/adminPublicKeyDecodeFailureScenario.js +4 -3
  103. package/tests/unit/state/apply/common/balances/base/requesterBalanceScenarioBase.js +2 -1
  104. package/tests/unit/state/apply/common/commonScenarioHelper.js +16 -16
  105. package/tests/unit/state/apply/common/payload-structure/initializationDisabledScenario.js +10 -5
  106. package/tests/unit/state/apply/common/payload-structure/invalidHashValidationScenario.js +2 -2
  107. package/tests/unit/state/apply/common/requester/requesterNodeEntryBufferMissingScenario.js +2 -1
  108. package/tests/unit/state/apply/common/requester/requesterNodeEntryDecodeFailureScenario.js +2 -1
  109. package/tests/unit/state/apply/common/validatorConsistency/base/validatorConsistencyScenarioBase.js +2 -1
  110. package/tests/unit/state/apply/common/validatorEntryValidation/base/validatorEntryValidationScenarioBase.js +2 -1
  111. package/tests/unit/state/apply/disableInitialization/disableInitializationScenarioHelpers.js +16 -9
  112. package/tests/unit/state/apply/removeIndexer/removeIndexerScenarioHelpers.js +6 -5
  113. package/tests/unit/state/apply/removeWriter/removeWriterScenarioHelpers.js +23 -19
  114. package/tests/unit/state/apply/transfer/transferDoubleSpendAcrossValidatorsScenario.js +45 -36
  115. package/tests/unit/state/apply/transfer/transferScenarioHelpers.js +48 -45
  116. package/tests/unit/state/apply/txOperation/txOperationScenarioHelpers.js +32 -29
  117. package/tests/unit/state/apply/txOperation/txOperationTransferFeeGuardScenarioFactory.js +2 -1
  118. package/tests/unit/state/stateModule.test.js +0 -1
  119. package/tests/unit/state/stateTestUtils.js +7 -3
  120. package/tests/unit/state/utils/address.test.js +3 -3
  121. package/tests/unit/state/utils/adminEntry.test.js +10 -9
  122. package/tests/unit/unit.test.js +1 -1
  123. package/tests/unit/utils/buffer/buffer.test.js +62 -1
  124. package/tests/unit/utils/check/adminControlOperation.test.js +3 -3
  125. package/tests/unit/utils/check/balanceInitializationOperation.test.js +2 -2
  126. package/tests/unit/utils/check/bootstrapDeploymentOperation.test.js +2 -3
  127. package/tests/unit/utils/check/common.test.js +7 -6
  128. package/tests/unit/utils/check/coreAdminOperation.test.js +3 -3
  129. package/tests/unit/utils/check/roleAccessOperation.test.js +3 -2
  130. package/tests/unit/utils/check/transactionOperation.test.js +3 -3
  131. package/tests/unit/utils/check/transferOperation.test.js +3 -3
  132. package/tests/unit/utils/fileUtils/readAddressesFromWhitelistFile.test.js +2 -1
  133. package/tests/unit/utils/fileUtils/readBalanceMigrationFile.test.js +2 -1
  134. package/tests/unit/utils/migrationUtils/validateAddressFromIncomingFile.test.js +7 -0
  135. package/tests/unit/utils/normalizers/normalizers.test.js +469 -0
  136. package/tests/unit/utils/protobuf/operationHelpers.test.js +120 -2
  137. package/tests/unit/utils/utils.test.js +0 -1
  138. package/rpc/rpc_server.mjs +0 -10
  139. package/src/core/network/messaging/NetworkMessages.js +0 -63
  140. package/src/core/network/messaging/handlers/GetRequestHandler.js +0 -112
  141. package/src/core/network/messaging/handlers/ResponseHandler.js +0 -108
  142. package/src/core/network/messaging/handlers/RoleOperationHandler.js +0 -116
  143. package/src/core/network/messaging/handlers/SubnetworkOperationHandler.js +0 -143
  144. package/src/core/network/messaging/handlers/TransferOperationHandler.js +0 -52
  145. package/src/core/network/messaging/routes/NetworkMessageRouter.js +0 -94
  146. package/src/core/network/messaging/validators/AdminResponse.js +0 -58
  147. package/src/core/network/messaging/validators/CustomNodeResponse.js +0 -46
  148. package/src/core/state/utils/indexerEntry.js +0 -105
  149. package/src/messages/base/StateBuilder.js +0 -25
  150. package/src/messages/completeStateMessages/CompleteStateMessageBuilder.js +0 -421
  151. package/src/messages/completeStateMessages/CompleteStateMessageDirector.js +0 -252
  152. package/src/messages/completeStateMessages/CompleteStateMessageOperations.js +0 -299
  153. package/src/messages/partialStateMessages/PartialStateMessageBuilder.js +0 -272
  154. package/src/messages/partialStateMessages/PartialStateMessageDirector.js +0 -137
  155. package/src/messages/partialStateMessages/PartialStateMessageOperations.js +0 -131
  156. package/src/utils/crypto.js +0 -11
  157. package/tests/integration/apply/addAdmin/addAdminBasic.test.js +0 -68
  158. package/tests/integration/apply/addAdmin/addAdminRecovery.test.js +0 -125
  159. package/tests/integration/apply/addIndexer.test.js +0 -237
  160. package/tests/integration/apply/addWhitelist.test.js +0 -53
  161. package/tests/integration/apply/addWriter.test.js +0 -244
  162. package/tests/integration/apply/apply.test.js +0 -19
  163. package/tests/integration/apply/banValidator.test.js +0 -109
  164. package/tests/integration/apply/postTx/invalidSubValues.test.js +0 -103
  165. package/tests/integration/apply/postTx/postTx.test.js +0 -222
  166. package/tests/integration/apply/removeIndexer.test.js +0 -128
  167. package/tests/integration/apply/removeWriter.test.js +0 -167
  168. package/tests/integration/apply/transfer.test.js +0 -81
  169. package/tests/integration/integration.test.js +0 -9
  170. package/tests/unit/messageOperations/assembleAddIndexerMessage.test.js +0 -21
  171. package/tests/unit/messageOperations/assembleAddWriterMessage.test.js +0 -16
  172. package/tests/unit/messageOperations/assembleAdminMessage.test.js +0 -69
  173. package/tests/unit/messageOperations/assembleBanWriterMessage.test.js +0 -16
  174. package/tests/unit/messageOperations/assemblePostTransaction.test.js +0 -442
  175. package/tests/unit/messageOperations/assembleRemoveIndexerMessage.test.js +0 -19
  176. package/tests/unit/messageOperations/assembleRemoveWriterMessage.test.js +0 -17
  177. package/tests/unit/messageOperations/assembleWhitelistMessages.test.js +0 -58
  178. package/tests/unit/messageOperations/commonsStateMessageOperationsTest.js +0 -277
  179. package/tests/unit/messageOperations/stateMessageOperations.test.js +0 -19
  180. package/tests/unit/state/utils/indexerEntry.test.js +0 -83
  181. package/tests/unit/state/utils/transaction.test.js +0 -97
  182. package/tests/unit/utils/crypto/createHash.test.js +0 -15
  183. /package/rpc/{constants.mjs → constants.js} +0 -0
  184. /package/rpc/{cors.mjs → cors.js} +0 -0
  185. /package/rpc/utils/{confirmedParameter.mjs → confirmedParameter.js} +0 -0
  186. /package/rpc/utils/{url.mjs → url.js} +0 -0
  187. /package/src/utils/{operations.js → applyOperations.js} +0 -0
@@ -0,0 +1,84 @@
1
+ import b4a from "b4a";
2
+ import GetRequestHandler from "./handlers/GetRequestHandler.js";
3
+ import ResponseHandler from "./handlers/ResponseHandler.js";
4
+ import RoleOperationHandler from "../shared/handlers/RoleOperationHandler.js";
5
+ import SubnetworkOperationHandler from "../shared/handlers/SubnetworkOperationHandler.js";
6
+ import TransferOperationHandler from "../shared/handlers/TransferOperationHandler.js";
7
+ import { NETWORK_MESSAGE_TYPES } from '../../../../utils/constants.js';
8
+ import * as operation from '../../../../utils/applyOperations.js';
9
+ import State from "../../../state/State.js";
10
+ import PeerWallet from "trac-wallet";
11
+
12
+ class NetworkMessageRouter {
13
+ #handlers;
14
+ #config;
15
+
16
+ /**
17
+ * @param {State} state
18
+ * @param {PeerWallet} wallet
19
+ * @param {TransactionRateLimiterService} rateLimiterService
20
+ * @param {TransactionPoolService} txPoolService
21
+ * @param {ConnectionManager} connectionManager
22
+ * @param {object} config
23
+ **/
24
+ constructor(state, wallet, rateLimiterService, txPoolService, connectionManager, config) {
25
+ this.#config = config;
26
+
27
+ this.#handlers = {
28
+ get: new GetRequestHandler(wallet, state),
29
+ response: new ResponseHandler(state, wallet, connectionManager, this.#config),
30
+ roleTransaction: new RoleOperationHandler(state, wallet, rateLimiterService, txPoolService, this.#config),
31
+ subNetworkTransaction: new SubnetworkOperationHandler(state, wallet, rateLimiterService, txPoolService, this.#config),
32
+ tracNetworkTransaction: new TransferOperationHandler(state, wallet, rateLimiterService, txPoolService, this.#config),
33
+ }
34
+ }
35
+
36
+ // NOTE: messageProtomux can be deleted, ad this is a session, and we can extract this from connection
37
+ async route(incomingMessage, connection, messageProtomux) {
38
+ const channelString = b4a.toString(this.#config.channel, 'utf8');
39
+ if (this.#isGetRequest(incomingMessage)) {
40
+ await this.#handlers.get.handle(incomingMessage, messageProtomux, connection, channelString);
41
+ }
42
+ else if (this.#isResponse(incomingMessage)) {
43
+ await this.#handlers.response.handle(incomingMessage, connection, channelString);
44
+ }
45
+ else if (this.#isRoleAccessOperation(incomingMessage)) {
46
+ await this.#handlers.roleTransaction.handle(incomingMessage, connection);
47
+ }
48
+ else if (this.#isSubnetworkOperation(incomingMessage)) {
49
+ await this.#handlers.subNetworkTransaction.handle(incomingMessage, connection);
50
+ }
51
+ else if (this.#isTransferOperation(incomingMessage)) {
52
+ await this.#handlers.tracNetworkTransaction.handle(incomingMessage, connection);
53
+ }
54
+ else {
55
+ throw new Error(`Failed to route message. Pubkey of requester is ${connection.remotePublicKey ? b4a.toString(connection.remotePublicKey, 'hex') : 'unknown'}`);
56
+ }
57
+
58
+ }
59
+
60
+ #isGetRequest(message) {
61
+ return Object.values(NETWORK_MESSAGE_TYPES.GET).includes(message);
62
+ }
63
+
64
+
65
+ #isResponse(message) {
66
+ return Object.values(NETWORK_MESSAGE_TYPES.RESPONSE).includes(message.op);
67
+ }
68
+
69
+ #isRoleAccessOperation(message) {
70
+ return operation.isRoleAccess(message.type)
71
+ }
72
+
73
+ #isSubnetworkOperation(message) {
74
+ return operation.isTransaction(message.type) ||
75
+ operation.isBootstrapDeployment(message.type)
76
+ }
77
+
78
+ #isTransferOperation(message) {
79
+ return operation.isTransfer(message.type)
80
+ }
81
+ }
82
+
83
+
84
+ export default NetworkMessageRouter;
@@ -0,0 +1,53 @@
1
+ import { NETWORK_MESSAGE_TYPES } from '../../../../../utils/constants.js';
2
+ import PeerWallet from 'trac-wallet';
3
+ import b4a from 'b4a';
4
+
5
+ class GetRequestHandler {
6
+ #wallet;
7
+ #state;
8
+
9
+ constructor(wallet, state) {
10
+ this.#wallet = wallet;
11
+ this.#state = state;
12
+ }
13
+
14
+ get state() {
15
+ return this.#state;
16
+ }
17
+
18
+ async handle(message, messageProtomux, connection, channelString) {
19
+ switch (message) {
20
+ case NETWORK_MESSAGE_TYPES.GET.VALIDATOR:
21
+ await this.handleGetValidatorResponse(messageProtomux, connection, channelString);
22
+ break;
23
+ default:
24
+ throw new Error(`Unhandled GET type: ${message}`);
25
+ }
26
+ }
27
+
28
+ async handleGetValidatorResponse(messageProtomux, connection, channelString) {
29
+ const nonce = PeerWallet.generateNonce().toString('hex');
30
+ const payload = {
31
+ op: 'validatorResponse',
32
+ wk: this.state.writingKey.toString('hex'),
33
+ address: this.#wallet.address,
34
+ nonce: nonce,
35
+ channel: channelString,
36
+ issuer: connection.remotePublicKey.toString('hex'),
37
+ timestamp: Date.now(),
38
+ };
39
+
40
+
41
+ const hashInput = b4a.from(JSON.stringify(payload), 'utf8');
42
+ const hash = await PeerWallet.blake3(hashInput);
43
+ const sig = this.#wallet.sign(hash);
44
+
45
+ const responseMessage = {
46
+ ...payload,
47
+ sig: sig.toString('hex'),
48
+ };
49
+ messageProtomux.send(responseMessage);
50
+ }
51
+ }
52
+
53
+ export default GetRequestHandler;
@@ -0,0 +1,37 @@
1
+ import ValidatorResponse from '../validators/ValidatorResponse.js';
2
+ import PeerWallet from 'trac-wallet';
3
+
4
+ class ResponseHandler {
5
+ #responseValidator;
6
+ #connectionManager;
7
+
8
+
9
+ constructor(state, wallet, connectionManager ,config) {
10
+ this.#responseValidator = new ValidatorResponse(state, wallet, config);
11
+ this.#connectionManager = connectionManager;
12
+
13
+ }
14
+
15
+ async handle(message, connection, channelString) {
16
+ await this.#handleValidatorResponse(message, connection, channelString);
17
+ }
18
+
19
+ async #handleValidatorResponse(message, connection, channelString) {
20
+ const isValid = await this.#responseValidator.validate(message, channelString);
21
+ if (isValid) {
22
+ const validatorAddressString = message.address;
23
+ const validatorPublicKey = PeerWallet.decodeBech32m(validatorAddressString);
24
+
25
+ if (this.#connectionManager.connected(validatorPublicKey)) {
26
+ return;
27
+ // TODO: What we should return? Or maybe we should throw?
28
+ }
29
+
30
+ this.#connectionManager.addValidator(validatorPublicKey, connection)
31
+ } else {
32
+ throw new Error("Validator response verification failed");
33
+ }
34
+ }
35
+ }
36
+
37
+ export default ResponseHandler;
@@ -2,8 +2,8 @@ import b4a from 'b4a';
2
2
  import BaseResponse from './base/BaseResponse.js';
3
3
  class ValidatorResponse extends BaseResponse {
4
4
 
5
- constructor(state, wallet) {
6
- super(state, wallet);
5
+ constructor(state, wallet, config) {
6
+ super(state, wallet, config);
7
7
  }
8
8
 
9
9
  async validate(message, channelString) {
@@ -1,7 +1,6 @@
1
1
  import b4a from 'b4a';
2
2
  import PeerWallet from 'trac-wallet';
3
- import { bufferToAddress } from '../../../../state/utils/address.js';
4
- import { blake3Hash } from '../../../../../utils/crypto.js';
3
+ import State from '../../../../../state/State.js';
5
4
 
6
5
  /*
7
6
  BaseResponse class for handling common validation logic for network responses.
@@ -10,10 +9,18 @@ import { blake3Hash } from '../../../../../utils/crypto.js';
10
9
  class BaseResponse {
11
10
  #wallet;
12
11
  #state;
12
+ #config
13
13
 
14
- constructor(state, wallet) {
14
+ /**
15
+ *
16
+ * @param {State} state
17
+ * @param {PeerWallet} wallet
18
+ * @param {object} config
19
+ */
20
+ constructor(state, wallet, config) {
15
21
  this.#state = state;
16
22
  this.#wallet = wallet;
23
+ this.#config = config;
17
24
  }
18
25
 
19
26
  get state() {
@@ -63,8 +70,7 @@ class BaseResponse {
63
70
 
64
71
  break;
65
72
  default:
66
- const addressString = bufferToAddress(message.address);
67
- publicKey = PeerWallet.decodeBech32m(addressString);
73
+ publicKey = PeerWallet.decodeBech32m(message.address);
68
74
  }
69
75
 
70
76
  if (!publicKey) {
@@ -73,7 +79,8 @@ class BaseResponse {
73
79
 
74
80
  const messageWithoutSig = { ...message };
75
81
  delete messageWithoutSig.sig;
76
- const hash = await blake3Hash(JSON.stringify(messageWithoutSig));
82
+ const hashInput = b4a.from(JSON.stringify(messageWithoutSig), 'utf8');
83
+ const hash = await PeerWallet.blake3(hashInput);
77
84
  const signature = b4a.from(message.sig, 'hex');
78
85
  const verified = this.#wallet.verify(signature, hash, publicKey);
79
86
 
@@ -0,0 +1,88 @@
1
+ import {OperationType} from '../../../../../utils/constants.js';
2
+ import PartialRoleAccess from "../validators/PartialRoleAccess.js";
3
+ import BaseOperationHandler from './base/BaseOperationHandler.js';
4
+ import {applyStateMessageFactory} from "../../../../../messages/state/applyStateMessageFactory.js";
5
+ import {safeEncodeApplyOperation} from "../../../../../utils/protobuf/operationHelpers.js";
6
+ import {normalizeRoleAccessOperation} from "../../../../../utils/normalizers.js";
7
+
8
+ class RoleOperationHandler extends BaseOperationHandler {
9
+ #partialRoleAccessValidator;
10
+ #wallet;
11
+ #config;
12
+ #txPoolService;
13
+
14
+ /**
15
+ * @param {State} state
16
+ * @param {PeerWallet} wallet
17
+ * @param {TransactionRateLimiterService} rateLimiter
18
+ * @param {TransactionPoolService} txPoolService
19
+ * @param {object} config
20
+ **/
21
+ constructor(state, wallet, rateLimiter, txPoolService ,config) {
22
+ super(state, wallet, rateLimiter, txPoolService, config);
23
+ this.#wallet = wallet;
24
+ this.#config = config;
25
+ this.#partialRoleAccessValidator = new PartialRoleAccess(state, this.#wallet.address ,this.#config)
26
+ this.#txPoolService = txPoolService;
27
+ }
28
+
29
+ get partialRoleAccessValidator() {
30
+ return this.#partialRoleAccessValidator;
31
+ }
32
+
33
+ async handleOperation(message, connection) {
34
+ const normalizedPartialRoleAccessPayload = normalizeRoleAccessOperation(message, this.#config)
35
+ const isValid = await this.partialRoleAccessValidator.validate(normalizedPartialRoleAccessPayload)
36
+ let completePayload = null
37
+ if (!isValid) {
38
+ throw new Error("OperationHandler: partial role access payload validation failed.");
39
+ }
40
+
41
+ switch (normalizedPartialRoleAccessPayload.type) {
42
+ case OperationType.ADD_WRITER:
43
+ completePayload = await applyStateMessageFactory(this.#wallet, this.#config)
44
+ .buildCompleteAddWriterMessage(
45
+ normalizedPartialRoleAccessPayload.address,
46
+ normalizedPartialRoleAccessPayload.rao.tx,
47
+ normalizedPartialRoleAccessPayload.rao.txv,
48
+ normalizedPartialRoleAccessPayload.rao.iw,
49
+ normalizedPartialRoleAccessPayload.rao.in,
50
+ normalizedPartialRoleAccessPayload.rao.is,
51
+ )
52
+ break;
53
+ case OperationType.REMOVE_WRITER:
54
+ completePayload = await applyStateMessageFactory(this.#wallet, this.#config)
55
+ .buildCompleteRemoveWriterMessage(
56
+ normalizedPartialRoleAccessPayload.address,
57
+ normalizedPartialRoleAccessPayload.rao.tx,
58
+ normalizedPartialRoleAccessPayload.rao.txv,
59
+ normalizedPartialRoleAccessPayload.rao.iw,
60
+ normalizedPartialRoleAccessPayload.rao.in,
61
+ normalizedPartialRoleAccessPayload.rao.is,
62
+ )
63
+ break;
64
+ case OperationType.ADMIN_RECOVERY:
65
+
66
+ completePayload = await applyStateMessageFactory(this.#wallet, this.#config)
67
+ .buildCompleteAdminRecoveryMessage(
68
+ normalizedPartialRoleAccessPayload.address,
69
+ normalizedPartialRoleAccessPayload.rao.tx,
70
+ normalizedPartialRoleAccessPayload.rao.txv,
71
+ normalizedPartialRoleAccessPayload.rao.iw,
72
+ normalizedPartialRoleAccessPayload.rao.in,
73
+ normalizedPartialRoleAccessPayload.rao.is,
74
+ )
75
+ break;
76
+ default:
77
+ throw new Error("OperationHandler: Assembling complete role access operation failed due to unsupported operation type.");
78
+ }
79
+
80
+ if (!completePayload) {
81
+ throw new Error("OperationHandler: Assembling complete role access operation failed.");
82
+ }
83
+
84
+ this.#txPoolService.addTransaction(safeEncodeApplyOperation(completePayload))
85
+ }
86
+ }
87
+
88
+ export default RoleOperationHandler;
@@ -0,0 +1,93 @@
1
+ import BaseOperationHandler from './base/BaseOperationHandler.js';
2
+ import {
3
+ OperationType
4
+ } from '../../../../../utils/constants.js';
5
+ import PartialBootstrapDeployment from "../validators/PartialBootstrapDeployment.js";
6
+ import PartialTransaction from "../validators/PartialTransaction.js";
7
+ import {applyStateMessageFactory} from "../../../../../messages/state/applyStateMessageFactory.js";
8
+ import {safeEncodeApplyOperation} from "../../../../../utils/protobuf/operationHelpers.js";
9
+ import {
10
+ normalizeBootstrapDeploymentOperation,
11
+ normalizeTransactionOperation
12
+ } from "../../../../../utils/normalizers.js";
13
+
14
+
15
+ class SubnetworkOperationHandler extends BaseOperationHandler {
16
+ #partialBootstrapDeploymentValidator;
17
+ #partialTransactionValidator;
18
+ #config;
19
+ #wallet;
20
+ #txPoolService;
21
+
22
+ /**
23
+ * @param {State} state
24
+ * @param {PeerWallet} wallet
25
+ * @param {TransactionRateLimiterService} rateLimiter
26
+ * @param {TransactionPoolService} txPoolService
27
+ * @param {object} config
28
+ **/
29
+ constructor( state, wallet, rateLimiter, txPoolService, config) {
30
+ super(state, wallet, rateLimiter, txPoolService, config);
31
+ this.#config = config;
32
+ this.#wallet = wallet
33
+ this.#partialBootstrapDeploymentValidator = new PartialBootstrapDeployment(state, this.#wallet.address, config);
34
+ this.#partialTransactionValidator = new PartialTransaction(state, this.#wallet.address, config);
35
+ this.#txPoolService = txPoolService;
36
+ }
37
+
38
+ async handleOperation(payload, connection) {
39
+ if (payload.type === OperationType.TX) {
40
+ await this.#partialTransactionSubHandler(payload, connection);
41
+ } else if (payload.type === OperationType.BOOTSTRAP_DEPLOYMENT) {
42
+ await this.#partialBootstrapDeploymentSubHandler(payload, connection);
43
+ } else {
44
+ throw new Error('Unsupported operation type for SubnetworkOperationHandler');
45
+ }
46
+ }
47
+
48
+ async #partialTransactionSubHandler(payload, connection) {
49
+ const normalizedPayload = normalizeTransactionOperation(payload, this.#config);
50
+ const isValid = await this.#partialTransactionValidator.validate(normalizedPayload);
51
+ if (!isValid) {
52
+ throw new Error("SubnetworkHandler: Transaction validation failed.");
53
+ }
54
+
55
+ const completeTransactionOperation = await applyStateMessageFactory(this.#wallet,this.#config)
56
+ .buildCompleteTransactionOperationMessage(
57
+ normalizedPayload.address,
58
+ normalizedPayload.txo.tx,
59
+ normalizedPayload.txo.txv,
60
+ normalizedPayload.txo.iw,
61
+ normalizedPayload.txo.in,
62
+ normalizedPayload.txo.ch,
63
+ normalizedPayload.txo.is,
64
+ normalizedPayload.txo.bs,
65
+ normalizedPayload.txo.mbs
66
+ )
67
+ this.#txPoolService.addTransaction(safeEncodeApplyOperation(completeTransactionOperation));
68
+ }
69
+
70
+ async #partialBootstrapDeploymentSubHandler(payload, connection) {
71
+ const normalizedPayload = normalizeBootstrapDeploymentOperation(payload, this.#config);
72
+ const isValid = await this.#partialBootstrapDeploymentValidator.validate(normalizedPayload);
73
+ if (!isValid) {
74
+ throw new Error("SubnetworkHandler: Bootstrap deployment validation failed.");
75
+ }
76
+
77
+
78
+ const completeBootstrapDeploymentOperation = await applyStateMessageFactory(this.#wallet, this.#config)
79
+ .buildCompleteBootstrapDeploymentMessage(
80
+ normalizedPayload.address,
81
+ normalizedPayload.bdo.tx,
82
+ normalizedPayload.bdo.txv,
83
+ normalizedPayload.bdo.bs,
84
+ normalizedPayload.bdo.ic,
85
+ normalizedPayload.bdo.in,
86
+ normalizedPayload.bdo.is
87
+ )
88
+ this.#txPoolService.addTransaction(safeEncodeApplyOperation(completeBootstrapDeploymentOperation));
89
+
90
+ }
91
+ }
92
+
93
+ export default SubnetworkOperationHandler;
@@ -0,0 +1,57 @@
1
+ import BaseOperationHandler from './base/BaseOperationHandler.js';
2
+ import {OperationType} from '../../../../../utils/constants.js';
3
+ import PartialTransfer from "../validators/PartialTransfer.js";
4
+ import {normalizeTransferOperation} from "../../../../../utils/normalizers.js"
5
+ import {applyStateMessageFactory} from "../../../../../messages/state/applyStateMessageFactory.js";
6
+ import {safeEncodeApplyOperation} from "../../../../../utils/protobuf/operationHelpers.js";
7
+
8
+ class TransferOperationHandler extends BaseOperationHandler {
9
+ #partialTransferValidator;
10
+ #config;
11
+ #wallet;
12
+ #txPoolService;
13
+
14
+ /**
15
+ * @param {State} state
16
+ * @param {PeerWallet} wallet
17
+ * @param {TransactionRateLimiterService} rateLimiter
18
+ * @param {object} config
19
+ **/
20
+ constructor(state, wallet, rateLimiter, txPoolService, config) {
21
+ super(state, wallet, rateLimiter, txPoolService, config);
22
+ this.#config = config;
23
+ this.#wallet = wallet;
24
+ this.#partialTransferValidator = new PartialTransfer(state, this.#wallet.address, this.#config);
25
+ this.#txPoolService = txPoolService;
26
+ }
27
+
28
+ async handleOperation(payload, connection) {
29
+ if (payload.type !== OperationType.TRANSFER) {
30
+ throw new Error('Unsupported operation type for TransferOperationHandler');
31
+ }
32
+ await this.#handleTransfer(payload, connection);
33
+ }
34
+
35
+ async #handleTransfer(payload, connection) {
36
+ const normalizedPayload = normalizeTransferOperation(payload, this.#config);
37
+ const isValid = await this.#partialTransferValidator.validate(normalizedPayload);
38
+ if (!isValid) {
39
+ throw new Error("TransferHandler: Transfer validation failed.");
40
+ }
41
+
42
+ const completeTransferOperation = await applyStateMessageFactory(this.#wallet, this.#config)
43
+ .buildCompleteTransferOperationMessage(
44
+ normalizedPayload.address,
45
+ normalizedPayload.tro.tx,
46
+ normalizedPayload.tro.txv,
47
+ normalizedPayload.tro.in,
48
+ normalizedPayload.tro.to,
49
+ normalizedPayload.tro.am,
50
+ normalizedPayload.tro.is
51
+ )
52
+
53
+ this.#txPoolService.addTransaction(safeEncodeApplyOperation(completeTransferOperation));
54
+ }
55
+ }
56
+
57
+ export default TransferOperationHandler;
@@ -1,49 +1,44 @@
1
1
  import b4a from 'b4a';
2
- import {MAX_PARTIAL_TX_PAYLOAD_BYTE_SIZE, TRANSACTION_POOL_SIZE, MAX_WRITERS_FOR_ADMIN_INDEXER_CONNECTION} from '../../../../../utils/constants.js';
2
+ import {MAX_PARTIAL_TX_PAYLOAD_BYTE_SIZE, TRANSACTION_POOL_SIZE} from '../../../../../../utils/constants.js';
3
+
3
4
  class BaseOperationHandler {
4
- #network;
5
5
  #state;
6
6
  #wallet;
7
7
  #rateLimiter;
8
- #disable_rate_limit;
9
- #options;
10
- constructor(network, state, wallet, rateLimiter, options = {}) {
8
+ #txPoolService;
9
+ #config;
10
+
11
+ /**
12
+ * @param {State} state
13
+ * @param {PeerWallet} wallet
14
+ * @param {TransactionRateLimiterService} rateLimiter
15
+ * @param {TransactionPoolService} txPoolService
16
+ * @param {object} config
17
+ **/
18
+ constructor(state, wallet, rateLimiter, txPoolService, config) {
11
19
  if (new.target === BaseOperationHandler) {
12
20
  throw new Error('BaseOperationHandler is abstract and cannot be instantiated directly');
13
21
  }
14
- this.#network = network;
15
22
  this.#state = state;
16
23
  this.#wallet = wallet;
17
24
  this.#rateLimiter = rateLimiter;
18
- this.#disable_rate_limit = options.disable_rate_limit === true;
19
- this.#options = options;
20
- }
21
- get network() {
22
- return this.#network;
23
- }
24
- get state() {
25
- return this.#state;
25
+ this.#txPoolService = txPoolService;
26
+ this.#config = config;
26
27
  }
27
- get wallet() {
28
- return this.#wallet;
29
- }
30
- get options() {
31
- return this.#options;
32
- }
33
-
28
+
34
29
  async validateBasicRequirements(payload, connection) {
35
30
  // Validate if operation can be processed:
36
31
  // - Non-writable nodes cannot process operations
37
32
  // - Regular indexers cannot process operations
38
33
  // - Admin-indexer can process operations only when network has less than MAX_WRITERS_FOR_ADMIN_INDEXER_CONNECTION writers
39
- const isAllowedToValidate = await this.state.allowedToValidate(this.wallet.address);
40
- const isAdminAllowedToValidate = await this.state.isAdminAllowedToValidate();
34
+ const isAllowedToValidate = await this.#state.allowedToValidate(this.#wallet.address);
35
+ const isAdminAllowedToValidate = await this.#state.isAdminAllowedToValidate();
41
36
  const canValidate = isAllowedToValidate || isAdminAllowedToValidate;
42
37
  if (!canValidate) {
43
38
  throw new Error('OperationHandler: State is not writable or is an indexer without admin privileges.');
44
39
  }
45
40
 
46
- if (this.network.transactionPoolService.tx_pool.length >= TRANSACTION_POOL_SIZE) {
41
+ if (this.#txPoolService.tx_pool.length >= TRANSACTION_POOL_SIZE) {
47
42
  throw new Error("OperationHandler: Transaction pool is full, ignoring incoming transaction.");
48
43
  }
49
44
 
@@ -51,8 +46,8 @@ class BaseOperationHandler {
51
46
  throw new Error(`OperationHandler: Payload size exceeds maximum limit of ${MAX_PARTIAL_TX_PAYLOAD_BYTE_SIZE} bytes by ${b4a.byteLength(JSON.stringify(payload)) - MAX_PARTIAL_TX_PAYLOAD_BYTE_SIZE} bytes.`);
52
47
  }
53
48
 
54
- if (this.#disable_rate_limit !== true) {
55
- const shouldDisconnect = this.#rateLimiter.handleRateLimit(connection, this.network);
49
+ if (!this.#config.disableRateLimit) {
50
+ const shouldDisconnect = this.#rateLimiter.handleRateLimit(connection);
56
51
  if (shouldDisconnect) {
57
52
  throw new Error(`OperationHandler: Rate limit exceeded for peer ${b4a.toString(connection.remotePublicKey, 'hex')}. Disconnecting...`);
58
53
  }
@@ -1,13 +1,13 @@
1
1
  import PartialOperation from './base/PartialOperation.js';
2
2
 
3
-
4
3
  class PartialBootstrapDeployment extends PartialOperation {
5
- constructor(state) {
6
- super(state);
4
+ constructor(state, selfAddress , config) {
5
+ super(state, selfAddress , config);
7
6
  }
8
7
 
9
8
  async validate(payload) {
10
9
  this.isPayloadSchemaValid(payload);
10
+ this.validateNoSelfValidation(payload);
11
11
  this.validateRequesterAddress(payload);
12
12
  await this.validateTransactionUniqueness(payload);
13
13
  await this.validateSignature(payload);
@@ -1,17 +1,20 @@
1
1
  import b4a from 'b4a';
2
-
3
- import { OperationType } from "../../../../utils/constants.js";
4
- import { bufferToAddress } from "../../../state/utils/address.js";
2
+ import {OperationType} from "../../../../../utils/constants.js";
3
+ import {bufferToAddress} from "../../../../state/utils/address.js";
5
4
  import PartialOperation from './base/PartialOperation.js';
6
- import { bufferToBigInt } from "../../../../utils/amountSerialization.js";
5
+ import {bufferToBigInt} from "../../../../../utils/amountSerialization.js";
7
6
 
8
7
  class PartialRoleAccess extends PartialOperation {
9
- constructor(state) {
10
- super(state);
8
+ #config;
9
+
10
+ constructor(state, selfAddress, config) {
11
+ super(state, selfAddress, config);
12
+ this.#config = config
11
13
  }
12
14
 
13
15
  async validate(payload) {
14
16
  this.isPayloadSchemaValid(payload);
17
+ this.validateNoSelfValidation(payload);
15
18
  this.validateRequesterAddress(payload);
16
19
  await this.validateTransactionUniqueness(payload);
17
20
  await this.validateSignature(payload);
@@ -33,10 +36,10 @@ class PartialRoleAccess extends PartialOperation {
33
36
  }
34
37
 
35
38
  async isRequesterAllowedToChangeRole(payload) {
36
- const { type } = payload;
39
+ const {type} = payload;
37
40
 
38
41
  if (type === OperationType.ADD_WRITER) {
39
- const nodeAddress = bufferToAddress(payload.address);
42
+ const nodeAddress = bufferToAddress(payload.address, this.#config.addressPrefix);
40
43
  const nodeEntry = await this.state.getNodeEntry(nodeAddress);
41
44
  if (!nodeEntry) {
42
45
  throw new Error(`Node with address ${nodeAddress} entry does not exist.`);
@@ -54,7 +57,7 @@ class PartialRoleAccess extends PartialOperation {
54
57
  return;
55
58
 
56
59
  } else if (type === OperationType.REMOVE_WRITER) {
57
- const nodeAddress = bufferToAddress(payload.address);
60
+ const nodeAddress = bufferToAddress(payload.address, this.#config.addressPrefix);
58
61
  const nodeEntry = await this.state.getNodeEntry(nodeAddress);
59
62
  if (!nodeEntry) {
60
63
  throw new Error(`Node with address ${nodeAddress} entry does not exist.`);
@@ -78,7 +81,7 @@ class PartialRoleAccess extends PartialOperation {
78
81
  }
79
82
 
80
83
  const adminAddressBuffer = payload.address;
81
- const adminAddress = bufferToAddress(adminAddressBuffer);
84
+ const adminAddress = bufferToAddress(adminAddressBuffer, this.#config.addressPrefix);
82
85
  const isRecoveryCase = !!(
83
86
  adminEntry.address === adminAddress &&
84
87
  !b4a.equals(payload.rao.iw, adminEntry.wk)
@@ -94,7 +97,7 @@ class PartialRoleAccess extends PartialOperation {
94
97
  }
95
98
 
96
99
  async validateWriterKey(payload) {
97
- const requesterAddress = bufferToAddress(payload.address);
100
+ const requesterAddress = bufferToAddress(payload.address, this.#config.addressPrefix);
98
101
  const nodeEntry = await this.state.getNodeEntry(requesterAddress);
99
102
  if (!nodeEntry) {
100
103
  throw new Error(`Node entry not found for address ${requesterAddress}`);
@@ -114,7 +117,7 @@ class PartialRoleAccess extends PartialOperation {
114
117
  }
115
118
 
116
119
  async validateRequesterBalanceForAddWriterOperation(payload, signed = false) {
117
- const requesterAddress = bufferToAddress(payload.address);
120
+ const requesterAddress = bufferToAddress(payload.address, this.#config.addressPrefix);
118
121
  let requesterEntry;
119
122
  if (signed) {
120
123
  requesterEntry = await this.state.getNodeEntry(requesterAddress);