send_multigpu.ts 15 KB

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