-
Notifications
You must be signed in to change notification settings - Fork 35
/
DeFiDContainer.ts
302 lines (267 loc) · 8.07 KB
/
DeFiDContainer.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
import Dockerode, { ContainerInfo, DockerOptions } from 'dockerode'
import fetch from 'cross-fetch'
import { DockerContainer } from './DockerContainer'
import { waitForCondition } from '../utils'
/**
* Types of network as per https://github.com/DeFiCh/ain/blob/bc231241/src/chainparams.cpp#L825-L836
*/
type Network = 'mainnet' | 'testnet' | 'devnet' | 'regtest'
/**
* Mandatory options to start defid with
*/
export interface StartOptions {
// TODO(fuxingloh): change to cookie based auth soon
user?: string
password?: string
timeout?: number
startFlags?: StartFlags[]
}
export interface StartFlags {
name: string
value: number
}
/**
* DeFiChain defid node managed in docker
*/
export abstract class DeFiDContainer extends DockerContainer {
/* eslint-disable @typescript-eslint/no-non-null-assertion, no-void */
public static readonly PREFIX = 'defichain-testcontainers-'
public static get image (): string {
if (process?.env?.DEFICHAIN_DOCKER_IMAGE !== undefined) {
return process.env.DEFICHAIN_DOCKER_IMAGE
}
return 'defi/defichain:HEAD-49fba65ce'
}
public static readonly DefaultStartOptions = {
user: 'testcontainers-user',
password: 'testcontainers-password'
}
protected startOptions?: StartOptions
protected cachedRpcUrl?: string
/**
* @param {Network} network of the container
* @param {string} image docker image name
* @param {DockerOptions} options
*/
protected constructor (
protected readonly network: Network,
protected readonly image: string = DeFiDContainer.image,
options?: DockerOptions
) {
super(image, options)
}
/**
* Convenience Cmd builder with StartOptions
*/
protected getCmd (opts: StartOptions): string[] {
return [
'defid',
'-printtoconsole',
'-rpcallowip=0.0.0.0/0',
'-rpcbind=0.0.0.0',
'-rpcworkqueue=512',
`-rpcuser=${opts.user!}`,
`-rpcpassword=${opts.password!}`
]
}
/**
* Create container and start it immediately waiting for defid to be ready
*/
async start (startOptions: StartOptions = {}): Promise<void> {
await this.tryPullImage()
this.startOptions = Object.assign(DeFiDContainer.DefaultStartOptions, startOptions)
this.container = await this.docker.createContainer({
name: this.generateName(),
Image: this.image,
Tty: true,
Cmd: this.getCmd(this.startOptions),
HostConfig: {
PublishAllPorts: true
}
})
await this.container.start()
await this.waitForRpc(startOptions.timeout)
}
/**
* Set contents of ~/.defi/defi.conf
* @param {string[]} options to set
*/
async setDeFiConf (options: string[]): Promise<void> {
if (options.length > 0) {
const fileContents = `${options.join('\n')}\n`
await this.exec({
Cmd: ['bash', '-c', `echo "${fileContents}" > ~/.defi/defi.conf`]
})
}
}
/**
* Generate a name for a new docker container with network type and random number
*/
generateName (): string {
const rand = Math.floor(Math.random() * 10000000)
return `${DeFiDContainer.PREFIX}-${this.network}-${rand}`
}
/**
* Get host machine port used for defid rpc
*/
public abstract getRpcPort (): Promise<string>
/**
* Get host machine url used for defid rpc calls with auth
* TODO(fuxingloh): not a great design when network config changed, the url and ports get refresh
*/
async getCachedRpcUrl (): Promise<string> {
if (this.cachedRpcUrl === undefined) {
const port = await this.getRpcPort()
const user = this.startOptions!.user!
const password = this.startOptions!.password!
this.cachedRpcUrl = `http://${user}:${password}@127.0.0.1:${port}/`
}
return this.cachedRpcUrl
}
/**
* For convenience sake, utility rpc for the current node.
* JSON 'result' is parsed and returned
* @throws DeFiDRpcError is raised for RPC errors
*/
async call (method: string, params: any = []): Promise<any> {
const body = JSON.stringify({
jsonrpc: '1.0',
id: Math.floor(Math.random() * 100000000000000),
method: method,
params: params
})
const text = await this.post(body)
const {
result,
error
} = JSON.parse(text)
if (error !== undefined && error !== null) {
throw new DeFiDRpcError(error)
}
return result
}
/**
* For convenience’s sake, HTTP POST to the RPC URL for the current node.
* Not error checked, returns the raw JSON as string.
*/
async post (body: string): Promise<string> {
const url = await this.getCachedRpcUrl()
const response = await fetch(url, {
method: 'POST',
body: body
})
return await response.text()
}
/**
* Convenience method to getmininginfo, typing mapping is non-exhaustive
*/
async getMiningInfo (): Promise<{ blocks: number, chain: string }> {
return await this.call('getmininginfo', [])
}
/**
* Convenience method to getblockcount, typing mapping is non exhaustive
*/
async getBlockCount (): Promise<number> {
return await this.call('getblockcount', [])
}
/**
* Convenience method to getbestblockhash, typing mapping is non-exhaustive
*/
async getBestBlockHash (): Promise<string> {
return await this.call('getbestblockhash', [])
}
/**
* Connect another node
* @param {string} ip
* @return {Promise<void>}
*/
async addNode (ip: string): Promise<void> {
return await this.call('addnode', [ip, 'onetry'])
}
/**
* Wait for rpc to be ready
* @param {number} [timeout=20000] in millis
*/
private async waitForRpc (timeout = 40000): Promise<void> {
await waitForCondition(async () => {
this.cachedRpcUrl = undefined
await this.getMiningInfo()
return true
}, timeout, 500, 'waitForRpc')
}
/**
* @deprecated as container.start() will automatically wait for ready now, you don't need to call this anymore
*/
async waitForReady (timeout = 40000): Promise<void> {
return await this.waitForRpc(timeout)
}
/**
* Stop and remove the current node and their associated volumes.
*
* This method will also automatically stop and removes nodes that are stale.
* Stale nodes are nodes that are running for more than 1 hour
*/
async stop (): Promise<void> {
try {
await this.container?.stop()
} finally {
try {
await this.container?.remove({ v: true })
} finally {
await cleanUpStale(DeFiDContainer.PREFIX, this.docker)
}
}
}
/**
* Restart container and wait for defid to be ready.
* This will stop the container and start it again with old data intact.
* @param {number} [timeout=30000] in millis
*/
async restart (timeout: number = 30000): Promise<void> {
await this.container?.restart()
await this.waitForRpc(timeout)
}
}
/**
* RPC error from container
*/
export class DeFiDRpcError extends Error {
constructor (error: { code: number, message: string }) {
super(`DeFiDRpcError: '${error.message}', code: ${error.code}`)
}
}
/**
* Clean up stale nodes are nodes that are running for 1 hour
*/
async function cleanUpStale (prefix: string, docker: Dockerode): Promise<void> {
/**
* Same prefix and created more than 1 hour ago
*/
function isStale (containerInfo: ContainerInfo): boolean {
if (containerInfo.Names.filter((value) => value.startsWith(prefix)).length > 0) {
return containerInfo.Created + 60 * 60 < Date.now() / 1000
}
return false
}
/**
* Stop container that are running, remove them after and their associated volumes
*/
async function tryStopRemove (containerInfo: ContainerInfo): Promise<void> {
const container = docker.getContainer(containerInfo.Id)
if (containerInfo.State === 'running') {
await container.stop()
}
await container.remove({ v: true })
}
return await new Promise((resolve, reject) => {
docker.listContainers({ all: true }, (error, result) => {
if (error instanceof Error) {
return reject(error)
}
const promises = (result ?? [])
.filter(isStale)
.map(tryStopRemove)
Promise.all(promises).finally(resolve)
})
})
}