send_universal.ts 14 KB

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