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 454
/
app_env.ts
179 lines (157 loc) · 5.61 KB
/
app_env.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
/*
* 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 { APIClient, createIPCClient } from '@liskhq/lisk-api-client';
import { codec } from '@liskhq/lisk-codec';
import { join } from 'path';
import { Block } from '@liskhq/lisk-chain';
import { objects } from '@liskhq/lisk-utils';
import { homedir } from 'os';
import { existsSync, rmdirSync } from 'fs-extra';
import { ModuleClass } from './types';
import {
defaultConfig,
defaultAccounts,
defaultFaucetAccount,
createDefaultAccount,
} from './fixtures';
import { createGenesisBlock } from './create_genesis_block';
import { PartialApplicationConfig } from '../types';
import { Application } from '../application';
import { InstantiablePlugin } from '../plugins/base_plugin';
import { TokenModule, SequenceModule, KeysModule, DPoSModule } from '../modules';
interface ApplicationEnvConfig {
modules: ModuleClass[];
plugins?: InstantiablePlugin[];
config?: PartialApplicationConfig;
genesisBlockJSON?: Record<string, unknown>;
}
export class ApplicationEnv {
private _application!: Application;
private _dataPath!: string;
private _ipcClient!: APIClient;
private _genesisBlock!: Record<string, unknown>;
public constructor(appConfig: ApplicationEnvConfig) {
this._initApplication(appConfig);
}
public get application(): Application {
return this._application;
}
public get ipcClient(): APIClient {
return this._ipcClient;
}
public get dataPath(): string {
return this._dataPath;
}
public get networkIdentifier(): Buffer {
return this._application.networkIdentifier;
}
public get lastBlock(): Block {
// eslint-disable-next-line dot-notation
return this._application['_node']['_chain'].lastBlock;
}
public async startApplication(): Promise<void> {
// eslint-disable-next-line dot-notation
this._application['_genesisBlock'] = this._genesisBlock;
await Promise.race([
this._application.run(),
new Promise(resolve => setTimeout(resolve, 3000)),
]);
// Only start client when ipc is enabled
if (this._application.config.rpc.enable && this._application.config.rpc.mode === 'ipc') {
this._ipcClient = await createIPCClient(this._dataPath);
}
}
public async stopApplication(options: { clearDB: boolean } = { clearDB: true }): Promise<void> {
if (options.clearDB) {
// eslint-disable-next-line dot-notation
await this._application['_forgerDB'].clear();
// eslint-disable-next-line dot-notation
await this._application['_blockchainDB'].clear();
// eslint-disable-next-line dot-notation
await this._application['_nodeDB'].clear();
}
if (this._application.config.rpc.enable && this._application.config.rpc.mode === 'ipc') {
await this._ipcClient.disconnect();
}
await this._application.shutdown();
}
public async waitNBlocks(n = 1): Promise<void> {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const height = this.lastBlock.header.height + n;
return new Promise(resolve => {
// eslint-disable-next-line dot-notation
this._application['_channel'].subscribe('app:block:new', () => {
if (this.lastBlock.header.height >= height) {
resolve();
}
});
});
}
private _initApplication(appConfig: ApplicationEnvConfig): Application {
// As we can call this function with different configuration
// so we need to make sure existing schemas are already clear
codec.clearCache();
const { genesisBlockJSON } = createGenesisBlock({ modules: appConfig.modules });
this._genesisBlock = appConfig.genesisBlockJSON ?? genesisBlockJSON;
// In order for application to start forging, update force to true
const config = objects.mergeDeep({}, defaultConfig, appConfig.config ?? {});
const { label } = config;
const application = new Application(this._genesisBlock, config as PartialApplicationConfig);
appConfig.modules.map(module => application.registerModule(module));
appConfig.plugins?.map(plugin => application.registerPlugin(plugin));
this._dataPath = join(application.config.rootPath, label);
this._application = application;
return application;
}
}
export const createDefaultApplicationEnv = (
appEnvConfig: Partial<ApplicationEnvConfig>,
): ApplicationEnv => {
const rootPath = appEnvConfig.config?.rootPath ?? defaultConfig.rootPath;
const label = appEnvConfig.config?.label ?? defaultConfig.label;
// Ensure directory is cleaned for each application env
const dataPath = join(rootPath.replace('~', homedir()), label);
if (existsSync(dataPath)) {
rmdirSync(dataPath, { recursive: true });
}
const defaultModules = [TokenModule, SequenceModule, KeysModule, DPoSModule];
const modules = [...new Set([...(appEnvConfig.modules ?? []), ...defaultModules])];
const faucetAccount = {
address: defaultFaucetAccount.address,
token: { balance: BigInt(defaultFaucetAccount.balance) },
sequence: { nonce: BigInt('0') },
};
const defaultDelegateAccounts = defaultAccounts().map((a, i) =>
createDefaultAccount(modules, {
address: a.address,
dpos: {
delegate: {
username: `delegate_${i}`,
},
},
}),
);
const accounts = [faucetAccount, ...defaultDelegateAccounts];
const { genesisBlockJSON } = createGenesisBlock({
modules,
accounts,
});
const appEnv = new ApplicationEnv({
...appEnvConfig,
modules,
genesisBlockJSON,
});
return appEnv;
};