send_multigpu_gpu.js 18 KB

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