forked from TrueCarry/JettonGramGpuMiner
-
Notifications
You must be signed in to change notification settings - Fork 1
/
send_multigpu.ts
446 lines (385 loc) · 14.8 KB
/
send_multigpu.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import { Address, BitReader, BitString, Cell, TupleReader, beginCell, external, internal, parseTuple, storeMessage, toNano } from '@ton/core'
import { KeyPair, getSecureRandomBytes, keyPairFromSeed, mnemonicToWalletKey } from '@ton/crypto'
import axios from 'axios'
// import { LiteClient, LiteRoundRobinEngine, LiteSingleEngine } from 'ton-lite-client'
import { TonClient4 } from '@ton/ton';
import { execSync, exec as exec_callback, spawn, ChildProcess } from 'child_process';
import fs from 'fs'
import { WalletContractV4 } from '@ton/ton';
import dotenv from 'dotenv'
import { givers } from './config'
import arg from 'arg'
import { LiteClient, LiteSingleEngine, LiteRoundRobinEngine } from 'ton-lite-client';
import { getLiteClient, getTon4Client, getTonCenterClient, getTonapiClient } from './client';
import { HighloadWalletV2 } from '@scaleton/highload-wallet';
import { OpenedContract } from '@ton/core';
import { Api } from 'tonapi-sdk-js';
import { promisify } from 'util'
const exec = promisify(exec_callback)
dotenv.config({ path: 'config.txt.txt' })
dotenv.config({ path: '.env.txt' })
dotenv.config()
dotenv.config({ path: 'config.txt' })
type ApiObj = LiteClient | TonClient4 | Api<unknown>
const args = arg({
'--api': String, // lite, tonhub, tonapi
'--bin': String, // cuda, opencl or path to miner
'--gpu-count': Number, // GPU COUNT!!!
'--timeout': Number, // Timeout for mining in seconds
'--allow-shards': Boolean, // if true - allows mining to other shards
'-c': String, // blockchain config
})
let bin = '.\\pow-miner-cuda.exe'
if (args['--bin']) {
const argBin = args['--bin']
if (argBin === 'cuda') {
bin = '.\\pow-miner-cuda.exe'
} else if (argBin === 'opencl' || argBin === 'amd') {
bin = '.\\pow-miner-opencl.exe'
} else {
bin = argBin
}
}
console.log('Using bin', bin)
const gpus = args['--gpu-count'] ?? 1
const timeout = args['--timeout'] ?? 5
const allowShards = args['--allow-shards'] ?? false
console.log('Using GPUs count', gpus)
console.log('Using timeout', timeout)
const mySeed = process.env.SEED as string
const totalDiff = BigInt('115792089237277217110272752943501742914102634520085823245724998868298727686144')
const envAddress = process.env.TARGET_ADDRESS
let TARGET_ADDRESS: string | undefined = undefined
if (envAddress) {
try {
TARGET_ADDRESS = Address.parse(envAddress).toString({ urlSafe: true, bounceable: false })
}
catch (e) {
console.log('Couldnt parse target address')
process.exit(1)
}
}
let bestGiver: { address: string } = { address: '' }
async function updateBestGivers(liteClient: ApiObj, myAddress: Address) {
const giver = givers[Math.floor(Math.random() * givers.length)]
bestGiver = {
address: giver.address,
}
}
async function getPowInfo(liteClient: ApiObj, address: Address): Promise<[bigint, bigint, bigint]> {
if (liteClient instanceof TonClient4) {
const lastInfo = await CallForSuccess(() => liteClient.getLastBlock())
const powInfo = await CallForSuccess(() => liteClient.runMethod(lastInfo.last.seqno, address, 'get_pow_params', []))
const reader = new TupleReader(powInfo.result)
const seed = reader.readBigNumber()
const complexity = reader.readBigNumber()
const iterations = reader.readBigNumber()
return [seed, complexity, iterations]
} else if (liteClient instanceof LiteClient) {
const lastInfo = await liteClient.getMasterchainInfo()
const powInfo = await liteClient.runMethod(address, 'get_pow_params', Buffer.from([]), lastInfo.last)
const powStack = Cell.fromBase64(powInfo.result as string)
const stack = parseTuple(powStack)
const reader = new TupleReader(stack)
const seed = reader.readBigNumber()
const complexity = reader.readBigNumber()
const iterations = reader.readBigNumber()
return [seed, complexity, iterations]
} else if (liteClient instanceof Api) {
try {
const powInfo = await CallForSuccess(
() => liteClient.blockchain.execGetMethodForBlockchainAccount(address.toRawString(), 'get_pow_params', {}),
50,
300)
const seed = BigInt(powInfo.stack[0].num as string)
const complexity = BigInt(powInfo.stack[1].num as string)
const iterations = BigInt(powInfo.stack[2].num as string)
return [seed, complexity, iterations]
} catch (e) {
console.log('ls error', e)
}
}
throw new Error('invalid client')
}
let go = true
let i = 0
let success = 0
let lastMinedSeed: bigint = BigInt(0)
let start = Date.now()
async function main() {
const minerOk = await testMiner(gpus)
if (!minerOk) {
console.log('Your miner is not working')
console.log('Check if you use correct bin (cuda, amd).')
console.log('If it doesn\'t help, try to run test_cuda or test_opencl script, to find out issue')
process.exit(1)
}
let liteClient: ApiObj
if (!args['--api']) {
console.log('Using TonHub API')
liteClient = await getTon4Client()
} else {
if (args['--api'] === 'lite') {
console.log('Using LiteServer API')
liteClient = await getLiteClient(args['-c'] ?? 'https://ton-blockchain.github.io/global.config.json')
} else if (args['--api'] === 'tonapi') {
console.log('Using TonApi')
liteClient = await getTonapiClient()
} else {
console.log('Using TonHub API')
liteClient = await getTon4Client()
}
}
const keyPair = await mnemonicToWalletKey(mySeed.split(' '))
const wallet = WalletContractV4.create({
workchain: 0,
publicKey: keyPair.publicKey
})
if (args['--wallet'] === 'highload') {
console.log('Using highload wallet', wallet.address.toString({ bounceable: false, urlSafe: true }))
} else {
console.log('Using v4r2 wallet', wallet.address.toString({ bounceable: false, urlSafe: true }))
}
const targetAddress = TARGET_ADDRESS ?? wallet.address.toString({ bounceable: false, urlSafe: true })
console.log('Target address:', targetAddress)
console.log('Date, time, status, seed, attempts, successes, timespent')
try {
await updateBestGivers(liteClient, wallet.address)
} catch (e) {
console.log('error', e)
throw Error('no givers')
}
setInterval(() => {
updateBestGivers(liteClient, wallet.address)
}, 5000)
while (go) {
const giverAddress = bestGiver.address
const [seed, complexity, iterations] = await getPowInfo(liteClient, Address.parse(giverAddress))
const prettyDifficulty = getPrettyDifficulty(giverAddress, complexity)
if (seed === lastMinedSeed) {
// console.log('Wating for a new seed')
updateBestGivers(liteClient, wallet.address)
await delay(200)
continue
}
const promises: any[] = []
let handlers: ChildProcess[] = []
const mined: Buffer | undefined = await new Promise(async (resolve, reject) => {
let rest = gpus
for (let i = 0; i < gpus; i++) {
const randomName = (await getSecureRandomBytes(8)).toString('hex') + '.boc'
const path = `bocs/${randomName}`
const command = `-g ${i} -F 128 -t ${timeout} ${targetAddress} ${seed} ${complexity} ${iterations} ${giverAddress} ${path}`
const procid = spawn(bin, command.split(' '), { stdio: "pipe" });
// procid.on('message', (m) => {
// console.log('message', m)
// })
// procid.stdout.on('data', (data) => {
// console.log(`stdout: ${data}`);
// })
// procid.stderr.on('data', (data) => {
// console.log(`err: ${data}`);
// })
handlers.push(procid)
procid.on('exit', () => {
let mined: Buffer | undefined = undefined
try {
const exists = fs.existsSync(path)
if (exists) {
mined = fs.readFileSync(path)
resolve(mined)
lastMinedSeed = seed
fs.rmSync(path)
for (const handle of handlers) {
handle.kill('SIGINT')
}
}
} catch (e) {
//
console.log('not mined', e)
} finally {
if (--rest === 0) {
resolve(undefined)
}
}
})
}
})
if (!mined) {
console.log(`${formatTime()}: not mined`, seed.toString(16).slice(0, 4), i++, success, Math.floor((Date.now() - start) / 1000), giverAddress, prettyDifficulty)
}
if (mined) {
const [newSeed] = await getPowInfo(liteClient, Address.parse(giverAddress))
if (newSeed !== seed) {
console.log('Mined already too late seed')
continue
}
console.log(`${formatTime()}: mined`, seed.toString(16).slice(0, 4), i++, ++success, Math.floor((Date.now() - start) / 1000), giverAddress, prettyDifficulty)
let seqno = 0
if (liteClient instanceof LiteClient || liteClient instanceof TonClient4) {
let w = liteClient.open(wallet)
try {
seqno = await CallForSuccess(() => w.getSeqno())
} catch (e) {
//
}
} else {
const res = await CallForSuccess(
() => (liteClient as Api<unknown>).blockchain.execGetMethodForBlockchainAccount(wallet.address.toRawString(), "seqno", {}),
50,
250
)
if (res.success) {
seqno = Number(BigInt(res.stack[0].num as string))
}
}
await sendMinedBoc(wallet, seqno, keyPair, giverAddress, Cell.fromBoc(mined)[0].asSlice().loadRef())
}
}
}
main()
async function sendMinedBoc(
wallet: WalletContractV4,
seqno: number,
keyPair: KeyPair,
giverAddress: string,
boc: Cell
) {
if (args['--api'] === 'tonapi') {
const tonapiClient = await getTonapiClient()
const transfer = wallet.createTransfer({
seqno,
secretKey: keyPair.secretKey,
messages: [internal({
to: giverAddress,
value: toNano('0.05'),
bounce: true,
body: boc,
})],
sendMode: 3 as any,
})
const msg = beginCell().store(storeMessage(external({
to: wallet.address,
body: transfer
}))).endCell()
let k = 0
let lastError: unknown
while (k < 20) {
try {
await tonapiClient.blockchain.sendBlockchainMessage({
boc: msg.toBoc().toString('base64'),
})
break
// return res
} catch (e: any) {
// lastError = err
k++
if (e.status === 429) {
await delay(200)
} else {
// console.log('tonapi error')
k = 20
break
}
}
}
return
}
const wallets: OpenedContract<WalletContractV4>[] = []
const ton4Client = await getTon4Client()
const w2 = ton4Client.open(wallet)
wallets.push(w2)
if (args['--api'] === 'lite') {
const liteServerClient = await getLiteClient(args['-c'] ?? 'https://ton-blockchain.github.io/global.config.json')
const w1 = liteServerClient.open(wallet)
wallets.push(w1)
}
for (let i = 0; i < 3; i++) {
for (const w of wallets) {
w.sendTransfer({
seqno,
secretKey: keyPair.secretKey,
messages: [internal({
to: giverAddress,
value: toNano('0.05'),
bounce: true,
body: boc,
})],
sendMode: 3 as any,
}).catch(e => {
//
})
}
}
}
async function testMiner(gpus: number): Promise<boolean> {
for (let i = 0; i < gpus; i++) {
const gpu = i
const randomName = (await getSecureRandomBytes(8)).toString('hex') + '.boc'
const path = `bocs/${randomName}`
const command = `${bin} -g ${gpu} -F 128 -t ${timeout} kQBWkNKqzCAwA9vjMwRmg7aY75Rf8lByPA9zKXoqGkHi8SM7 229760179690128740373110445116482216837 53919893334301279589334030174039261347274288845081144962207220498400000000000 10000000000 kQBWkNKqzCAwA9vjMwRmg7aY75Rf8lByPA9zKXoqGkHi8SM7 ${path}`
try {
const output = execSync(command, { encoding: 'utf-8', stdio: "pipe" }); // the default is 'buffer'
} catch (e) {
}
let mined: Buffer | undefined = undefined
try {
mined = fs.readFileSync(path)
fs.rmSync(path)
} catch (e) {
//
}
if (!mined) {
return false
}
}
return true
}
// Function to call ton api untill we get response.
// Because testnet is pretty unstable we need to make sure response is final
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function CallForSuccess<T extends (...args: any[]) => any>(
toCall: T,
attempts = 20,
delayMs = 100
): Promise<ReturnType<T>> {
if (typeof toCall !== 'function') {
throw new Error('unknown input')
}
let i = 0
let lastError: unknown
while (i < attempts) {
try {
const res = await toCall()
return res
} catch (err) {
lastError = err
i++
await delay(delayMs)
}
}
console.log('error after attempts', i)
throw lastError
}
export function delay(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
function formatTime() {
return new Date().toLocaleTimeString('en-US', {
hour12: false,
hour: "numeric",
minute: "numeric",
day: "numeric",
month: "numeric",
year: "numeric",
second: "numeric"
});
}
const twoPow256 = BigInt(2) ** BigInt(256)
function getPrettyDifficulty(address: string, complexity: BigInt): string {
const difficulty: BigInt = twoPow256 / complexity
const prettyDifficulty = Number(difficulty / BigInt(1000000000)).toFixed(0)
return prettyDifficulty + 'G'
}