-
Notifications
You must be signed in to change notification settings - Fork 458
/
chain.ts
247 lines (221 loc) · 7.11 KB
/
chain.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
/*
* Copyright © 2019 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 { Database, NotFoundError } from '@liskhq/lisk-db';
import * as createDebug from 'debug';
import { regularMerkleTree } from '@liskhq/lisk-tree';
import {
DEFAULT_KEEP_EVENTS_FOR_HEIGHTS,
DEFAULT_MAX_BLOCK_HEADER_CACHE,
DEFAULT_MIN_BLOCK_HEADER_CACHE,
GENESIS_BLOCK_VERSION,
} from './constants';
import { DataAccess } from './data_access';
import {
blockSchema,
signingBlockHeaderSchema,
blockHeaderSchema,
stateDiffSchema,
} from './schema';
import { Block } from './block';
import { Event } from './event';
import { BlockHeader } from './block_header';
import { CurrentState } from './state_store/smt_store';
interface ChainConstructor {
// Constants
readonly keepEventsForHeights: number;
readonly maxTransactionsSize: number;
readonly minBlockHeaderCache?: number;
readonly maxBlockHeaderCache?: number;
}
interface ChainInitArgs {
readonly db: Database;
readonly chainID: Buffer;
readonly genesisBlock: Block;
}
interface BlockValidationInput {
readonly version: number;
}
const debug = createDebug('lisk:chain');
export class Chain {
public dataAccess!: DataAccess;
public readonly constants: {
readonly maxTransactionsSize: number;
readonly minBlockHeaderCache: number;
readonly maxBlockHeaderCache: number;
readonly keepEventsForHeights: number;
};
private _lastBlock?: Block;
private _finalizedHeight?: number;
private _chainID!: Buffer;
private _genesisHeight!: number;
public constructor({
// Constants
maxTransactionsSize,
keepEventsForHeights = DEFAULT_KEEP_EVENTS_FOR_HEIGHTS,
minBlockHeaderCache = DEFAULT_MIN_BLOCK_HEADER_CACHE,
maxBlockHeaderCache = DEFAULT_MAX_BLOCK_HEADER_CACHE,
}: ChainConstructor) {
// Register codec schema
codec.addSchema(blockSchema);
codec.addSchema(blockHeaderSchema);
codec.addSchema(signingBlockHeaderSchema);
codec.addSchema(stateDiffSchema);
this.constants = {
maxTransactionsSize,
maxBlockHeaderCache,
minBlockHeaderCache,
keepEventsForHeights,
};
}
public get genesisHeight(): number {
return this._genesisHeight;
}
public get lastBlock(): Block {
if (this._lastBlock === undefined) {
throw new Error('Chain has not been initialized.');
}
return this._lastBlock;
}
public get finalizedHeight(): number {
if (this._finalizedHeight === undefined) {
throw new Error('Chain has not been initialized.');
}
return this._finalizedHeight;
}
public get chainID(): Buffer {
return this._chainID;
}
public init(args: ChainInitArgs): void {
this._chainID = args.chainID;
this.dataAccess = new DataAccess({
db: args.db,
minBlockHeaderCache: this.constants.minBlockHeaderCache,
maxBlockHeaderCache: this.constants.maxBlockHeaderCache,
keepEventsForHeights: this.constants.keepEventsForHeights,
});
}
public async loadLastBlocks(genesisBlock: Block): Promise<void> {
let storageLastBlock: Block;
try {
storageLastBlock = await this.dataAccess.getLastBlock();
} catch (error) {
throw new Error('Failed to load last block.');
}
if (storageLastBlock.header.height !== genesisBlock.header.height) {
await this._cacheBlockHeaders(storageLastBlock);
}
this._lastBlock = storageLastBlock;
this._genesisHeight = genesisBlock.header.height;
this._finalizedHeight = await this.dataAccess.getFinalizedHeight();
}
public resetBlockHeaderCache(): void {
this.dataAccess.resetBlockHeaderCache();
}
public async genesisBlockExist(genesisBlock: Block): Promise<boolean> {
let matchingGenesisBlock: BlockHeader | undefined;
try {
matchingGenesisBlock = await this.dataAccess.getBlockHeaderByID(genesisBlock.header.id);
} catch (error) {
if (!(error instanceof NotFoundError)) {
throw error;
}
}
let lastBlockHeader: BlockHeader | undefined;
try {
lastBlockHeader = await this.dataAccess.getLastBlockHeader();
} catch (error) {
if (!(error instanceof NotFoundError)) {
throw error;
}
}
if (lastBlockHeader && !matchingGenesisBlock) {
throw new Error('Genesis block does not match.');
}
if (!lastBlockHeader && !matchingGenesisBlock) {
return false;
}
return true;
}
public validateBlock(block: Block, inputs: BlockValidationInput): void {
block.validate();
if (block.header.version !== inputs.version) {
throw new Error(`Block version must be ${inputs.version}.`);
}
const transactionIDs = [];
let transactionsSize = 0;
for (const tx of block.transactions) {
transactionIDs.push(tx.id);
transactionsSize += tx.getBytes().length;
}
if (transactionsSize > this.constants.maxTransactionsSize) {
throw new Error(
`Transactions length is longer than configured length: ${this.constants.maxTransactionsSize}.`,
);
}
const transactionRoot = regularMerkleTree.calculateMerkleRootWithLeaves(transactionIDs);
if (!transactionRoot.equals(block.header.transactionRoot as Buffer)) {
throw new Error('Invalid transaction root.');
}
}
public async saveBlock(
block: Block,
events: Event[],
state: CurrentState,
finalizedHeight: number,
{ removeFromTempTable } = {
removeFromTempTable: false,
},
): Promise<void> {
await this.dataAccess.saveBlock(block, events, state, finalizedHeight, removeFromTempTable);
this.dataAccess.addBlockHeader(block.header);
this._finalizedHeight = finalizedHeight;
this._lastBlock = block;
}
public async removeBlock(
block: Block,
state: CurrentState,
{ saveTempBlock } = { saveTempBlock: false },
): Promise<void> {
if (block.header.version === GENESIS_BLOCK_VERSION) {
throw new Error('Cannot delete genesis block.');
}
let secondLastBlock: Block;
try {
secondLastBlock = await this.dataAccess.getBlockByID(block.header.previousBlockID);
} catch (error) {
throw new Error('PreviousBlock is null.');
}
await this.dataAccess.deleteBlock(block, state, saveTempBlock);
await this.dataAccess.removeBlockHeader(block.header.id);
this._lastBlock = secondLastBlock;
}
private async _cacheBlockHeaders(storageLastBlock: Block): Promise<void> {
// Cache the block headers (size=DEFAULT_MAX_BLOCK_HEADER_CACHE)
const fromHeight = Math.max(storageLastBlock.header.height - DEFAULT_MAX_BLOCK_HEADER_CACHE, 0);
const toHeight = storageLastBlock.header.height;
debug(
{ h: storageLastBlock.header.height, fromHeight, toHeight },
'Cache block headers during chain init',
);
const blockHeaders = await this.dataAccess.getBlockHeadersByHeightBetween(fromHeight, toHeight);
const sortedBlockHeaders = [...blockHeaders].sort(
(a: BlockHeader, b: BlockHeader) => a.height - b.height,
);
for (const blockHeader of sortedBlockHeaders) {
debug({ height: blockHeader.height }, 'Add block header to cache');
this.dataAccess.addBlockHeader(blockHeader);
}
}
}