send_universal_things.ts 14 KB

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