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
@@ -1,63 +0,0 @@
1
-
2
- import Protomux from 'protomux';
3
- import b4a from 'b4a';
4
- import c from 'compact-encoding';
5
- import NetworkMessageRouter from './routes/NetworkMessageRouter.js';
6
-
7
- class NetworkMessages {
8
- #messageRouter;
9
- #network;
10
- #options;
11
-
12
- constructor(network, options = {}) {
13
- this.#network = network;
14
- this.#options = options;
15
- }
16
-
17
- get network() {
18
- return this.#network;
19
- }
20
-
21
- initializeMessageRouter(state, wallet) {
22
- this.#messageRouter = new NetworkMessageRouter(
23
- this.network,
24
- state,
25
- wallet,
26
- this.#options
27
- );
28
- }
29
-
30
- async setupProtomuxMessages(connection) {
31
- const mux = Protomux.from(connection);
32
- connection.userData = mux;
33
- const message_channel = mux.createChannel({
34
- protocol: b4a.toString(this.network.channel, 'utf8'),
35
- onopen() { },
36
- onclose() { }
37
- });
38
-
39
- message_channel.open();
40
-
41
- const messageProtomux = message_channel.addMessage({
42
- encoding: c.json,
43
- onmessage: async (incomingMessage) => {
44
- try {
45
- if (typeof incomingMessage === 'object' || typeof incomingMessage === 'string') {
46
- await this.#messageRouter.route(incomingMessage, connection, messageProtomux);
47
- } else {
48
- throw new Error('NetworkMessages: Received message is undefined');
49
- }
50
- } catch (error) {
51
- console.error(`NetworkMessages: Failed to handle incoming message: ${error.message}`);
52
- } finally {
53
- this.network.swarm.leavePeer(connection.remotePublicKey);
54
- }
55
- }
56
- });
57
-
58
- connection.messenger = messageProtomux;
59
- return { message_channel, message: messageProtomux };
60
- }
61
- }
62
-
63
- export default NetworkMessages;
@@ -1,112 +0,0 @@
1
- import { NETWORK_MESSAGE_TYPES } from '../../../../utils/constants.js';
2
- import PeerWallet from 'trac-wallet';
3
- import b4a from 'b4a';
4
- import { blake3Hash } from '../../../../utils/crypto.js';
5
-
6
- class GetRequestHandler {
7
- #wallet;
8
- #state;
9
-
10
- constructor(wallet, state) {
11
- this.#wallet = wallet;
12
- this.#state = state;
13
- }
14
-
15
- get state() {
16
- return this.#state;
17
- }
18
-
19
- async handle(message, messageProtomux, connection, channelString) {
20
- switch (message) {
21
- case NETWORK_MESSAGE_TYPES.GET.VALIDATOR:
22
- await this.handleGetValidatorResponse(messageProtomux, connection, channelString);
23
- break;
24
- case NETWORK_MESSAGE_TYPES.GET.ADMIN:
25
- await this.handleGetAdminRequest(messageProtomux, connection, channelString);
26
- break;
27
- case NETWORK_MESSAGE_TYPES.GET.NODE:
28
- await this.handleCustomNodeRequest(messageProtomux, connection, channelString);
29
- break;
30
- default:
31
- throw new Error(`Unhandled GET type: ${message}`);
32
- }
33
- }
34
-
35
- async handleGetValidatorResponse(messageProtomux, connection, channelString) {
36
- const nonce = PeerWallet.generateNonce().toString('hex');
37
- const payload = {
38
- op: 'validatorResponse',
39
- wk: this.state.writingKey.toString('hex'),
40
- address: this.#wallet.address,
41
- nonce: nonce,
42
- channel: channelString,
43
- issuer: connection.remotePublicKey.toString('hex'),
44
- timestamp: Date.now(),
45
- };
46
-
47
- const hash = await blake3Hash(JSON.stringify(payload));
48
- const sig = this.#wallet.sign(hash);
49
-
50
- const responseMessage = {
51
- ...payload,
52
- sig: sig.toString('hex'),
53
- };
54
- messageProtomux.send(responseMessage);
55
- }
56
-
57
- async handleGetAdminRequest(messageProtomux, connection, channelString) {
58
- const adminEntry = await this.state.getAdminEntry();
59
- if (adminEntry === null) {
60
- throw new Error("Admin entry is null. This is not possible to create admin stream.");
61
- }
62
-
63
- const adminPublicKey = PeerWallet.decodeBech32m(adminEntry.address);
64
-
65
- if (!b4a.equals(this.#wallet.publicKey, adminPublicKey)) {
66
- throw new Error("You are not an admin. This is not possible to create admin stream.");
67
- }
68
-
69
- const nonce = PeerWallet.generateNonce().toString('hex');
70
- const payload = {
71
- op: 'adminResponse',
72
- wk: this.state.writingKey.toString('hex'),
73
- address: this.#wallet.address,
74
- nonce: nonce,
75
- channel: channelString,
76
- issuer: connection.remotePublicKey.toString('hex'),
77
- timestamp: Date.now(),
78
- };
79
- const hash = await blake3Hash(JSON.stringify(payload));
80
- const sig = this.#wallet.sign(hash);
81
-
82
- const responseMessage = {
83
- ...payload,
84
- sig: sig.toString('hex'),
85
- };
86
- messageProtomux.send(responseMessage);
87
- }
88
-
89
- async handleCustomNodeRequest(messageProtomux, connection, channelString) {
90
- const nonce = PeerWallet.generateNonce().toString('hex');
91
- const payload = {
92
- op: 'nodeResponse',
93
- address: this.#wallet.address,
94
- nonce: nonce,
95
- channel: channelString,
96
- issuer: connection.remotePublicKey.toString('hex'),
97
- timestamp: Date.now(),
98
- };
99
-
100
- const hash = await blake3Hash(JSON.stringify(payload));
101
- const sig = this.#wallet.sign(hash);
102
-
103
- const responseMessage = {
104
- ...payload,
105
- sig: sig.toString('hex'),
106
- };
107
- messageProtomux.send(responseMessage);
108
-
109
- }
110
- }
111
-
112
- export default GetRequestHandler;
@@ -1,108 +0,0 @@
1
- import { NETWORK_MESSAGE_TYPES } from '../../../../utils/constants.js';
2
- import ValidatorResponse from '../validators/ValidatorResponse.js';
3
- import AdminResponse from '../validators/AdminResponse.js';
4
- import CustomNodeResponse from '../validators/CustomNodeResponse.js';
5
- import PeerWallet from 'trac-wallet';
6
- import b4a from "b4a";
7
-
8
- class ResponseHandler {
9
- #network;
10
- #state;
11
- #responseValidator;
12
- #adminValidator;
13
- #customNodeValidator;
14
-
15
- constructor(network, state, wallet) {
16
- this.#network = network;
17
- this.#state = state;
18
- this.#responseValidator = new ValidatorResponse(this.state, wallet);
19
- this.#adminValidator = new AdminResponse(this.state, wallet);
20
- this.#customNodeValidator = new CustomNodeResponse(this.state, wallet);
21
-
22
- }
23
-
24
- get network() {
25
- return this.#network;
26
- }
27
-
28
- get state() {
29
- return this.#state;
30
- }
31
-
32
- get responseValidator() {
33
- return this.#responseValidator;
34
- }
35
-
36
- get adminValidator() {
37
- return this.#adminValidator;
38
- }
39
-
40
- get customNodeValidator() {
41
- return this.#customNodeValidator;
42
- }
43
-
44
- async handle(message, connection, channelString) {
45
- switch (message.op) {
46
- case NETWORK_MESSAGE_TYPES.RESPONSE.VALIDATOR:
47
- await this.#handleValidatorResponse(message, connection, channelString);
48
- break;
49
- case NETWORK_MESSAGE_TYPES.RESPONSE.ADMIN:
50
- await this.#handleAdminResponse(message, connection, channelString);
51
- break;
52
- case NETWORK_MESSAGE_TYPES.RESPONSE.NODE:
53
- await this.#handleCustomNodeResponse(message, connection, channelString);
54
- break;
55
- default:
56
- throw new Error(`Unhandled RESPONSE type: ${message}`);
57
- }
58
- }
59
-
60
- async #handleValidatorResponse(message, connection, channelString) {
61
- const isValid = await this.responseValidator.validate(message, channelString);
62
- if (isValid) {
63
- const validatorAddressString = message.address;
64
- const validatorPublicKey = PeerWallet.decodeBech32m(validatorAddressString);
65
-
66
- if (this.network.validatorConnectionManager.connected(validatorPublicKey)) {
67
- return;
68
- }
69
-
70
- console.log('Validator stream established', validatorAddressString);
71
- this.network.validatorConnectionManager.addValidator(validatorPublicKey, connection)
72
- } else {
73
- throw new Error("Validator response verification failed");
74
- }
75
- }
76
-
77
- async #handleAdminResponse(message, connection, channelString) {
78
- const isValid = await this.adminValidator.validate(message, channelString);
79
- if (isValid) {
80
- const adminEntry = await this.state.getAdminEntry();
81
- const adminPublicKey = PeerWallet.decodeBech32m(adminEntry.address);
82
-
83
- console.log('Admin stream established:', adminEntry.address);
84
- this.network.admin_stream = connection;
85
- this.network.admin = adminPublicKey;
86
- } else {
87
- throw new Error("Admin response verification failed");
88
- }
89
- }
90
-
91
- async #handleCustomNodeResponse(message, connection, channelString) {
92
- const isValid = await this.customNodeValidator.validate(message, channelString);
93
- if (isValid) {
94
- const customNodeAddressString = message.address;
95
- const customNodePublicKey = PeerWallet.decodeBech32m(customNodeAddressString);
96
-
97
- console.log('Custom node stream established:', customNodeAddressString);
98
- this.network.custom_stream = connection;
99
- this.network.custom_node = customNodePublicKey;
100
- } else {
101
- throw new Error("Custom node response verification failed");
102
- }
103
- }
104
-
105
-
106
- }
107
-
108
- export default ResponseHandler;
@@ -1,116 +0,0 @@
1
- import {OperationType} from '../../../../utils/constants.js';
2
- import PartialRoleAccess from "../validators/PartialRoleAccess.js";
3
- import {addressToBuffer} from "../../../state/utils/address.js";
4
- import CompleteStateMessageOperations
5
- from "../../../../messages/completeStateMessages/CompleteStateMessageOperations.js";
6
- import {normalizeHex} from "../../../../utils/helpers.js";
7
- import BaseOperationHandler from './base/BaseOperationHandler.js';
8
-
9
- class RoleOperationHandler extends BaseOperationHandler {
10
- #partialRoleAccessValidator;
11
- #wallet;
12
- #network;
13
-
14
- constructor(network, state, wallet, rateLimiter, options = {}) {
15
- super(network, state, wallet, rateLimiter, options);
16
- this.#wallet = wallet;
17
- this.#network = network;
18
- this.#partialRoleAccessValidator = new PartialRoleAccess(state)
19
- }
20
-
21
- get wallet() {
22
- return this.#wallet;
23
- }
24
-
25
- get network() {
26
- return this.#network;
27
- }
28
-
29
- get partialRoleAccessValidator() {
30
- return this.#partialRoleAccessValidator;
31
- }
32
-
33
- async handleOperation(message, connection) {
34
- const normalizedPartialRoleAccessPayload = this.#normalizePartialRoleAccess(message)
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 CompleteStateMessageOperations.assembleAddWriterMessage(
44
- this.wallet,
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 CompleteStateMessageOperations.assembleRemoveWriterMessage(
55
- this.wallet,
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
- completePayload = await CompleteStateMessageOperations.assembleAdminRecoveryMessage(
66
- this.wallet,
67
- normalizedPartialRoleAccessPayload.address,
68
- normalizedPartialRoleAccessPayload.rao.tx,
69
- normalizedPartialRoleAccessPayload.rao.txv,
70
- normalizedPartialRoleAccessPayload.rao.iw,
71
- normalizedPartialRoleAccessPayload.rao.in,
72
- normalizedPartialRoleAccessPayload.rao.is,
73
- );
74
- console.log("Assembled complete role access operation:", completePayload);
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.network.transactionPoolService.addTransaction(completePayload)
85
- }
86
-
87
- #normalizePartialRoleAccess(payload) {
88
- if (!payload || typeof payload !== 'object' || !payload.rao) {
89
- throw new Error('Invalid payload for bootstrap deployment normalization.');
90
- }
91
- const {type, address, rao} = payload;
92
- if (
93
- !type ||
94
- !address ||
95
- !rao.tx || !rao.txv || !rao.iw || !rao.in || !rao.is
96
- ) {
97
- throw new Error('Missing required fields in bootstrap deployment payload.');
98
- }
99
-
100
- const normalizedRao = {
101
- tx: normalizeHex(rao.tx),
102
- txv: normalizeHex(rao.txv),
103
- iw: normalizeHex(rao.iw),
104
- in: normalizeHex(rao.in),
105
- is: normalizeHex(rao.is)
106
- };
107
-
108
- return {
109
- type,
110
- address: addressToBuffer(address),
111
- rao: normalizedRao
112
- };
113
- }
114
- }
115
-
116
- export default RoleOperationHandler;
@@ -1,143 +0,0 @@
1
- import BaseOperationHandler from './base/BaseOperationHandler.js';
2
- import CompleteStateMessageOperations from "../../../../messages/completeStateMessages/CompleteStateMessageOperations.js";
3
- import {
4
- OperationType
5
- } from '../../../../utils/constants.js';
6
- import PartialBootstrapDeployment from "../validators/PartialBootstrapDeployment.js";
7
- import {addressToBuffer, bufferToAddress} from "../../../state/utils/address.js";
8
- import PartialTransaction from "../validators/PartialTransaction.js";
9
- import {normalizeHex} from "../../../../utils/helpers.js";
10
-
11
- /**
12
- * THIS CLASS IS ULTRA IMPORTANT BECAUSE IF SOMEONE WILL SEND A TRASH TO VALIDATOR AND IT WON'T BE HANDLED PROPERTLY -
13
- * FOR EXAMPLE VALIDATOR WILL BROADCAST IT TO THE INDEXER LAYER THEN IT WILL BE BANNED. SO EVERYTHING WHAT IS TRASH
14
- * MUST BE REFUSED.
15
- * TODO: WE SHOULD AUDIT VALIDATORS AND MAKE SURE THEY ARE NOT BROADCASTING TRASH TO THE INDEXER LAYER.
16
- */
17
-
18
- class SubnetworkOperationHandler extends BaseOperationHandler {
19
- #partialBootstrapDeploymentValidator;
20
- #partialTransactionValidator;
21
-
22
- constructor(network, state, wallet, rateLimiter, options = {}) {
23
- super(network, state, wallet, rateLimiter, options);
24
- this.#partialBootstrapDeploymentValidator = new PartialBootstrapDeployment(this.state);
25
- this.#partialTransactionValidator = new PartialTransaction(this.state);
26
- }
27
-
28
- async handleOperation(payload) {
29
- if (payload.type === OperationType.TX) {
30
- await this.#partialTransactionSubHandler(payload);
31
- } else if (payload.type === OperationType.BOOTSTRAP_DEPLOYMENT) {
32
- await this.#partialBootstrapDeploymentSubHandler(payload);
33
- } else {
34
- throw new Error('Unsupported operation type for SubnetworkOperationHandler');
35
- }
36
- }
37
-
38
- async #partialTransactionSubHandler(payload) {
39
- const normalizedPayload = this.#normalizeTransactionOperation(payload);
40
- const isValid = await this.#partialTransactionValidator.validate(normalizedPayload);
41
- if (!isValid) {
42
- throw new Error("SubnetworkHandler: Transaction validation failed.");
43
- }
44
-
45
- const completeTransactionOperation = await CompleteStateMessageOperations.assembleCompleteTransactionOperationMessage(
46
- this.wallet,
47
- normalizedPayload.address,
48
- normalizedPayload.txo.tx,
49
- normalizedPayload.txo.txv,
50
- normalizedPayload.txo.iw,
51
- normalizedPayload.txo.in,
52
- normalizedPayload.txo.ch,
53
- normalizedPayload.txo.is,
54
- normalizedPayload.txo.bs,
55
- normalizedPayload.txo.mbs
56
- );
57
- this.network.transactionPoolService.addTransaction(completeTransactionOperation);
58
- }
59
-
60
- async #partialBootstrapDeploymentSubHandler(payload) {
61
- const normalizedPayload = this.#normalizeBootstrapDeployment(payload);
62
- const isValid = await this.#partialBootstrapDeploymentValidator.validate(normalizedPayload);
63
- if (!isValid) {
64
- throw new Error("SubnetworkHandler: Bootstrap deployment validation failed.");
65
- }
66
-
67
- const completeBootstrapDeploymentOperation = await CompleteStateMessageOperations.assembleCompleteBootstrapDeployment(
68
- this.wallet,
69
- normalizedPayload.address,
70
- normalizedPayload.bdo.tx,
71
- normalizedPayload.bdo.txv,
72
- normalizedPayload.bdo.bs,
73
- normalizedPayload.bdo.ic,
74
- normalizedPayload.bdo.in,
75
- normalizedPayload.bdo.is,
76
- )
77
- this.network.transactionPoolService.addTransaction(completeBootstrapDeploymentOperation);
78
-
79
- }
80
-
81
- #normalizeBootstrapDeployment(payload) {
82
- if (!payload || typeof payload !== 'object' || !payload.bdo) {
83
- throw new Error('Invalid payload for bootstrap deployment normalization.');
84
- }
85
- const {type, address, bdo} = payload;
86
- if (
87
- type !== OperationType.BOOTSTRAP_DEPLOYMENT ||
88
- !address ||
89
- !bdo.tx || !bdo.bs || !bdo.in || !bdo.is || !bdo.txv
90
- ) {
91
- throw new Error('Missing required fields in bootstrap deployment payload.');
92
- }
93
-
94
- const normalizedBdo = {
95
- tx: normalizeHex(bdo.tx), // Transaction hash
96
- txv: normalizeHex(bdo.txv), // Transaction validity
97
- bs: normalizeHex(bdo.bs), // External bootstrap
98
- ic: normalizeHex(bdo.ic), // Channel
99
- in: normalizeHex(bdo.in), // Nonce
100
- is: normalizeHex(bdo.is) // Signature
101
- };
102
-
103
- return {
104
- type,
105
- address: addressToBuffer(address),
106
- bdo: normalizedBdo
107
- };
108
- }
109
-
110
- #normalizeTransactionOperation(payload) {
111
- if (!payload || typeof payload !== 'object' || !payload.txo) {
112
- throw new Error('Invalid payload for transaction operation normalization.');
113
- }
114
- const {type, address, txo} = payload;
115
- if (
116
- type !== OperationType.TX ||
117
- !address ||
118
- !txo.tx || !txo.txv || !txo.iw || !txo.in ||
119
- !txo.ch || !txo.is || !txo.bs || !txo.mbs
120
- ) {
121
- throw new Error('Missing required fields in transaction operation payload.');
122
- }
123
-
124
- const normalizedTxo = {
125
- tx: normalizeHex(txo.tx), // Transaction hash
126
- txv: normalizeHex(txo.txv), // Transaction validity
127
- iw: normalizeHex(txo.iw), // Writing key
128
- in: normalizeHex(txo.in), // Nonce
129
- ch: normalizeHex(txo.ch), // Content hash
130
- is: normalizeHex(txo.is), // Signature
131
- bs: normalizeHex(txo.bs), // External bootstrap
132
- mbs: normalizeHex(txo.mbs) // MSB bootstrap key
133
- };
134
-
135
- return {
136
- type,
137
- address: addressToBuffer(address),
138
- txo: normalizedTxo
139
- };
140
- }
141
- }
142
-
143
- export default SubnetworkOperationHandler;
@@ -1,52 +0,0 @@
1
- import BaseOperationHandler from './base/BaseOperationHandler.js';
2
- import CompleteStateMessageOperations from "../../../../messages/completeStateMessages/CompleteStateMessageOperations.js";
3
- import { OperationType } from '../../../../utils/constants.js';
4
- import PartialTransfer from "../validators/PartialTransfer.js";
5
- import {normalizeTransferOperation} from "../../../../utils/normalizers.js"
6
-
7
- /**
8
- * THIS CLASS IS ULTRA IMPORTANT BECAUSE IF SOMEONE WILL SEND A TRASH TO VALIDATOR AND IT WON'T BE HANDLED PROPERTLY -
9
- * FOR EXAMPLE VALIDATOR WILL BROADCAST IT TO THE INDEXER LAYER THEN IT WILL BE BANNED. SO EVERYTHING WHAT IS TRASH
10
- * MUST BE REFUSED.
11
- * TODO: WE SHOULD AUDIT VALIDATORS AND MAKE SURE THEY ARE NOT BROADCASTING TRASH TO THE INDEXER LAYER.
12
- */
13
-
14
-
15
- class TransferOperationHandler extends BaseOperationHandler {
16
- #partialTransferValidator;
17
-
18
- constructor(network, state, wallet, rateLimiter, options = {}) {
19
- super(network, state, wallet, rateLimiter, options);
20
- this.#partialTransferValidator = new PartialTransfer(this.state);
21
- }
22
-
23
- async handleOperation(payload) {
24
- if (payload.type !== OperationType.TRANSFER) {
25
- throw new Error('Unsupported operation type for TransferOperationHandler');
26
- }
27
- await this.#handleTransfer(payload);
28
- }
29
-
30
- async #handleTransfer(payload) {
31
- const normalizedPayload = normalizeTransferOperation(payload);
32
- const isValid = await this.#partialTransferValidator.validate(normalizedPayload);
33
- if (!isValid) {
34
- throw new Error("TransferHandler: Transfer validation failed.");
35
- }
36
-
37
- const completeTransferOperation = await CompleteStateMessageOperations.assembleCompleteTransferOperationMessage(
38
- this.wallet,
39
- normalizedPayload.address,
40
- normalizedPayload.tro.tx,
41
- normalizedPayload.tro.txv,
42
- normalizedPayload.tro.in,
43
- normalizedPayload.tro.to,
44
- normalizedPayload.tro.am,
45
- normalizedPayload.tro.is
46
- );
47
-
48
- this.network.transactionPoolService.addTransaction(completeTransferOperation);
49
- }
50
- }
51
-
52
- export default TransferOperationHandler;
@@ -1,94 +0,0 @@
1
- import b4a from "b4a";
2
-
3
- import GetRequestHandler from "../handlers/GetRequestHandler.js";
4
- import ResponseHandler from "../handlers/ResponseHandler.js";
5
- import RoleOperationHandler from "../handlers/RoleOperationHandler.js";
6
- import SubnetworkOperationHandler from "../handlers/SubnetworkOperationHandler.js";
7
- import TransferOperationHandler from "../handlers/TransferOperationHandler.js";
8
- import {NETWORK_MESSAGE_TYPES} from '../../../../utils/constants.js';
9
- import * as operation from '../../../../utils/operations.js';
10
- import TransactionRateLimiterService from "../../services/TransactionRateLimiterService.js";
11
-
12
- class NetworkMessageRouter {
13
- #network;
14
- #handlers;
15
- #options;
16
- #rateLimiter;
17
- constructor(network, state, wallet, options = {}) {
18
- this.#network = network;
19
- this.#rateLimiter = new TransactionRateLimiterService();
20
- this.#handlers = {
21
- get: new GetRequestHandler(wallet, state),
22
- response: new ResponseHandler(network, state, wallet),
23
- RoleTransaction: new RoleOperationHandler(network, state, wallet, this.#rateLimiter, options),
24
- subNetworkTransaction: new SubnetworkOperationHandler(network, state, wallet, this.#rateLimiter, options),
25
- tracNetworkTransaction: new TransferOperationHandler(network, state, wallet, this.#rateLimiter, options),
26
- }
27
- this.#options = options;
28
- }
29
-
30
- get network() {
31
- return this.#network;
32
- }
33
-
34
- async route(incomingMessage, connection, messageProtomux) {
35
- try {
36
- // TODO: Add a check here — only a writer should be able to process the handlers isRoleAccessOperation,isSubnetworkOperation
37
- // and admin nodes until the writers' index is less than 25. OperationType.APPEND_WHITELIST can be processed by only READERS
38
-
39
- const channelString = b4a.toString(this.network.channel, 'utf8');
40
- if (this.#isGetRequest(incomingMessage)) {
41
- await this.#handlers.get.handle(incomingMessage, messageProtomux, connection, channelString);
42
- this.network.swarm.leavePeer(connection.remotePublicKey);
43
- }
44
- else if (this.#isResponse(incomingMessage)) {
45
- await this.#handlers.response.handle(incomingMessage, connection, channelString);
46
- this.network.swarm.leavePeer(connection.remotePublicKey);
47
- }
48
- else if (this.#isRoleAccessOperation(incomingMessage)) {
49
- await this.#handlers.RoleTransaction.handle(incomingMessage, connection);
50
- this.network.swarm.leavePeer(connection.remotePublicKey);
51
-
52
- }
53
- else if (this.#isSubnetworkOperation(incomingMessage)) {
54
- await this.#handlers.subNetworkTransaction.handle(incomingMessage, connection);
55
- this.network.swarm.leavePeer(connection.remotePublicKey);
56
- }
57
- else if(this.#isTransferOperation(incomingMessage)) {
58
- await this.#handlers.tracNetworkTransaction.handle(incomingMessage, connection);
59
- this.network.swarm.leavePeer(connection.remotePublicKey);
60
- }
61
- else {
62
- this.network.swarm.leavePeer(connection.remotePublicKey);
63
- }
64
-
65
- } catch (error) {
66
- throw new Error(`Failed to route message: ${error.message}. Pubkey of requester is ${connection.remotePublicKey ? b4a.toString(connection.remotePublicKey, 'hex') : 'unknown'}`);
67
- }
68
- }
69
-
70
- #isGetRequest(message) {
71
- return Object.values(NETWORK_MESSAGE_TYPES.GET).includes(message);
72
- }
73
-
74
-
75
- #isResponse(message) {
76
- return Object.values(NETWORK_MESSAGE_TYPES.RESPONSE).includes(message.op);
77
- }
78
-
79
- #isRoleAccessOperation(message) {
80
- return operation.isRoleAccess(message.type)
81
- }
82
-
83
- #isSubnetworkOperation(message) {
84
- return operation.isTransaction(message.type) ||
85
- operation.isBootstrapDeployment(message.type)
86
- }
87
-
88
- #isTransferOperation(message) {
89
- return operation.isTransfer(message.type)
90
- }
91
- }
92
-
93
-
94
- export default NetworkMessageRouter;