send_multigpu_gpu.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { Address, BitReader, BitString, Cell, TupleReader, beginCell, external, internal, parseTuple, storeMessage, toNano } from '@ton/core'
  2. import { KeyPair, getSecureRandomBytes, keyPairFromSeed, mnemonicToWalletKey } from '@ton/crypto'
  3. import axios from 'axios'
  4. // import { LiteClient, LiteRoundRobinEngine, LiteSingleEngine } from 'ton-lite-client'
  5. import { TonClient4 } from '@ton/ton';
  6. import { execSync, exec as exec_callback, spawn, ChildProcess } from 'child_process';
  7. import fs from 'fs'
  8. import { WalletContractV4 } from '@ton/ton';
  9. import dotenv from 'dotenv'
  10. import { givers1000, givers10000, givers100000 } from './givers_gpu'
  11. import arg from 'arg'
  12. import { LiteClient, LiteSingleEngine, LiteRoundRobinEngine } from 'ton-lite-client';
  13. import { getLiteClient, getTon4Client, getTonCenterClient, getTonapiClient } from './client';
  14. import { HighloadWalletV2 } from '@scaleton/highload-wallet';
  15. import { OpenedContract } from '@ton/core';
  16. import { Api } from 'tonapi-sdk-js';
  17. import { promisify } from 'util'
  18. const exec = promisify(exec_callback)
  19. dotenv.config({ path: 'config.txt.txt' })
  20. dotenv.config({ path: '.env.txt' })
  21. dotenv.config()
  22. dotenv.config({ path: 'config.txt' })
  23. type ApiObj = LiteClient | TonClient4 | Api<unknown>
  24. const args = arg({
  25. '--givers': Number, // 100 1000 10000
  26. '--api': String, // lite, tonhub, tonapi
  27. '--bin': String, // cuda, opencl or path to miner
  28. '--gpu-count': Number, // GPU COUNT!!!
  29. '--timeout': Number, // Timeout for mining in seconds
  30. '--allow-shards': Boolean, // if true - allows mining to other shards
  31. '-c': String, // blockchain config
  32. })
  33. let givers = givers1000
  34. if (args['--givers']) {
  35. const val = args['--givers']
  36. const allowed = [1000, 10000, 100000]
  37. if (!allowed.includes(val)) {
  38. throw new Error('Invalid --givers argument')
  39. }
  40. switch (val) {
  41. case 1000:
  42. givers = givers1000
  43. console.log('Using givers 1 000')
  44. break
  45. case 10000:
  46. givers = givers10000
  47. console.log('Using givers 10 000')
  48. break
  49. case 100000:
  50. givers = givers100000
  51. console.log('Using givers 100 000')
  52. break
  53. }
  54. } else {
  55. console.log('Using givers 1 000')
  56. }
  57. let bin = '.\\pow-miner-cuda.exe'
  58. if (args['--bin']) {
  59. const argBin = args['--bin']
  60. if (argBin === 'cuda') {
  61. bin = '.\\pow-miner-cuda.exe'
  62. } else if (argBin === 'opencl' || argBin === 'amd') {
  63. bin = '.\\pow-miner-opencl.exe'
  64. } else {
  65. bin = argBin
  66. }
  67. }
  68. console.log('Using bin', bin)
  69. const gpus = args['--gpu-count'] ?? 1
  70. const timeout = args['--timeout'] ?? 5
  71. const allowShards = args['--allow-shards'] ?? false
  72. console.log('Using GPUs count', gpus)
  73. console.log('Using timeout', timeout)
  74. const mySeed = process.env.SEED as string
  75. const totalDiff = BigInt('115792089237277217110272752943501742914102634520085823245724998868298727686144')
  76. const envAddress = process.env.TARGET_ADDRESS
  77. let TARGET_ADDRESS: string | undefined = undefined
  78. if (envAddress) {
  79. try {
  80. TARGET_ADDRESS = Address.parse(envAddress).toString({ urlSafe: true, bounceable: false })
  81. }
  82. catch (e) {
  83. console.log('Couldnt parse target address')
  84. process.exit(1)
  85. }
  86. }
  87. let bestGiver: { address: string, coins: number } = { address: '', coins: 0 }
  88. async function updateBestGivers(liteClient: ApiObj, myAddress: Address) {
  89. const giver = givers[Math.floor(Math.random() * givers.length)]
  90. bestGiver = {
  91. address: giver.address,
  92. coins: giver.reward,
  93. }
  94. }
  95. async function getPowInfo(liteClient: ApiObj, address: Address): Promise<[bigint, bigint, bigint]> {
  96. if (liteClient instanceof TonClient4) {
  97. const lastInfo = await CallForSuccess(() => liteClient.getLastBlock())
  98. const powInfo = await CallForSuccess(() => liteClient.runMethod(lastInfo.last.seqno, address, 'get_pow_params', []))
  99. const reader = new TupleReader(powInfo.result)
  100. const seed = reader.readBigNumber()
  101. const complexity = reader.readBigNumber()
  102. const iterations = reader.readBigNumber()
  103. return [seed, complexity, iterations]
  104. } else if (liteClient instanceof LiteClient) {
  105. const lastInfo = await liteClient.getMasterchainInfo()
  106. const powInfo = await liteClient.runMethod(address, 'get_pow_params', Buffer.from([]), lastInfo.last)
  107. const powStack = Cell.fromBase64(powInfo.result as string)
  108. const stack = parseTuple(powStack)
  109. const reader = new TupleReader(stack)
  110. const seed = reader.readBigNumber()
  111. const complexity = reader.readBigNumber()
  112. const iterations = reader.readBigNumber()
  113. return [seed, complexity, iterations]
  114. } else if (liteClient instanceof Api) {
  115. try {
  116. const powInfo = await CallForSuccess(
  117. () => liteClient.blockchain.execGetMethodForBlockchainAccount(address.toRawString(), 'get_pow_params', {}),
  118. 50,
  119. 300)
  120. const seed = BigInt(powInfo.stack[0].num as string)
  121. const complexity = BigInt(powInfo.stack[1].num as string)
  122. const iterations = BigInt(powInfo.stack[2].num as string)
  123. return [seed, complexity, iterations]
  124. } catch (e) {
  125. console.log('ls error', e)
  126. }
  127. }
  128. throw new Error('invalid client')
  129. }
  130. let go = true
  131. let i = 0
  132. let success = 0
  133. let lastMinedSeed: bigint = BigInt(0)
  134. let start = Date.now()
  135. async function main() {
  136. const minerOk = await testMiner(gpus)
  137. if (!minerOk) {
  138. console.log('Your miner is not working')
  139. console.log('Check if you use correct bin (cuda, amd).')
  140. console.log('If it doesn\'t help, try to run test_cuda or test_opencl script, to find out issue')
  141. process.exit(1)
  142. }
  143. let liteClient: ApiObj
  144. if (!args['--api']) {
  145. console.log('Using TonHub API')
  146. liteClient = await getTon4Client()
  147. } else {
  148. if (args['--api'] === 'lite') {
  149. console.log('Using LiteServer API')
  150. liteClient = await getLiteClient(args['-c'] ?? 'https://ton-blockchain.github.io/global.config.json')
  151. } else if (args['--api'] === 'tonapi') {
  152. console.log('Using TonApi')
  153. liteClient = await getTonapiClient()
  154. } else {
  155. console.log('Using TonHub API')
  156. liteClient = await getTon4Client()
  157. }
  158. }
  159. const keyPair = await mnemonicToWalletKey(mySeed.split(' '))
  160. const wallet = WalletContractV4.create({
  161. workchain: 0,
  162. publicKey: keyPair.publicKey
  163. })
  164. if (args['--wallet'] === 'highload') {
  165. console.log('Using highload wallet', wallet.address.toString({ bounceable: false, urlSafe: true }))
  166. } else {
  167. console.log('Using v4r2 wallet', wallet.address.toString({ bounceable: false, urlSafe: true }))
  168. }
  169. const targetAddress = TARGET_ADDRESS ?? wallet.address.toString({ bounceable: false, urlSafe: true })
  170. console.log('Target address:', targetAddress)
  171. console.log('Date, time, status, seed, attempts, successes, timespent')
  172. try {
  173. await updateBestGivers(liteClient, wallet.address)
  174. } catch (e) {
  175. console.log('error', e)
  176. throw Error('no givers')
  177. }
  178. setInterval(() => {
  179. updateBestGivers(liteClient, wallet.address)
  180. }, 5000)
  181. while (go) {
  182. const giverAddress = bestGiver.address
  183. const [seed, complexity, iterations] = await getPowInfo(liteClient, Address.parse(giverAddress))
  184. if (seed === lastMinedSeed) {
  185. // console.log('Wating for a new seed')
  186. updateBestGivers(liteClient, wallet.address)
  187. await delay(200)
  188. continue
  189. }
  190. const promises: any[] = []
  191. let handlers: ChildProcess[] = []
  192. const mined: Buffer | undefined = await new Promise(async (resolve, reject) => {
  193. let rest = gpus
  194. for (let i = 0; i < gpus; i++) {
  195. const randomName = (await getSecureRandomBytes(8)).toString('hex') + '.boc'
  196. const path = `bocs/${randomName}`
  197. const command = `-g ${i} -F 128 -t ${timeout} ${targetAddress} ${seed} ${complexity} ${iterations} ${giverAddress} ${path}`
  198. const procid = spawn(bin, command.split(' '), { stdio: "pipe" });
  199. // procid.on('message', (m) => {
  200. // console.log('message', m)
  201. // })
  202. // procid.stdout.on('data', (data) => {
  203. // console.log(`stdout: ${data}`);
  204. // })
  205. // procid.stderr.on('data', (data) => {
  206. // console.log(`err: ${data}`);
  207. // })
  208. handlers.push(procid)
  209. procid.on('exit', () => {
  210. let mined: Buffer | undefined = undefined
  211. try {
  212. const exists = fs.existsSync(path)
  213. if (exists) {
  214. mined = fs.readFileSync(path)
  215. resolve(mined)
  216. lastMinedSeed = seed
  217. fs.rmSync(path)
  218. for (const handle of handlers) {
  219. handle.kill('SIGINT')
  220. }
  221. }
  222. } catch (e) {
  223. //
  224. console.log('not mined', e)
  225. } finally {
  226. if (--rest === 0) {
  227. resolve(undefined)
  228. }
  229. }
  230. })
  231. }
  232. })
  233. if (!mined) {
  234. console.log(`${formatTime()}: not mined`, seed.toString(16).slice(0, 4), i++, success, Math.floor((Date.now() - start) / 1000))
  235. }
  236. if (mined) {
  237. const [newSeed] = await getPowInfo(liteClient, Address.parse(giverAddress))
  238. if (newSeed !== seed) {
  239. console.log('Mined already too late seed')
  240. continue
  241. }
  242. console.log(`${formatTime()}: mined`, seed.toString(16).slice(0, 4), i++, ++success, Math.floor((Date.now() - start) / 1000))
  243. let seqno = 0
  244. if (liteClient instanceof LiteClient || liteClient instanceof TonClient4) {
  245. let w = liteClient.open(wallet)
  246. try {
  247. seqno = await CallForSuccess(() => w.getSeqno())
  248. } catch (e) {
  249. //
  250. }
  251. } else {
  252. const res = await CallForSuccess(
  253. () => (liteClient as Api<unknown>).blockchain.execGetMethodForBlockchainAccount(wallet.address.toRawString(), "seqno", {}),
  254. 50,
  255. 250
  256. )
  257. if (res.success) {
  258. seqno = Number(BigInt(res.stack[0].num as string))
  259. }
  260. }
  261. await sendMinedBoc(wallet, seqno, keyPair, giverAddress, Cell.fromBoc(mined)[0].asSlice().loadRef())
  262. }
  263. }
  264. }
  265. main()
  266. async function sendMinedBoc(
  267. wallet: WalletContractV4,
  268. seqno: number,
  269. keyPair: KeyPair,
  270. giverAddress: string,
  271. boc: Cell
  272. ) {
  273. if (args['--api'] === 'tonapi') {
  274. const tonapiClient = await getTonapiClient()
  275. const transfer = wallet.createTransfer({
  276. seqno,
  277. secretKey: keyPair.secretKey,
  278. messages: [internal({
  279. to: giverAddress,
  280. value: toNano('0.05'),
  281. bounce: true,
  282. body: boc,
  283. })],
  284. sendMode: 3 as any,
  285. })
  286. const msg = beginCell().store(storeMessage(external({
  287. to: wallet.address,
  288. body: transfer
  289. }))).endCell()
  290. let k = 0
  291. let lastError: unknown
  292. while (k < 20) {
  293. try {
  294. await tonapiClient.blockchain.sendBlockchainMessage({
  295. boc: msg.toBoc().toString('base64'),
  296. })
  297. break
  298. // return res
  299. } catch (e: any) {
  300. // lastError = err
  301. k++
  302. if (e.status === 429) {
  303. await delay(200)
  304. } else {
  305. // console.log('tonapi error')
  306. k = 20
  307. break
  308. }
  309. }
  310. }
  311. return
  312. }
  313. const wallets: OpenedContract<WalletContractV4>[] = []
  314. const ton4Client = await getTon4Client()
  315. const w2 = ton4Client.open(wallet)
  316. wallets.push(w2)
  317. if (args['--api'] === 'lite') {
  318. const liteServerClient = await getLiteClient(args['-c'] ?? 'https://ton-blockchain.github.io/global.config.json')
  319. const w1 = liteServerClient.open(wallet)
  320. wallets.push(w1)
  321. }
  322. for (let i = 0; i < 3; i++) {
  323. for (const w of wallets) {
  324. w.sendTransfer({
  325. seqno,
  326. secretKey: keyPair.secretKey,
  327. messages: [internal({
  328. to: giverAddress,
  329. value: toNano('0.05'),
  330. bounce: true,
  331. body: boc,
  332. })],
  333. sendMode: 3 as any,
  334. }).catch(e => {
  335. //
  336. })
  337. }
  338. }
  339. }
  340. async function testMiner(gpus: number): Promise<boolean> {
  341. for (let i = 0; i < gpus; i++) {
  342. const gpu = i
  343. const randomName = (await getSecureRandomBytes(8)).toString('hex') + '.boc'
  344. const path = `bocs/${randomName}`
  345. const command = `${bin} -g ${gpu} -F 128 -t ${timeout} kQBWkNKqzCAwA9vjMwRmg7aY75Rf8lByPA9zKXoqGkHi8SM7 229760179690128740373110445116482216837 53919893334301279589334030174039261347274288845081144962207220498400000000000 10000000000 kQBWkNKqzCAwA9vjMwRmg7aY75Rf8lByPA9zKXoqGkHi8SM7 ${path}`
  346. try {
  347. const output = execSync(command, { encoding: 'utf-8', stdio: "pipe" }); // the default is 'buffer'
  348. } catch (e) {
  349. }
  350. let mined: Buffer | undefined = undefined
  351. try {
  352. mined = fs.readFileSync(path)
  353. fs.rmSync(path)
  354. } catch (e) {
  355. //
  356. }
  357. if (!mined) {
  358. return false
  359. }
  360. }
  361. return true
  362. }
  363. // Function to call ton api untill we get response.
  364. // Because testnet is pretty unstable we need to make sure response is final
  365. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  366. export async function CallForSuccess<T extends (...args: any[]) => any>(
  367. toCall: T,
  368. attempts = 20,
  369. delayMs = 100
  370. ): Promise<ReturnType<T>> {
  371. if (typeof toCall !== 'function') {
  372. throw new Error('unknown input')
  373. }
  374. let i = 0
  375. let lastError: unknown
  376. while (i < attempts) {
  377. try {
  378. const res = await toCall()
  379. return res
  380. } catch (err) {
  381. lastError = err
  382. i++
  383. await delay(delayMs)
  384. }
  385. }
  386. console.log('error after attempts', i)
  387. throw lastError
  388. }
  389. export function delay(ms: number) {
  390. return new Promise((resolve) => {
  391. setTimeout(resolve, ms)
  392. })
  393. }
  394. function formatTime() {
  395. return new Date().toLocaleTimeString('en-US', {
  396. hour12: false,
  397. hour: "numeric",
  398. minute: "numeric",
  399. day: "numeric",
  400. month: "numeric",
  401. year: "numeric",
  402. second: "numeric"
  403. });
  404. }