send_universal_gpu.js 16 KB

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