send_multigpu_things.ts 15 KB

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