-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
316 lines (260 loc) · 9.57 KB
/
app.js
File metadata and controls
316 lines (260 loc) · 9.57 KB
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
import axios from 'axios'
import * as fs from 'node:fs'
import winston from 'winston'
import { extractUserIdFromJwtToken, generateRandomHardwareInfo, getIpAddressFromProxyUrl, getProxyAgent, sleep } from './utils.js'
// Global constants
const BASE_URI = 'https://gateway-run.bls.dev/api/v1'
const PING_INTERVAL = 120000
// Logger configuration function to add an account prefix
function createLogger(accountIdentifier) {
return winston.createLogger({
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.printf(({ timestamp, level, message }) =>
`${timestamp} | [${accountIdentifier}] ${level}: ${message}`
)
),
transports: [new winston.transports.Console()]
})
}
// Connection states
const CONNECTION_STATES = {
CONNECTED: 1,
DISCONNECTED: 2,
NONE_CONNECTION: 3
}
class AccountSession {
constructor(token, nodeId, hardwareId, proxy) {
try {
this.userId = extractUserIdFromJwtToken(token)
} catch (error) {
throw new Error(`Failed to extract userId from token: ${error.message}`)
}
this.token = token
this.nodeId = nodeId
this.proxy = proxy
this.extensionVersion = '0.1.7'
this.ipAddress = getIpAddressFromProxyUrl(proxy)
this.hardwareId = hardwareId
this.retries = 0
this.lastPingTime = 0
const shortNodeId = nodeId.substring(0, 9) + '...' + nodeId.substring(nodeId.length - 4)
this.logger = createLogger(`nodeId:${shortNodeId}@${this.ipAddress || 'no-proxy'}`)
}
async getHardwareInfo() {
const filePath = `hardwares/${this.nodeId}.json`
if (fs.existsSync(filePath)) {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'))
}
const hardwareInfo = generateRandomHardwareInfo()
fs.writeFileSync(filePath, JSON.stringify(hardwareInfo, null, 2))
return hardwareInfo
}
async start() {
try {
await this.registerNode()
await this.startSession()
await this.ping()
this.startPingLoop()
this.logger.info(`node ${this.nodeId} started`)
} catch (error) {
this.logger.error(`Initialization error: ${error.message}`)
}
}
async registerNode() {
// try to get node info
const node = await this.getNode()
if (node) {
this.logger.info(`Node ${this.nodeId} already registered`)
return
}
const hardwareInfo = await this.getHardwareInfo()
const response = await this.performRequest('post', `${BASE_URI}/nodes/${this.nodeId}`, {
ipAddress: this.ipAddress,
hardwareId: this.hardwareId,
hardwareInfo: hardwareInfo,
extensionVersion: this.extensionVersion
})
this.logger.info(`Register node response: ${JSON.stringify(response?.data)}`)
}
async getNode() {
const response = await this.performRequest('get', `${BASE_URI}/nodes/${this.nodeId}`)
this.logger.info(`Register node response: ${JSON.stringify(response?.data)}`)
}
async checkHealth() {
try {
const response = await this.performRequest('get', `https://gateway-run.bls.dev/health`)
const data = await response.json()
if (!data || data.status !== 'ok') {
this.logger.error(`Check health failed for proxy ${this.ipAddress}`)
return
}
this.logger.info(`Check health response: ${JSON.stringify(response?.data)}`)
} catch (error) {
this.logger.error(`Check health failed: ${error.message}`)
}
}
async startSession() {
try {
const response = await this.performRequest('post', `${BASE_URI}/nodes/${this.nodeId}/start-session`)
if (!response) {
this.logger.error(`Start session failed for proxy ${this.ipAddress}`)
return
}
this.logger.info(`Start session response: ${JSON.stringify(response?.data)}`)
} catch (error) {
this.logger.error(`Start session failed for proxy ${this.ipAddress}: ${error.message}`)
}
}
async performRequest(method, url, data, maxRetries = 3) {
const headers = {
'Authorization': `Bearer ${this.token}`,
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'application/json',
'Origin': 'chrome-extension://pljbjcehnhcnofmkdbjolghdcjnmekia',
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5"
}
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
let options = {
headers
}
if (this.proxy) {
const agent = await getProxyAgent(this.proxy)
this.logger.info(`Using proxy ${this.proxy} for request to ${url}`)
options.httpAgent = agent
options.httpsAgent = agent
}
let response = null
if (method === 'post') {
response = await axios.post(url, data || {}, options)
} else if (method === 'get') {
response = await axios.get(url, options)
}
if (!response) {
this.logger.error(`API call failed to ${url} for proxy ${this.ipAddress}, empty response`)
return null
}
this.logger.info(`response: status: ${response.status}(${response.statusText}), body: ${JSON.stringify(response?.data)}`)
return response
} catch (error) {
if (error.response) {
this.logger.error(`API call failed to ${url} for proxy ${this.ipAddress}: ${error.response.status}(${error.response.statusText})`)
}
this.logger.error(`API call failed to ${url} for proxy ${this.ipAddress}: ${error.message}`)
if (error.response && error.response.status === 403) return null
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000))
} finally {
this.logger.info(`Request to ${url} completed`)
}
}
this.logger.error(`API call failed to ${url} after ${maxRetries} attempts for proxy ${this.ipAddress}`)
return null
}
startPingLoop() {
const interval = setInterval(async () => {
await this.ping()
}, PING_INTERVAL)
this.logger.info(`Ping loop started with interval ${PING_INTERVAL}ms`)
process.on('SIGINT', () => clearInterval(interval))
}
async ping() {
const currentTime = Date.now()
if (currentTime - this.lastPingTime < PING_INTERVAL) {
this.logger.info(`Skipping ping for account ${this.userId} as interval has not elapsed yet`)
return
}
this.lastPingTime = currentTime
try {
const response = await this.performRequest('post', `${BASE_URI}/nodes/${this.nodeId}/ping`)
if (!response) {
this.logger.error(`Ping failed for proxy ${this.ipAddress}`)
this.handlePingFail(this.proxy, response)
return
}
const info = ` NodeId: ${this.nodeId}, proxy: ${this.ipAddress}`
if (!response.data.status) {
this.logger.info(`first time ping done: ${info}`)
} else if (response.data.status.toLowerCase() === 'ok') {
this.logger.info(`ping success: ${info}`)
} else {
this.logger.error(`ping failed: ${info}`)
}
} catch (error) {
this.logger.error(`Ping failed for proxy ${this.ipAddress}: ${error.message}`)
this.handlePingFail(proxy, null)
}
}
async stopPing() {
this.logger.info('Stopping ping loop')
clearInterval(this.pingInterval)
}
handlePingFail(proxy, response) {
this.retries++
if (response?.code === 403) {
this.handleLogout(proxy)
} else if (this.retries >= 2) {
this.statusConnect = CONNECTION_STATES.DISCONNECTED
}
}
handleLogout(proxy) {
this.statusConnect = CONNECTION_STATES.NONE_CONNECTION
this.logger.info(`Logged out and cleared session info for proxy ${proxy}`)
}
}
async function loadNodes() {
try {
// 结构: userToken|nodeId:hardwareId|proxy
const lines = fs.readFileSync('nodes.txt', 'utf-8')
// 移除空行和空格,引号
return lines.split('\n').filter(Boolean).map(token => token.trim().replace(/['"]+/g, '')).map(token => {
const [userToken, nodeIdHardwareId, proxy] = token.split('|')
const [nodeId, hardwareId] = nodeIdHardwareId.split(':')
return { userToken, nodeId, hardwareId, proxy }
})
} catch (error) {
console.log(`Failed to load tokens: ${error.message}`)
throw error
}
}
// Main function
async function main() {
console.log(`
------------------------------------------------------------
| Bless bot by @overtrue |
| Telegram: https://t.me/+ntyApQYvrBowZTc1 |
| GitHub: https://github.com/web3bothub/bless-network-bot |
------------------------------------------------------------
`)
console.log('Starting program...')
await sleep(3000)
try {
const nodes = await loadNodes()
if (nodes.length === 0) {
console.error('No nodes found in nodes.txt')
return
}
console.log(`Loaded ${nodes.length} nodes`)
const sessions = nodes.map(async ({ userToken, nodeId, hardwareId, proxy }) => {
const session = new AccountSession(userToken, nodeId, hardwareId, proxy)
await sleep(10000)
return session.start()
})
await Promise.allSettled(sessions)
console.log('All sessions started, you can view your all nodes status in https://bless.network/dashboard/nodes')
} catch (error) {
console.error(`Program terminated: ${error} `)
}
}
// SIGINT
process.on('SIGINT', () => {
console.log('Caught interrupt signal')
process.exit()
})
main().catch(error => {
console.error(`Fatal error: ${error} `)
})