send_multigpu_meridian.ts 16 KB

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