forked from web3bothub/nodepay-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
284 lines (245 loc) · 8.63 KB
/
app.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import axios from 'axios'
import { promises as fs } from 'fs'
import { v4 as uuidV4 } from 'uuid'
import winston from 'winston'
import { getIpAddress, getProxyAgent, getRandomUserAgent, sleep } from './utils.js'
// Global constants
const DOMAIN_API = {
SESSION: 'http://api.nodepay.ai/api/auth/session',
PING: [
"http://52.77.10.116/api/network/ping",
"http://18.142.29.174/api/network/ping",
"http://13.215.134.222/api/network/ping",
"http://54.255.192.166/api/network/ping",
]
}
const PING_INTERVAL = 180 * 1000 // 180 seconds
// 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, id) {
this.accountId = id
this.token = token
this.browserId = uuidV4()
this.accountInfo = {}
this.proxyAuthStatus = false
this.statusConnect = CONNECTION_STATES.NONE_CONNECTION
this.retries = 0
this.lastPingTime = 0
this.proxies = []
this.userAgent = getRandomUserAgent()
this.logger = createLogger(`token:${id}`)
}
async init() {
try {
await this.getProxies()
await this.authenticate()
await this.ping()
this.startPingLoop()
} catch (error) {
this.logger.error(`Initialization error: ${error.message}`)
}
}
async getProxies() {
try {
// First, try to load the account-specific proxy file
const accountProxyPath = `./proxies/${this.accountId}.txt`
const proxyData = await fs.readFile(accountProxyPath, 'utf-8').catch(async () => {
// If account-specific file is not found, fall back to root proxies.txt
const rootProxyPath = './proxies.txt'
this.logger.info(`Account-specific proxy file(${accountProxyPath}) not found, trying ${rootProxyPath} instead.`)
return await fs.readFile(rootProxyPath, 'utf-8')
})
this.proxies = proxyData.split('\n').filter(Boolean)
if (!this.proxies.length) {
throw new Error('No proxies found in either account-specific or root proxy file')
}
this.logger.info(`Loaded ${this.proxies.length} proxies for account token ${this.accountId}.`)
} catch (error) {
this.logger.error(`Failed to load proxies: ${error.message}`)
throw error
}
}
async authenticate() {
for (const proxy of this.proxies) {
try {
if (!this.proxyAuthStatus) {
this.browserId = uuidV4()
const ipAddress = await getIpAddress(proxy)
this.logger.info(`IP address: ${ipAddress}`)
const response = await this.performRequest(DOMAIN_API.SESSION, {}, proxy)
if (!response) continue
if (!response || !response.data || response.data.code < 0) {
throw new Error('Invalid response')
}
if (response.data.code !== 0) {
this.logger.error(`Failed to authenticate with proxy ${proxy}: ${JSON.stringify(response.data)}, response.data.code is not 0`)
this.handleLogout(proxy)
continue
}
this.accountInfo = response.data.data
if (this.accountInfo.uid) {
this.proxyAuthStatus = true
this.saveSessionInfo()
this.logger.info(`Authenticated with proxy ${proxy}`)
} else {
this.logger.error(`Failed to authenticate with proxy ${proxy}: ${JSON.stringify(this.accountInfo)}, response.data.data.uid is not found`)
this.handleLogout(proxy)
continue
}
}
} catch (error) {
this.logger.error(`Failed to authenticate with proxy: ${proxy}: ${error.message}`)
}
}
}
async performRequest(url, data, proxy, maxRetries = 3) {
const headers = {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
'User-Agent': this.userAgent
}
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
let options = {
headers
}
if (proxy) {
const agent = await getProxyAgent(proxy)
this.logger.info(`Using proxy ${proxy} for request to ${url}`)
options.httpAgent = agent
options.httpsAgent = agent
}
const response = await axios.post(url, data, options)
return response
} catch (error) {
this.logger.error(`API call failed to ${url} for proxy ${proxy}: ${error.message}`)
if (error.response && error.response.status === 403) return null
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000))
}
}
this.logger.error(`API call failed to ${url} after ${maxRetries} attempts for proxy ${proxy}`)
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.accountId} as interval has not elapsed yet`)
return
}
this.lastPingTime = currentTime
for (const proxy of this.proxies) {
try {
const data = {
id: this.accountInfo.uid,
browser_id: this.browserId,
timestamp: Math.floor(currentTime / 1000),
version: '2.2.7'
}
// foreach each PING API, try to ping
let pingSuccess = false
for (const pingApi of DOMAIN_API.PING) {
this.logger.info(`Pinging [${pingApi}] for proxy ${proxy}`)
const response = await this.performRequest(pingApi, data, proxy)
this.logger.info(`Ping response: ${JSON.stringify(response?.data)}`)
if (response && response.data && response.data.code === 0) {
this.retries = 0
this.statusConnect = CONNECTION_STATES.CONNECTED
pingSuccess = true
this.logger.info(`Ping successful for proxy ${proxy}`)
break
}
}
if (!pingSuccess) {
this.logger.error(`Ping failed for proxy ${proxy}, tried all endpoints.`)
this.handlePingFail(proxy, null)
}
} catch (error) {
this.logger.error(`Ping failed for proxy ${proxy}`)
this.handlePingFail(proxy, null)
}
}
}
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.accountInfo = {}
this.proxyAuthStatus = false
this.logger.info(`Logged out and cleared session info for proxy ${proxy}`)
}
saveSessionInfo() {
// Placeholder for saving session info if needed
}
}
async function loadTokens() {
try {
const tokens = await fs.readFile('tokens.txt', 'utf-8')
// 移除空行和空格,引号
return tokens.split('\n').filter(Boolean).map(token => token.trim().replace(/['"]+/g, ''))
} catch (error) {
console.log(`Failed to load tokens: ${error.message}`)
throw error
}
}
// Main function
async function main() {
console.log(`
_ __ __ ___ ___ __
/ |/ /__ ___/ /__ / _ \\___ ___ __/ _ )___ / /_
/ / _ \\/ _ / -_) ___/ _ \`/ // / _ / _ \\/ __/
/_/|_/\\___/\\_,_/\\__/_/ \\_,_/\\_, /____/\\___/\\__/
/___/
-----------------------------------------------------
| NodePay bot by @overtrue |
| Telegram: https://t.me/+ntyApQYvrBowZTc1 |
| GitHub: https://github.com/web3bothub/nodepay-bot |
------------------------------------------------------
`)
console.log('Starting program...')
await sleep(3000)
try {
const tokens = await loadTokens()
const sessions = tokens.map(async (token, index) => {
const session = new AccountSession(token, index + 1)
await sleep(10000)
return session.init()
})
await Promise.allSettled(sessions)
} catch (error) {
console.error(`Program terminated: ${error} `)
}
}
main().catch(error => {
console.error(`Fatal error: ${error} `)
})