send_multigpu_meridian.js 19 KB

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