-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathturtlecoind-ha.js
262 lines (240 loc) · 8.96 KB
/
turtlecoind-ha.js
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
'use strict'
const pty = require('node-pty')
const util = require('util')
const inherits = require('util').inherits
const EventEmitter = require('events').EventEmitter
const request = require('request-promise')
const fs = require('fs')
const daemonResponses = {
synced: 'SUCCESSFULLY SYNCHRONIZED WITH THE TURTLECOIN NETWORK',
altsynced: 'SYNCHRONIZED OK',
started: 'Always exit TurtleCoind and Simplewallet with',
help: 'Show this help'
}
const blockTargetTime = 30
const TurtleCoind = function (opts) {
opts = opts || {}
if (!(this instanceof TurtleCoind)) return new TurtleCoind(opts)
this.path = opts.path
this.pollingInterval = opts.pollingInterval || 2000
this.timeout = opts.timeout || 2000
this.dataDir = opts.dataDir || false
this.testnet = opts.testnet || false
this.print = opts.print || false
this.enableCors = opts.enableCors || false
this.enableBlockExplorer = opts.enableBlockExplorer || false
this.rpcBindIp = opts.rpcBindIp || '127.0.0.1'
this.rpcBindPort = opts.rpcBindPort || 11898
this.p2pBindIp = opts.p2pBindIp || false
this.p2pBindPort = opts.p2pBindPort || false
this.p2pExternalPort = opts.p2pExternalPort || false
this.allowLocalIp = opts.allowLocalIp || false
this.peers = opts.peers || false
this.priorityNodes = opts.priorityNodes || false
this.exclusiveNodes = opts.exclusiveNodes || false
this.seedNode = opts.seedNode || false
this.hideMyPort = opts.hideMyPort || false
this.dbThreads = opts.dbThreads || false
this.dbMaxOpenFiles = opts.dbMaxOpenFiles || false
this.dbWriteBufferSize = opts.dbWriteBufferSize || false
this.dbReadCacheSize = opts.dbReadCacheSize || false
this._rpcQueryIp = (this.rpcBindIp === '0.0.0.0') ? '127.0.0.1' : this.rpcBindIp
}
inherits(TurtleCoind, EventEmitter)
TurtleCoind.prototype.start = function () {
if (!fs.existsSync(this.path)) {
this.emit('error', util.format('%s could not be found', this.path))
return false
}
this.sycned = false
var args = this._buildargs()
this.child = pty.spawn(this.path, args, {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
})
this.child.on('error', (error) => {
this.emit('error', util.format('Error in child process...: %s', error))
})
this.child.on('data', (data) => {
this.emit('data', data.trim())
})
this.child.on('close', (exitcode) => {
this.emit('stopped', exitcode)
})
// Attach to our own events so that we know when we can start our checking processes
this.on('data', this._checkChildStdio)
this.on('synced', this._checkServices)
this.emit('start', util.format('%s %s', this.path, args.join(' ')))
}
TurtleCoind.prototype.stop = function () {
// If we are currently running our checks, it's a good idea to stop them before we go kill the child process
if (this.checkDaemon) {
clearInterval(this.checkDaemon)
this.checkDaemon = null
}
this.synced = false
// We detach ourselves from our own event emitters here so that we don't accidentally stack on top of ourselves when we start back up
this.removeListener('synced', this._checkServices)
this.removeListener('data', this._checkChildStdio)
// Let's try to exit cleanly and if not, kill the process
if (this.child) this.write('exit')
setTimeout(() => {
if (this.child) this.child.kill()
}, (this.timeout * 2))
}
TurtleCoind.prototype.write = function (data) {
this._write(util.format('%s\r', data))
}
TurtleCoind.prototype._checkChildStdio = function (data) {
if (data.indexOf(daemonResponses.synced) !== -1) {
this.emit('synced')
} else if (data.indexOf(daemonResponses.altsynced) !== -1) {
this.emit('synced')
} else if (data.indexOf(daemonResponses.started) !== -1) {
this.emit('started')
} else if (data.indexOf(daemonResponses.help) !== -1) {
this.help = true
}
}
TurtleCoind.prototype._checkServices = function () {
if (!this.synced) {
this.synced = true
this.checkDaemon = setInterval(() => {
Promise.all([
this._checkRpc(),
this._checkDaemon()
]).then((results) => {
var info = results[0][0]
info.globalHashRate = Math.round(info.difficulty / blockTargetTime)
if (this.trigger) {
clearTimeout(this.trigger)
this.trigger = null
}
this.emit('ready', info)
}).catch((err) => {
this.emit('error', err)
if (!this.trigger) {
this.trigger = setTimeout(() => {
this.emit('down')
}, (this.pollingInterval * 2))
}
})
}, this.pollingInterval)
}
}
TurtleCoind.prototype._checkRpc = function () {
return new Promise((resolve, reject) => {
Promise.all([
this._getInfo(),
this._getHeight(),
this._getTransactions()
]).then((results) => {
if (results[0].height === results[1].height && results[0].status === results[1].status && results[1].status === results[2].status) {
return resolve(results)
} else {
return reject(new Error('Daemon is returning inconsistent results'))
}
}).catch((err) => {
return reject(util.format('Daemon is not passing checks...: %s', err))
})
})
}
TurtleCoind.prototype._checkDaemon = function () {
return new Promise((resolve, reject) => {
this.help = false
this.write('help')
setTimeout(() => {
if (this.help) return resolve(true)
return reject(new Error('Daemon is unresponsive'))
}, 1000)
})
}
TurtleCoind.prototype._write = function (data) {
this.child.write(data)
}
TurtleCoind.prototype._queryRpc = function (method) {
return new Promise((resolve, reject) => {
request({
method: 'GET',
uri: util.format('http://%s:%s/%s', this.rpcBindIp, this.rpcBindPort, method),
timeout: this.timeout
}).then((data) => {
return resolve(JSON.parse(data))
}).catch((err) => {
return reject(err)
})
})
}
TurtleCoind.prototype._getInfo = function () {
return new Promise((resolve, reject) => {
this._queryRpc('getinfo').then((data) => {
return resolve(data)
}).catch((err) => {
return reject(util.format('Could not get /getInfo: %s', err))
})
})
}
TurtleCoind.prototype._getHeight = function () {
return new Promise((resolve, reject) => {
this._queryRpc('getheight').then((data) => {
return resolve(data)
}).catch((err) => {
return reject(util.format('Could not get /getheight: %s', err))
})
})
}
TurtleCoind.prototype._getTransactions = function () {
return new Promise((resolve, reject) => {
this._queryRpc('gettransactions').then((data) => {
return resolve(data)
}).catch((err) => {
return reject(util.format('Could not get /gettransactions: %s', err))
})
})
}
TurtleCoind.prototype._buildargs = function () {
var args = ''
if (this.dataDir) args = util.format('%s --data-dir %s', args, this.dataDir)
if (this.testnet) args = util.format('%s --testnet', args)
if (this.print) args = util.format('%s --print-genesis-tx', args)
if (this.enableCors) args = util.format('%s --enable-cors %s', args, this.enableCors)
if (this.enableBlockExplorer) args = util.format('%s --enable_blockexplorer', args)
if (this.rpcBindIp) args = util.format('%s --rpc-bind-ip %s', args, this.rpcBindIp)
if (this.rpcBindPort) args = util.format('%s --rpc-bind-port %s', args, this.rpcBindPort)
if (this.p2pBindIp) args = util.format('%s --p2p-bind-ip %s', args, this.p2pBindIp)
if (this.p2pBindPort) args = util.format('%s --p2p-bind-port %s', args, this.p2pBindPort)
if (this.p2pExternalPort) args = util.format('%s --p2p-external-port %s', args, this.p2pExternalPort)
if (this.allowLocalIp) args = util.format('%s --allow-local-ip', args)
if (Array.isArray(this.peers)) {
this.peers.forEach((peer) => {
args = util.format('%s --add-peer %s', args, peer)
})
} else if (this.peers) {
args = util.format('%s --add-peer %s', args, this.peers)
}
if (Array.isArray(this.priorityNodes)) {
this.priorityNodes.forEach((peer) => {
args = util.format('%s --add-priority-node %s', args, peer)
})
} else if (this.priorityNodes) {
args = util.format('%s --add-priority-node %s', args, this.priorityNodes)
}
if (Array.isArray(this.exclusiveNodes)) {
this.exclusiveNodes.forEach((peer) => {
args = util.format('%s --add-exclusive-node %s', args, peer)
})
} else if (this.exclusiveNodes) {
args = util.format('%s --add-exclusive-node %s', args, this.exclusiveNodes)
}
if (this.seedNode) args = util.format('%s --seed-node %s', args, this.seednode)
if (this.hideMyPort) args = util.format('%s --hide-my-port', args)
if (this.dbThreads) args = util.format('%s --db-threads %s', args, this.dbThreads)
if (this.dbMaxOpenFiles) args = util.format('%s --db-max-open-files %s', args, this.dbMaxOpenFiles)
if (this.dbWriteBufferSize) args = util.format('%s --db-write-buffer-size %s', args, this.dbWriteBufferSize)
if (this.dbReadCacheSize) args = util.format('%s --db-read-cache-size %s', args, this.dbReadCacheSize)
return args.split(' ')
}
module.exports = TurtleCoind