-
Notifications
You must be signed in to change notification settings - Fork 458
/
recover_message.ts
521 lines (485 loc) · 16.8 KB
/
recover_message.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*
* Copyright © 2022 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 { codec } from '@liskhq/lisk-codec';
import { regularMerkleTree } from '@liskhq/lisk-tree';
import { utils } from '@liskhq/lisk-cryptography';
import { NotFoundError } from '@liskhq/lisk-chain';
import {
CommandExecuteContext,
CommandVerifyContext,
VerificationResult,
VerifyStatus,
} from '../../../../state_machine/types';
import { CCMsg, CrossChainMessageContext, MessageRecoveryParams } from '../../types';
import { BaseInteroperabilityCommand } from '../../base_interoperability_command';
import { MainchainInteroperabilityInternalMethod } from '../internal_method';
import {
getMainchainID,
validateFormat,
getEncodedCCMAndID,
getDecodedCCMAndID,
} from '../../utils';
import {
CCMStatusCode,
CONTEXT_STORE_KEY_CCM_PROCESSING,
EVENT_TOPIC_CCM_EXECUTION,
} from '../../constants';
import { ccmSchema, messageRecoveryParamsSchema } from '../../schemas';
import { TerminatedOutboxAccount, TerminatedOutboxStore } from '../../stores/terminated_outbox';
import {
CCMProcessedCode,
CcmProcessedEvent,
CCMProcessedResult,
} from '../../events/ccm_processed';
import { InvalidRMTVerificationEvent } from '../../events/invalid_rmt_verification';
// https://github.com/LiskHQ/lips/blob/main/proposals/lip-0054.md#message-recovery-command
export class RecoverMessageCommand extends BaseInteroperabilityCommand<MainchainInteroperabilityInternalMethod> {
public schema = messageRecoveryParamsSchema;
// https://github.com/LiskHQ/lips/blob/main/proposals/lip-0054.md#verification-1
public async verify(
context: CommandVerifyContext<MessageRecoveryParams>,
): Promise<VerificationResult> {
const {
params: { chainID, crossChainMessages, idxs },
} = context;
let terminatedOutboxAccount: TerminatedOutboxAccount | undefined;
try {
terminatedOutboxAccount = await this.stores.get(TerminatedOutboxStore).get(context, chainID);
} catch (error) {
if (error instanceof NotFoundError) {
return {
status: VerifyStatus.FAIL,
error: new Error('Terminated outbox account does not exist.'),
};
}
throw error;
}
// Check that there is at least one cross-chain message to recover.
if (!crossChainMessages.length) {
return {
status: VerifyStatus.FAIL,
error: new Error('No cross-chain messages to recover.'),
};
}
if (idxs.length !== crossChainMessages.length) {
return {
status: VerifyStatus.FAIL,
error: new Error(
'Inclusion proof indices and cross-chain messages do not have the same length.',
),
};
}
for (let i = 0; i < idxs.length - 1; i += 1) {
if (idxs[i] > idxs[i + 1]) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message indexes are not strictly increasing.'),
};
}
}
// Ensure that there are at least two bits, i.e. the value must be larger than 1.
// It's sufficient to check only the first one due the ascending order.
// See https://github.com/LiskHQ/lips/blob/main/proposals/lip-0031.md#proof-serialization.
if (idxs[0] <= 1) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message does not have a valid index.'),
};
}
// Check that the CCMs are still pending. We can check only the first one,
// as the idxs are sorted in ascending order. Note that one must unset the most significant
// bit a of an encoded index in idxs in order to get the position in the tree.
// See https://github.com/LiskHQ/lips/blob/main/proposals/lip-0031.md#proof-serialization.
const firstPosition = parseInt(idxs[0].toString(2).slice(1), 2);
if (firstPosition < terminatedOutboxAccount.partnerChainInboxSize) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message is not pending.'),
};
}
// Check that the CCM indices do not exceed the outbox size. We check only the last one,
// as the idxs are sorted in ascending order. As above, the most significant bit of the encoded
// index in idxs must be unset to get the position in the tree.
const lastPosition = parseInt(idxs[idxs.length - 1].toString(2).slice(1), 2);
if (terminatedOutboxAccount.outboxSize <= lastPosition) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message was never in the outbox.'),
};
}
// Process basic checks for all CCMs.
// Verify general format. Past this point, we can access ccm root properties.
for (const crossChainMessage of crossChainMessages) {
const ccm = codec.decode<CCMsg>(ccmSchema, crossChainMessage);
validateFormat(ccm);
if (ccm.status !== CCMStatusCode.OK) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message status is not valid.'),
};
}
// The receiving chain must be the terminated chain.
if (!ccm.receivingChainID.equals(chainID)) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message receiving chain ID is not valid.'),
};
}
// The sending chain must be live.
const isLive = await this.internalMethod.isLive(
context,
ccm.sendingChainID,
context.header.timestamp,
);
if (!isLive) {
return {
status: VerifyStatus.FAIL,
error: new Error('Cross-chain message sending chain is not live.'),
};
}
}
return {
status: VerifyStatus.OK,
};
}
// https://github.com/LiskHQ/lips/blob/main/proposals/lip-0054.md#execution-1
public async execute(context: CommandExecuteContext<MessageRecoveryParams>): Promise<void> {
const { params } = context;
const terminatedOutboxSubstore = this.stores.get(TerminatedOutboxStore);
const terminatedOutboxAccount = await terminatedOutboxSubstore.get(
context,
context.params.chainID,
);
// Check the inclusion proof against the sidechain outbox root.
const proof = {
size: terminatedOutboxAccount.outboxSize,
idxs: params.idxs,
siblingHashes: params.siblingHashes,
};
const isVerified = regularMerkleTree.verifyDataBlock(
params.crossChainMessages,
proof,
terminatedOutboxAccount.outboxRoot,
);
if (!isVerified) {
this.events.get(InvalidRMTVerificationEvent).error(context);
throw new Error('Message recovery proof of inclusion is not valid.');
}
// Update the context to indicate that now we start the CCM processing.
context.contextStore.set(CONTEXT_STORE_KEY_CCM_PROCESSING, true);
// Set CCM status to recovered and assign fee to trs sender.
const recoveredCCMs: Buffer[] = [];
for (const crossChainMessage of params.crossChainMessages) {
const { decodedCCM: ccm, ccmID } = getDecodedCCMAndID(crossChainMessage);
const ctx: CrossChainMessageContext = {
...context,
ccm,
eventQueue: context.eventQueue.getChildQueue(
Buffer.concat([EVENT_TOPIC_CCM_EXECUTION, ccmID]),
),
};
let recoveredCCM: CCMsg;
// If the sending chain is the mainchain, recover the CCM.
// This function never raises an error.
if (ccm.sendingChainID.equals(getMainchainID(context.chainID))) {
recoveredCCM = await this._applyRecovery(ctx);
} else {
// If the sending chain is not the mainchain, forward the CCM.
// This function never raises an error.
recoveredCCM = await this._forwardRecovery(ctx);
}
// Append the recovered CCM to the list of recovered CCMs.
// Notice that the ccm has been updated in the applyRecovery and forwardRecovery functions
// as the status is set to CCM_STATUS_CODE_RECOVERED (so that it cannot be recovered again).
recoveredCCMs.push(codec.encode(ccmSchema, recoveredCCM));
}
// Update the context to indicate that now we stop the CCM processing.
context.contextStore.set(CONTEXT_STORE_KEY_CCM_PROCESSING, false);
terminatedOutboxAccount.outboxRoot = regularMerkleTree.calculateRootFromUpdateData(
recoveredCCMs.map(ccm => utils.hash(ccm)),
{ ...proof, indexes: proof.idxs },
);
await terminatedOutboxSubstore.set(context, context.params.chainID, terminatedOutboxAccount);
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
private async _applyRecovery(context: CrossChainMessageContext): Promise<CCMsg> {
const { logger } = context;
const { ccmID } = getEncodedCCMAndID(context.ccm);
const recoveredCCM: CCMsg = {
...context.ccm,
status: CCMStatusCode.RECOVERED,
sendingChainID: context.ccm.receivingChainID,
receivingChainID: context.ccm.sendingChainID,
};
let ccmFailed = false;
let ccmResult = CCMProcessedResult.APPLIED;
let ccmCode = CCMProcessedCode.SUCCESS;
try {
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.verifyCrossChainMessage) {
logger.debug(
{
moduleName: module,
commandName: recoveredCCM.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute verifyCrossChainMessage',
);
await method.verifyCrossChainMessage(context);
}
}
} catch (error) {
logger.debug(
{
err: error as Error,
moduleName: recoveredCCM.module,
commandName: recoveredCCM.crossChainCommand,
},
'Fail to verify cross chain message.',
);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_VERIFY_CCM_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
const commands = this.ccCommands.get(recoveredCCM.module);
if (!commands) {
ccmFailed = true;
ccmResult = CCMProcessedResult.DISCARDED;
ccmCode = CCMProcessedCode.MODULE_NOT_SUPPORTED;
}
const command = commands?.find(com => com.name === recoveredCCM.crossChainCommand);
if (!ccmFailed && !command) {
ccmFailed = true;
ccmResult = CCMProcessedResult.DISCARDED;
ccmCode = CCMProcessedCode.CROSS_CHAIN_COMMAND_NOT_SUPPORTED;
}
if (command?.verify) {
try {
await command.verify(context);
} catch (error) {
logger.debug(
{
err: error as Error,
moduleName: recoveredCCM.module,
commandName: recoveredCCM.crossChainCommand,
},
'Fail to verify cross chain command.',
);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_VERIFY_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
}
const baseEventSnapshotID = context.eventQueue.createSnapshot();
const baseStateSnapshotID = context.stateStore.createSnapshot();
try {
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.beforeCrossChainCommandExecute) {
logger.debug(
{
moduleName: module,
commandName: recoveredCCM.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute beforeCrossChainCommandExecute',
);
await method.beforeCrossChainCommandExecute(context);
}
}
} catch (error) {
context.eventQueue.restoreSnapshot(baseEventSnapshotID);
context.stateStore.restoreSnapshot(baseStateSnapshotID);
logger.debug(
{
err: error as Error,
moduleName: recoveredCCM.module,
commandName: recoveredCCM.crossChainCommand,
},
'Fail to execute beforeCrossChainCommandExecute.',
);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_BEFORE_CCC_EXECUTION_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
// We execute the cross-chain command logic only if there is no ccm failure.
if (!ccmFailed) {
const execEventSnapshotID = context.eventQueue.createSnapshot();
const execStateSnapshotID = context.stateStore.createSnapshot();
try {
const params = command?.schema ? codec.decode(command?.schema, recoveredCCM.params) : {};
await command?.execute({ ...context, params });
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.SUCCESS,
result: CCMProcessedResult.APPLIED,
ccm: recoveredCCM,
});
} catch (error) {
context.eventQueue.restoreSnapshot(execEventSnapshotID);
context.stateStore.restoreSnapshot(execStateSnapshotID);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.FAILED_CCM,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
}
}
try {
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.afterCrossChainCommandExecute) {
logger.debug(
{
moduleName: module,
commandName: recoveredCCM.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute afterCrossChainCommandExecute',
);
await method.afterCrossChainCommandExecute(context);
}
}
} catch (error) {
context.eventQueue.restoreSnapshot(baseEventSnapshotID);
context.stateStore.restoreSnapshot(baseStateSnapshotID);
logger.debug(
{ err: error as Error, moduleName: module, commandName: recoveredCCM.crossChainCommand },
'Fail to execute afterCrossChainCommandExecute',
);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_AFTER_CCC_EXECUTION_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
if (ccmFailed) {
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: ccmCode,
result: ccmResult,
ccm: recoveredCCM,
});
}
return recoveredCCM;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
private async _forwardRecovery(context: CrossChainMessageContext): Promise<CCMsg> {
const { logger } = context;
const { ccmID } = getEncodedCCMAndID(context.ccm);
const recoveredCCM: CCMsg = {
...context.ccm,
status: CCMStatusCode.RECOVERED,
sendingChainID: context.ccm.receivingChainID,
receivingChainID: context.ccm.sendingChainID,
};
try {
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.verifyCrossChainMessage) {
logger.debug(
{
moduleName: module,
commandName: recoveredCCM.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute verifyCrossChainMessage',
);
await method.verifyCrossChainMessage(context);
}
}
} catch (error) {
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_VERIFY_CCM_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
logger.debug(
{
err: error as Error,
moduleName: recoveredCCM.module,
commandName: recoveredCCM.crossChainCommand,
},
'Fail to execute verifyCrossChainMessage.',
);
return recoveredCCM;
}
const baseEventSnapshotID = context.eventQueue.createSnapshot();
const baseStateSnapshotID = context.stateStore.createSnapshot();
try {
for (const [module, method] of this.interoperableCCMethods.entries()) {
if (method.beforeCrossChainMessageForwarding) {
logger.debug(
{
moduleName: module,
commandName: recoveredCCM.crossChainCommand,
ccmID: ccmID.toString('hex'),
},
'Execute beforeCrossChainMessageForwarding',
);
await method.beforeCrossChainMessageForwarding({ ...context, ccmFailed: false });
}
}
} catch (error) {
context.eventQueue.restoreSnapshot(baseEventSnapshotID);
context.stateStore.restoreSnapshot(baseStateSnapshotID);
logger.debug(
{
err: error as Error,
moduleName: recoveredCCM.module,
commandName: recoveredCCM.crossChainCommand,
},
'Fail to execute beforeCrossChainMessageForwarding.',
);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.INVALID_CCM_BEFORE_CCC_FORWARDING_EXCEPTION,
result: CCMProcessedResult.DISCARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
await this.internalMethod.addToOutbox(context, recoveredCCM.receivingChainID, recoveredCCM);
this.events
.get(CcmProcessedEvent)
.log(context, recoveredCCM.sendingChainID, recoveredCCM.receivingChainID, {
code: CCMProcessedCode.SUCCESS,
result: CCMProcessedResult.FORWARDED,
ccm: recoveredCCM,
});
return recoveredCCM;
}
}