send_multigpu.js 18 KB

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