This repository has been archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 456
/
state_machine.ts
322 lines (302 loc) · 11.2 KB
/
state_machine.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
* Copyright © 2021 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
import { validator } from '@liskhq/lisk-validator';
import { standardEventDataSchema } from '@liskhq/lisk-chain';
import { codec } from '@liskhq/lisk-codec';
import { TransactionExecutionResult } from '../abi';
import { Logger } from '../logger';
import { BaseCommand, BaseModule } from '../modules';
import { GenesisConfig } from '../types';
import { BlockContext } from './block_context';
import { GenerationContext } from './generator_context';
import { GenesisBlockContext } from './genesis_block_context';
import { TransactionContext } from './transaction_context';
import { VerifyStatus, VerificationResult } from './types';
import { EVENT_TRANSACTION_NAME } from './constants';
export class StateMachine {
private readonly _modules: BaseModule[] = [];
private _logger!: Logger;
private _initialized = false;
public registerModule(mod: BaseModule): void {
this._validateExisting(mod);
this._modules.push(mod);
}
public async init(
logger: Logger,
genesisConfig: GenesisConfig,
moduleConfig: Record<string, Record<string, unknown>> = {},
): Promise<void> {
this._logger = logger;
if (this._initialized) {
return;
}
for (const mod of this._modules) {
if (mod.init) {
await mod.init({
moduleConfig: moduleConfig[mod.name] ?? {},
genesisConfig,
});
}
this._logger.info(`Registered and initialized ${mod.name} module`);
for (const command of mod.commands) {
this._logger.info(`Registered ${mod.name} module has command ${command.name}`);
}
}
this._initialized = true;
}
public async executeGenesisBlock(ctx: GenesisBlockContext): Promise<void> {
const initContext = ctx.createInitGenesisStateContext();
for (const mod of this._modules) {
if (mod.initGenesisState) {
this._logger.debug({ moduleName: mod.name }, 'Executing initGenesisState');
await mod.initGenesisState(initContext);
this._logger.debug({ moduleName: mod.name }, 'Executed initGenesisState');
}
}
const finalizeContext = ctx.createFinalizeGenesisStateContext();
for (const mod of this._modules) {
if (mod.finalizeGenesisState) {
this._logger.debug({ moduleName: mod.name }, 'Executing finalizeGenesisState');
await mod.finalizeGenesisState(finalizeContext);
this._logger.debug({ moduleName: mod.name }, 'Executed finalizeGenesisState');
}
}
}
public async insertAssets(ctx: GenerationContext): Promise<void> {
const initContext = ctx.getInsertAssetContext();
for (const mod of this._modules) {
if (mod.insertAssets) {
this._logger.debug({ moduleName: mod.name }, 'Executing insertAssets');
await mod.insertAssets(initContext);
this._logger.debug({ moduleName: mod.name }, 'Executed insertAssets');
}
}
}
public async verifyTransaction(
ctx: TransactionContext,
onlyCommand = false,
): Promise<VerificationResult> {
const transactionContext = ctx.createTransactionVerifyContext();
try {
if (!onlyCommand) {
for (const mod of this._modules) {
if (mod.verifyTransaction) {
this._logger.debug({ moduleName: mod.name }, 'Executing verifyTransaction');
const result = await mod.verifyTransaction(transactionContext);
this._logger.debug({ moduleName: mod.name }, 'Executed verifyTransaction');
if (result.status !== VerifyStatus.OK) {
this._logger.debug(
{ err: result.error, moduleName: mod.name },
'Transaction verification failed',
);
return result;
}
}
}
}
const command = this._getCommand(ctx.transaction.module, ctx.transaction.command);
const commandContext = ctx.createCommandVerifyContext(command.schema);
validator.validate(command.schema, commandContext.params);
if (command.verify) {
this._logger.debug(
{ commandName: command.name, moduleName: ctx.transaction.module },
'Executing command.verify',
);
const result = await command.verify(commandContext);
this._logger.debug(
{ commandName: command.name, moduleName: ctx.transaction.module },
'Executed command.verify',
);
if (result.status !== VerifyStatus.OK) {
this._logger.debug(
{ err: result.error, moduleName: ctx.transaction.module, commandName: command.name },
'Command verification failed',
);
return result;
}
}
return { status: VerifyStatus.OK };
} catch (error) {
this._logger.debug(
{
err: error as Error,
commandName: ctx.transaction.command,
moduleName: ctx.transaction.module,
},
'Transaction verification failed',
);
return { status: VerifyStatus.FAIL, error: error as Error };
}
}
public async executeTransaction(ctx: TransactionContext): Promise<TransactionExecutionResult> {
let status = TransactionExecutionResult.OK;
const transactionContext = ctx.createTransactionExecuteContext();
const eventQueueSnapshotID = ctx.eventQueue.createSnapshot();
const stateStoreSnapshotID = ctx.stateStore.createSnapshot();
for (const mod of this._modules) {
if (mod.beforeCommandExecute) {
try {
this._logger.debug({ moduleName: mod.name }, 'Executing beforeCommandExecute');
await mod.beforeCommandExecute(transactionContext);
this._logger.debug({ moduleName: mod.name }, 'Executed beforeCommandExecute');
} catch (error) {
ctx.eventQueue.restoreSnapshot(eventQueueSnapshotID);
ctx.stateStore.restoreSnapshot(stateStoreSnapshotID);
this._logger.debug(
{ err: error as Error, moduleName: mod.name },
'Transaction beforeCommandExecution failed',
);
return TransactionExecutionResult.INVALID;
}
}
}
const command = this._getCommand(ctx.transaction.module, ctx.transaction.command);
// Execute command
const commandEventQueueSnapshotID = ctx.eventQueue.createSnapshot();
const commandStateStoreSnapshotID = ctx.stateStore.createSnapshot();
const commandContext = ctx.createCommandExecuteContext(command.schema);
try {
this._logger.debug({ commandName: command.name }, 'Executing command.execute');
await command.execute(commandContext);
this._logger.debug({ commandName: command.name }, 'Executed command.execute');
} catch (error) {
ctx.eventQueue.restoreSnapshot(commandEventQueueSnapshotID);
ctx.stateStore.restoreSnapshot(commandStateStoreSnapshotID);
status = TransactionExecutionResult.FAIL;
this._logger.debug(
{
err: error as Error,
moduleName: ctx.transaction.module,
commandName: ctx.transaction.command,
},
'Command execution failed',
);
}
// Execute after transaction hooks
for (const mod of this._modules) {
if (mod.afterCommandExecute) {
try {
this._logger.debug({ moduleName: mod.name }, 'Executing afterCommandExecute');
await mod.afterCommandExecute(transactionContext);
this._logger.debug({ moduleName: mod.name }, 'Executed afterCommandExecute');
} catch (error) {
ctx.eventQueue.restoreSnapshot(eventQueueSnapshotID);
ctx.stateStore.restoreSnapshot(stateStoreSnapshotID);
this._logger.debug(
{ err: error as Error, moduleName: mod.name },
'Transaction afterCommandExecution failed',
);
return TransactionExecutionResult.INVALID;
}
}
}
ctx.eventQueue.unsafeAdd(
ctx.transaction.module,
EVENT_TRANSACTION_NAME,
codec.encode(standardEventDataSchema, { success: status === TransactionExecutionResult.OK }),
[ctx.transaction.id],
);
return status;
}
public async verifyAssets(ctx: BlockContext): Promise<void> {
for (const asset of ctx.assets.getAll()) {
if (this._findModule(asset.module) === undefined) {
throw new Error(`Module ${asset.module} is not registered.`);
}
}
const blockVerifyContext = ctx.getBlockVerifyExecuteContext();
for (const mod of this._modules) {
if (mod.verifyAssets) {
this._logger.debug({ moduleName: mod.name }, 'Executing verifyAssets');
await mod.verifyAssets(blockVerifyContext);
this._logger.debug({ moduleName: mod.name }, 'Executed verifyAssets');
}
}
}
public async beforeTransactionsExecute(ctx: BlockContext): Promise<void> {
const blockExecuteContext = ctx.getBlockExecuteContext();
for (const mod of this._modules) {
if (mod.beforeTransactionsExecute) {
this._logger.debug({ moduleName: mod.name }, 'Executing beforeTransactionsExecute');
await mod.beforeTransactionsExecute(blockExecuteContext);
this._logger.debug({ moduleName: mod.name }, 'Executed beforeTransactionsExecute');
}
}
}
public async afterExecuteBlock(ctx: BlockContext): Promise<void> {
const blockExecuteContext = ctx.getBlockAfterExecuteContext();
for (const mod of this._modules) {
if (mod.afterTransactionsExecute) {
this._logger.debug({ moduleName: mod.name }, 'Executing afterTransactionsExecute');
await mod.afterTransactionsExecute(blockExecuteContext);
this._logger.debug({ moduleName: mod.name }, 'Executed afterTransactionsExecute');
}
}
}
private _findModule(name: string): BaseModule | undefined {
const existingModule = this._modules.find(m => m.name === name);
if (existingModule) {
return existingModule;
}
return undefined;
}
private _getCommand(module: string, command: string): BaseCommand {
const targetModule = this._findModule(module);
if (!targetModule) {
this._logger.debug(`Module ${module} is not registered`);
throw new Error(`Module ${module} is not registered.`);
}
const targetCommand = targetModule.commands.find(c => c.name === command);
if (!targetCommand) {
this._logger.debug(`Module ${module} does not have command ${command} registered`);
throw new Error(`Module ${module} does not have command ${command} registered.`);
}
return targetCommand;
}
private _validateExisting(mod: BaseModule): void {
const existingModule = this._modules.find(m => m.name === mod.name);
if (existingModule) {
this._logger.debug(`Module ${mod.name} is registered`);
throw new Error(`Module ${mod.name} is registered.`);
}
const allExistingEvents = this._modules.reduce<Buffer[]>((prev, curr) => {
prev.push(...curr.events.keys());
return prev;
}, []);
for (const event of mod.events.values()) {
const duplicate = allExistingEvents.find(k => k.equals(event.key));
if (duplicate) {
this._logger.debug(`Module ${mod.name} has conflicting event ${event.name}`);
throw new Error(
`Module ${mod.name} has conflicting event ${event.name}. Please update the event name.`,
);
}
allExistingEvents.push(event.key);
}
const allExistingStores = this._modules.reduce<Buffer[]>((prev, curr) => {
prev.push(...curr.stores.keys());
return prev;
}, []);
for (const store of mod.stores.values()) {
const duplicate = allExistingStores.find(k => k.equals(store.key));
if (duplicate) {
this._logger.debug(`Module ${mod.name} has conflicting store ${store.name}`);
throw new Error(
`Module ${mod.name} has conflicting store ${store.name}. Please update the store name.`,
);
}
allExistingStores.push(store.key);
}
}
}