send_universal.js 16 KB

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