send_universal.js 16 KB

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