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,272 +0,0 @@
1
- import PeerWallet from "trac-wallet";
2
- import b4a from "b4a";
3
-
4
- import StateBuilder from '../base/StateBuilder.js'
5
- import { OperationType, TRAC_ADDRESS_SIZE, NETWORK_ID } from '../../utils/constants.js';
6
- import { addressToBuffer, bufferToAddress, isAddressValid } from '../../core/state/utils/address.js';
7
- import { isHexString } from "../../utils/helpers.js";
8
- import { blake3Hash } from "../../utils/crypto.js";
9
- import { createMessage } from "../../utils/buffer.js";
10
- import { isTransaction, isRoleAccess, isBootstrapDeployment, isTransfer } from "../../utils/operations.js";
11
-
12
- class PartialStateMessageBuilder extends StateBuilder {
13
- #wallet;
14
- #operationType;
15
- #address;
16
- #writingKey;
17
- #txValidity;
18
- #contentHash;
19
- #externalBootstrap;
20
- #withMsbBootstrap;
21
- #bootstrapNonce;
22
- #bootstrapSignature;
23
- #channel;
24
- #incomingAddress;
25
- #amount;
26
- #payload;
27
-
28
- constructor(wallet) {
29
- super();
30
- if (!wallet || typeof wallet !== 'object') {
31
- throw new Error('Wallet must be a valid wallet object');
32
- }
33
- if (!isAddressValid(wallet.address)) {
34
- throw new Error('Wallet should have a valid TRAC address.');
35
- }
36
-
37
-
38
- this.#wallet = wallet;
39
- this.reset();
40
- }
41
-
42
- reset() {
43
- this.#operationType = null;
44
- this.#address = null;
45
- this.#writingKey = null;
46
- this.#txValidity = null;
47
- this.#contentHash = null;
48
- this.#externalBootstrap = null;
49
- this.#withMsbBootstrap = false;
50
- this.#bootstrapNonce = null;
51
- this.#bootstrapSignature = null;
52
- this.#incomingAddress = null;
53
- this.#amount = null;
54
- this.#channel = null;
55
- this.#payload = {};
56
- }
57
-
58
- forOperationType(operationType) {
59
- if (!Object.values(OperationType).includes(operationType) || OperationType === OperationType.UNKNOWN) {
60
- throw new Error(`Invalid operation type: ${operationType}`);
61
- }
62
-
63
- this.#operationType = operationType;
64
- this.#payload.type = operationType;
65
- return this;
66
- }
67
-
68
- withAddress(address) {
69
- if (!isAddressValid(address)) {
70
- throw new Error(`Address field must be a valid TRAC bech32m address with length ${TRAC_ADDRESS_SIZE}.`);
71
- }
72
-
73
- this.#address = address;
74
- this.#payload.address = this.#address;
75
- return this;
76
- }
77
-
78
- withContentHash(contentHash) {
79
- if (!isHexString(contentHash) || contentHash.length !== 64) {
80
- throw new Error('Content hash must be a 64-length hexstring.');
81
- }
82
- this.#contentHash = contentHash;
83
- return this;
84
- }
85
-
86
- withExternalBootstrap(bootstrap) {
87
- if (!isHexString(bootstrap) || bootstrap.length !== 64) {
88
- throw new Error('Bootstrap key must be a 64-length hexstring.');
89
- }
90
- this.#externalBootstrap = bootstrap;
91
- return this;
92
- }
93
-
94
- withMsbBootstrap(msbBootstrap) {
95
- if (!isHexString(msbBootstrap) || msbBootstrap.length !== 64) {
96
- throw new Error('MSB Bootstrap key must be a 64-length hexstring.');
97
- }
98
- this.#withMsbBootstrap = msbBootstrap;
99
- return this;
100
- }
101
-
102
- withWriterKey(writerKey) {
103
- if (!isHexString(writerKey) || writerKey.length !== 64) {
104
- throw new Error('Writer key must be a 64-length hexstring.');
105
- }
106
- this.#writingKey = writerKey;
107
- return this;
108
- }
109
-
110
- withTxValidity(txValidity) {
111
- if (!isHexString(txValidity) || txValidity.length !== 64) {
112
- throw new Error('txValidity must be a 64-length hexstring.');
113
- }
114
- this.#txValidity = txValidity;
115
- return this;
116
- }
117
-
118
- withIncomingAddress(address) {
119
- if (!isAddressValid(address)) {
120
- throw new Error(`Incoming address field must be a valid TRAC bech32m address with length ${TRAC_ADDRESS_SIZE}.`);
121
- }
122
-
123
- this.#incomingAddress = address;
124
- return this;
125
- }
126
-
127
- withAmount(amount) {
128
- if (!isHexString(amount) || amount.length !== 32) {
129
- throw new Error('Amount must be a 32-length hexstring.');
130
- }
131
-
132
- this.#amount = amount;
133
- return this;
134
- }
135
-
136
- withChannel(channel) {
137
- if (!isHexString(channel) || channel.length !== 64) {
138
- throw new Error('Channel must be a 64-length hexstring.');
139
- }
140
-
141
- this.#channel = channel;
142
- return this;
143
- }
144
-
145
- async buildValueAndSign() {
146
- const nonce = PeerWallet.generateNonce();
147
- let txMsg = null;
148
- let tx = null;
149
- let signature = null;
150
-
151
- // Creating a message for signing based on operation type
152
- // ATTENTION REMEMBER THAT createMessage accept only BUFFER arguments and uint32
153
- switch (this.#operationType) {
154
- case OperationType.ADD_WRITER:
155
- case OperationType.REMOVE_WRITER:
156
- case OperationType.ADMIN_RECOVERY:
157
- txMsg = createMessage(
158
- NETWORK_ID,
159
- b4a.from(this.#txValidity, 'hex'),
160
- b4a.from(this.#writingKey, 'hex'),
161
- nonce,
162
- this.#operationType
163
- );
164
- break;
165
-
166
- case OperationType.BOOTSTRAP_DEPLOYMENT:
167
- if (!this.#externalBootstrap) {
168
- throw new Error('External bootstrap key must be set for BOOTSTRAP DEPLOYMENT operation.');
169
- }
170
- txMsg = createMessage(
171
- NETWORK_ID,
172
- b4a.from(this.#txValidity, 'hex'),
173
- b4a.from(this.#externalBootstrap, 'hex'),
174
- b4a.from(this.#channel, 'hex'),
175
- nonce,
176
- OperationType.BOOTSTRAP_DEPLOYMENT
177
- );
178
- break;
179
-
180
- case OperationType.TX:
181
- txMsg = createMessage(
182
- NETWORK_ID,
183
- b4a.from(this.#txValidity, 'hex'),
184
- b4a.from(this.#writingKey, 'hex'),
185
- b4a.from(this.#contentHash, 'hex'),
186
- b4a.from(this.#externalBootstrap, 'hex'),
187
- b4a.from(this.#withMsbBootstrap, 'hex'),
188
- nonce,
189
- OperationType.TX
190
- );
191
- break;
192
- case OperationType.TRANSFER:
193
- txMsg = createMessage(
194
- NETWORK_ID,
195
- b4a.from(this.#txValidity, 'hex'),
196
- addressToBuffer(this.#incomingAddress), // we need to sign address of the recipient as well
197
- b4a.from(this.#amount, 'hex'),
198
- nonce,
199
- OperationType.TRANSFER
200
- );
201
- break;
202
- default:
203
- throw new Error(`Unsupported operation type: ${this.#operationType}`);
204
- }
205
-
206
- // tx and signature
207
- tx = await blake3Hash(txMsg);
208
- signature = this.#wallet.sign(tx);
209
-
210
- // Build the payload based on operation type
211
- if (isBootstrapDeployment(this.#operationType)) {
212
- this.#payload.bdo = {
213
- tx: tx.toString('hex'),
214
- txv: this.#txValidity,
215
- bs: this.#externalBootstrap,
216
- ic: this.#channel,
217
- in: nonce.toString('hex'),
218
- is: signature.toString('hex')
219
- };
220
- } else if (isRoleAccess(this.#operationType)) {
221
- this.#payload.rao = {
222
- tx: tx.toString('hex'),
223
- txv: this.#txValidity,
224
- iw: this.#writingKey,
225
- in: nonce.toString('hex'),
226
- is: signature.toString('hex')
227
- };
228
- } else if (isTransaction(this.#operationType)) {
229
- this.#payload.txo = {
230
- tx: tx.toString('hex'),
231
- txv: this.#txValidity,
232
- iw: this.#writingKey,
233
- ch: this.#contentHash,
234
- bs: this.#externalBootstrap,
235
- mbs: this.#withMsbBootstrap,
236
- in: nonce.toString('hex'),
237
- is: signature.toString('hex'),
238
- };
239
- } else if (isTransfer(this.#operationType)) {
240
- this.#payload.tro = {
241
- tx: tx.toString('hex'),
242
- txv: this.#txValidity,
243
- to: this.#incomingAddress,
244
- am: this.#amount,
245
- in: nonce.toString('hex'),
246
- is: signature.toString('hex')
247
- }
248
- }
249
-
250
- return this;
251
- }
252
-
253
- getPayload() {
254
- if (
255
- !this.#payload.type ||
256
- !this.#payload.address ||
257
- (
258
- !this.#payload.bdo &&
259
- !this.#payload.rao &&
260
- !this.#payload.txo &&
261
- !this.#payload.tro
262
- )
263
- ) {
264
- throw new Error('Product is not fully assembled. Missing type, address, or value bdo/rao/txo/tro.');
265
- }
266
- const res = this.#payload;
267
- this.reset();
268
- return res;
269
- }
270
- }
271
-
272
- export default PartialStateMessageBuilder;
@@ -1,137 +0,0 @@
1
- import StateBuilder from '../base/StateBuilder.js'
2
- import {OperationType} from '../../utils/constants.js'
3
- import address from "../../core/state/utils/address.js";
4
-
5
- class PartialStateMessageDirector {
6
- #builder;
7
-
8
- set builder(builderInstance) {
9
- if (!(builderInstance instanceof StateBuilder)) {
10
- throw new Error('Director requires a Builder instance.');
11
- }
12
- this.#builder = builderInstance;
13
- }
14
-
15
- /**
16
- * Builds a PARTIAL bootstrap deployment operation message, which can be sent to a validator.
17
- * The validator can sign this operation to make it COMPLETE and broadcast it to the network.
18
- * Bootstrap deployment is required to register a subnetwork. The network will reject
19
- * TransactionOperation messages for external bootstraps that are not registered.
20
- * Do NOT attempt to register the MSB bootstrap key.
21
- *
22
- * @param {String} address - Trac address of the requester/invoker node that broadcasts the operation.
23
- * @param {String} bootstrap - Bootstrap key from the subnetwork to be registered.
24
- * MUST be different from the MSB bootstrap key.
25
- * BEFORE deploying, ensure the subnetwork bootstrap is not already deployed.
26
- * @param {String} txValidity - Transaction validity hash representing the current indexer combination.
27
- * The operation remains valid as long as indexer keys maintain their order.
28
- * Acts as protection against deferred execution attacks.
29
- * @returns {Promise<Object>} The built bootstrap deployment operation message.
30
- * @throws {Error} If the builder has not been set or message building fails.
31
- */
32
- async buildPartialBootstrapDeploymentMessage(address, bootstrap, channel, txValidity) {
33
- if (!this.#builder) throw new Error('Builder has not been set.');
34
-
35
- await this.#builder
36
- .forOperationType(OperationType.BOOTSTRAP_DEPLOYMENT)
37
- .withAddress(address)
38
- .withTxValidity(txValidity)
39
- .withExternalBootstrap(bootstrap)
40
- .withChannel(channel)
41
- .buildValueAndSign();
42
-
43
- return this.#builder.getPayload();
44
- }
45
-
46
- async buildAddWriterMessage(address, writingKey, txValidity) {
47
- if (!this.#builder) throw new Error('Builder has not been set.');
48
-
49
- await this.#builder
50
- .forOperationType(OperationType.ADD_WRITER)
51
- .withAddress(address)
52
- .withTxValidity(txValidity)
53
- .withWriterKey(writingKey)
54
- .buildValueAndSign();
55
-
56
- return this.#builder.getPayload();
57
- }
58
-
59
- async buildRemoveWriterMessage(address, writerKey, txValidity) {
60
- if (!this.#builder) throw new Error('Builder has not been set.');
61
-
62
- await this.#builder
63
- .forOperationType(OperationType.REMOVE_WRITER)
64
- .withAddress(address)
65
- .withTxValidity(txValidity)
66
- .withWriterKey(writerKey)
67
- .buildValueAndSign();
68
-
69
- return this.#builder.getPayload();
70
- }
71
-
72
- async buildAdminRecoveryMessage(address, writingKey, txValidity) {
73
- if (!this.#builder) throw new Error('Builder has not been set.');
74
-
75
- await this.#builder
76
- .forOperationType(OperationType.ADMIN_RECOVERY)
77
- .withAddress(address)
78
- .withTxValidity(txValidity)
79
- .withWriterKey(writingKey)
80
- .buildValueAndSign();
81
-
82
- return this.#builder.getPayload();
83
- }
84
-
85
- /**
86
- * Builds a transaction operation message for cross-network communication
87
- * @param {String} address - Trac address of the requester/invoker node that broadcasts the transaction
88
- * @param {String} incomingWritingKey - Writing key from the subnetwork, used for authentication of the requesting node
89
- * @param {String} txValidity - Transaction validity hash representing current indexer combination.
90
- * Transaction remains valid as long as indexer keys maintain their order.
91
- * Acts as protection against deferred execution attacks.
92
- * @param {String} contentHash - Hash of the contract content from the subnetwork,
93
- * ensures data integrity between networks
94
- * @param {String} externalBootstrap - Bootstrap key from the subnetwork,
95
- * used for cross-network communication verification.
96
- * MUST BE DIFFERENT from the MSB bootstrap key.
97
- * transaction will be rejected if external bootstrap won't be
98
- * deployed in the MSB (bootstrapDeploymentOperation).
99
- * @param {String} msbBootstrap - Main Settlement Bus bootstrap key,
100
- * used for internal network verification
101
- * @returns {Promise<Object>} The built transaction operation message
102
- * @throws {Error} If builder hasn't been set or if message building fails
103
- */
104
- async buildTransactionOperationMessage(
105
- address,
106
- incomingWritingKey,
107
- txValidity,
108
- contentHash,
109
- externalBootstrap,
110
- msbBootstrap,
111
- ) {
112
- if (!this.#builder) throw new Error('Builder has not been set.');
113
- await this.#builder
114
- .forOperationType(OperationType.TX)
115
- .withAddress(address)
116
- .withTxValidity(txValidity)
117
- .withWriterKey(incomingWritingKey)
118
- .withContentHash(contentHash)
119
- .withExternalBootstrap(externalBootstrap)
120
- .withMsbBootstrap(msbBootstrap)
121
- .buildValueAndSign();
122
- return this.#builder.getPayload();
123
- }
124
- async buildTransferOperationMessage(address, recipientAddress, amount, txValidity){
125
- if (!this.#builder) throw new Error('Builder has not been set.');
126
- await this.#builder
127
- .forOperationType(OperationType.TRANSFER)
128
- .withAddress(address)
129
- .withTxValidity(txValidity)
130
- .withIncomingAddress(recipientAddress)
131
- .withAmount(amount)
132
- .buildValueAndSign();
133
- return this.#builder.getPayload();
134
- }
135
- }
136
-
137
- export default PartialStateMessageDirector;
@@ -1,131 +0,0 @@
1
- import PartialStateMessageBuilder from './PartialStateMessageBuilder.js';
2
- import PartialStateMessageDirector from './PartialStateMessageDirector.js';
3
-
4
- class PartialStateMessageOperations {
5
-
6
- /**
7
- * Assembles a PARTIAL bootstrap deployment operation, which can be sent to a validator.
8
- * The validator can sign this operation to make it COMPLETE and broadcast it to the network.
9
- * Bootstrap deployment is required to register a subnetwork. The network will reject
10
- * TransactionOperation messages for external bootstraps that are not registered.
11
- * Do NOT attempt to register the MSB bootstrap key.
12
- *
13
- * @param {Object} wallet - Wallet of the requester/invoker node that broadcasts the operation
14
- * @param {String} externalBootstrap - Bootstrap key from the subnetwork to be registered.
15
- * MUST be different from the MSB bootstrap key.
16
- * BEFORE deploying ensure if the subnetwork bootstrap is not already deployed.
17
- * @param {String} txValidity - Transaction validity hash representing the current indexer combination.
18
- * The operation remains valid as long as indexer keys maintain their order.
19
- * Acts as protection against deferred execution attacks.
20
- * @returns {Promise<Object>} The assembled bootstrap deployment operation message
21
- * @throws {Error} If assembly of the bootstrap deployment operation message fails
22
- */
23
- static async assembleBootstrapDeploymentMessage(wallet, externalBootstrap, channel, txValidity) {
24
- try {
25
- const builder = new PartialStateMessageBuilder(wallet);
26
- const director = new PartialStateMessageDirector();
27
- director.builder = builder;
28
- return await director.buildPartialBootstrapDeploymentMessage(
29
- wallet.address,
30
- externalBootstrap,
31
- channel,
32
- txValidity
33
- );
34
- } catch (error) {
35
- throw new Error(`Failed to assemble partial bootstrap deployment message: ${error.message}`);
36
- }
37
- }
38
-
39
- static async assembleAddWriterMessage(wallet, writingKey, txValidity) {
40
- try {
41
- const builder = new PartialStateMessageBuilder(wallet);
42
- const director = new PartialStateMessageDirector();
43
- director.builder = builder;
44
- return await director.buildAddWriterMessage(wallet.address, writingKey, txValidity);
45
- } catch (error) {
46
- throw new Error(`Failed to assemble add writer message: ${error.message}`);
47
- }
48
- }
49
-
50
- static async assembleRemoveWriterMessage(wallet, writerKey, txValidity) {
51
- try {
52
- const builder = new PartialStateMessageBuilder(wallet);
53
- const director = new PartialStateMessageDirector();
54
- director.builder = builder;
55
- return await director.buildRemoveWriterMessage(wallet.address, writerKey, txValidity);
56
- } catch (error) {
57
- throw new Error(`Failed to assemble remove writer message: ${error.message}`);
58
- }
59
- }
60
-
61
- static async assembleAdminRecoveryMessage(wallet, writingKey, txValidity) {
62
- try {
63
- const builder = new PartialStateMessageBuilder(wallet);
64
- const director = new PartialStateMessageDirector();
65
- director.builder = builder;
66
- return await director.buildAdminRecoveryMessage(wallet.address, writingKey, txValidity);
67
- } catch (error) {
68
- throw new Error(`Failed to assemble admin recovery message: ${error.message}`);
69
- }
70
- }
71
-
72
-
73
- /**
74
- * Assembles a PARTIAL transaction operation, which can be sent to a validator, who can then
75
- * sign the transaction to make it COMPLETE.
76
- *
77
- * @param {Object} wallet - Wallet of the requester/invoker node that broadcasts the transaction
78
- * @param {String} incomingWritingKey - Writing key from the subnetwork, used for authentication of the requesting node
79
- * @param {String} txValidity - Transaction validity hash representing current indexer combination.
80
- * Transaction remains valid as long as indexer keys maintain their order.
81
- * Acts as protection against deferred execution attacks.
82
- * @param {String} contentHash - Hash of the contract content from the subnetwork,
83
- * ensures data integrity between networks
84
- * @param {String} externalBootstrap - Bootstrap key from the subnetwork,
85
- * used for cross-network communication verification.
86
- * MUST BE DIFFERENT from the MSB bootstrap key.
87
- * transaction will be rejected if external bootstrap won't be
88
- * deployed in the MSB (bootstrapDeploymentOperation).
89
- * @param {String} msbBootstrap - Main Settlement Bus bootstrap key,
90
- * used for internal network verification
91
- * @returns {Promise<Object>} The assembled transaction operation message
92
- * @throws {Error} If assembly of the transaction operation message fails
93
- */
94
- static async assembleTransactionOperationMessage(wallet, incomingWritingKey, txValidity, contentHash, externalBootstrap, msbBootstrap) {
95
- try {
96
- const builder = new PartialStateMessageBuilder(wallet);
97
- const director = new PartialStateMessageDirector();
98
- director.builder = builder;
99
- return await director.buildTransactionOperationMessage(
100
- wallet.address,
101
- incomingWritingKey,
102
- txValidity,
103
- contentHash,
104
- externalBootstrap,
105
- msbBootstrap
106
- );
107
- } catch (error) {
108
- throw new Error(`Failed to assemble transaction operation message: ${error.message}`);
109
- }
110
- }
111
-
112
- static async assembleTransferOperationMessage(wallet, recipientAddress, amount, txValidity) {
113
- try {
114
- const builder = new PartialStateMessageBuilder(wallet);
115
- const director = new PartialStateMessageDirector();
116
- director.builder = builder;
117
- return await director.buildTransferOperationMessage(
118
- wallet.address,
119
- recipientAddress,
120
- amount,
121
- txValidity
122
- );
123
- } catch (error) {
124
- throw new Error(`Failed to assemble transfer operation message: ${error.message}`);
125
- }
126
-
127
- }
128
-
129
- }
130
-
131
- export default PartialStateMessageOperations;
@@ -1,11 +0,0 @@
1
- import b4a from "b4a";
2
- import { blake3 } from "@tracsystems/blake3";
3
-
4
- export async function blake3Hash(input, hashLength = 32) {
5
- if (typeof input === "string") {
6
- input = b4a.from(input, "utf8");
7
- }
8
-
9
- const hashBytes = await blake3(input, hashLength);
10
- return b4a.from(hashBytes);
11
- }
@@ -1,68 +0,0 @@
1
- import {test, hook} from '../../../helpers/wrapper.js';
2
- import {
3
- initMsbAdmin, initTemporaryDirectory, removeTemporaryDirectory, setupMsbPeer, setupMsbWriter, setupMsbIndexer,
4
- tryToSyncWriters
5
- } from '../../../helpers/setupApplyTests.js';
6
- import {randomBytes} from '../../../helpers/setupApplyTests.js';
7
- import CompleteStateMessageOperations from '../../../../src/messages/completeStateMessages/CompleteStateMessageOperations.js';
8
- import {testKeyPair1} from '../../../fixtures/apply.fixtures.js';
9
- import b4a from 'b4a';
10
- import { ADMIN_INITIAL_BALANCE } from '../../../../src/utils/constants.js';
11
-
12
- //TODO: ADD TEST WHEN NON-ADMIN NODE FORGES ADD ADMIN OPERATION AND BROADCASTS IT TO THE STATE - SHOULD BE REJECTED
13
-
14
- let admin;
15
- let tmpDirectory;
16
- let randomChannel;
17
-
18
- const sendAddAdmin = async (invoker) => {
19
- const validity = b4a.from(await admin.msb.state.getIndexerSequenceState(), 'hex')
20
- const addAdminMessage = await CompleteStateMessageOperations.assembleAddAdminMessage(
21
- admin.wallet,
22
- admin.msb.state.writingKey,
23
- validity
24
- );
25
-
26
- // add admin to base
27
- await invoker.msb.state.append(addAdminMessage); // Send `add admin` request to apply function
28
- }
29
-
30
- hook('Initialize admin for addAdmin tests', async () => {
31
- randomChannel = randomBytes(32).toString('hex');
32
- const baseOptions = {
33
- enable_tx_apply_logs: false,
34
- enable_interactive_mode: false,
35
- enable_role_requester: false,
36
- channel: randomChannel,
37
- enable_validator_observer: false,
38
- }
39
- tmpDirectory = await initTemporaryDirectory();
40
- admin = await initMsbAdmin(testKeyPair1, tmpDirectory, baseOptions);
41
- await admin.msb.ready();
42
- });
43
-
44
- test('Apply function addAdmin for the first time - happy path', async (k) => {
45
- const writersLength = await admin.msb.state.getWriterLength();
46
- const adminEntryBefore = await admin.msb.state.getAdminEntry();
47
- k.is(adminEntryBefore, null, 'Admin entry should be null before adding a new admin');
48
-
49
- await sendAddAdmin(admin)
50
- await tryToSyncWriters(admin);
51
- const adminEntryAfter = await admin.msb.state.getAdminEntry(); // check if the admin entry was added successfully in the base
52
- const nodeAdminEntry = await admin.msb.state.getNodeEntry(adminEntryAfter.address)
53
- const newWritersLength = await admin.msb.state.getWriterLength();
54
- // check the result
55
- k.ok(adminEntryAfter, 'Result should not be null');
56
- k.ok(adminEntryAfter.address === admin.wallet.address, 'Admin address in base should match admin wallet address');
57
- k.ok(b4a.equals(adminEntryAfter.wk, admin.msb.state.writingKey), 'Admin writing key in base should match admin MSB writing key');
58
- k.ok(b4a.equals(adminEntryAfter.wk, admin.options.bootstrap), 'Admin writing key in base should match bootstrap key');
59
- k.is(nodeAdminEntry.isWriter, true, 'Admin should be writer');
60
- k.is(nodeAdminEntry.isIndexer, true, 'Admin should be indexer');
61
- k.ok(b4a.equals(nodeAdminEntry.balance, ADMIN_INITIAL_BALANCE), 'Admin should have an initial balance');
62
- k.is(newWritersLength, writersLength + 1, 'Admin should increase writers length');
63
- });
64
-
65
- hook('Clean up addAdmin recovery setup', async () => {
66
- if (admin && admin.msb) await admin.msb.close();
67
- if (tmpDirectory) await removeTemporaryDirectory(tmpDirectory);
68
- });