send_universal.ts 14 KB

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