send_universal_TESTING.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. dotenv_1.default.config({ path: 'config.txt.txt' });
  30. dotenv_1.default.config({ path: '.env.txt' });
  31. dotenv_1.default.config();
  32. dotenv_1.default.config({ path: 'config.txt' });
  33. const args = (0, arg_1.default)({
  34. '--givers': Number, // 100 1000 10000
  35. '--api': String, // lite, tonhub
  36. '--bin': String, // cuda, opencl or path to miner
  37. '--gpu': Number, // gpu id, default 0
  38. '--timeout': Number, // Timeout for mining in seconds
  39. '--allow-shards': Boolean, // if true - allows mining to other shards
  40. '-c': String, // blockchain config
  41. });
  42. let givers = givers_1.givers1000;
  43. if (args['--givers']) {
  44. const val = args['--givers'];
  45. const allowed = [100, 1000];
  46. if (!allowed.includes(val)) {
  47. throw new Error('Invalid --givers argument');
  48. }
  49. switch (val) {
  50. case 100:
  51. givers = givers_1.givers100;
  52. console.log('Using givers 100');
  53. break;
  54. case 1000:
  55. givers = givers_1.givers1000;
  56. console.log('Using givers 1 000');
  57. break;
  58. // case 10000:
  59. // givers = givers10000
  60. // console.log('Using givers 10 000')
  61. // break
  62. }
  63. }
  64. else {
  65. console.log('Using givers 10 000');
  66. }
  67. let bin = '.\\pow-miner-cuda.exe';
  68. if (args['--bin']) {
  69. const argBin = args['--bin'];
  70. if (argBin === 'cuda') {
  71. bin = '.\\pow-miner-cuda.exe';
  72. }
  73. else if (argBin === 'opencl' || argBin === 'amd') {
  74. bin = '.\\pow-miner-opencl.exe';
  75. }
  76. else {
  77. bin = argBin;
  78. }
  79. }
  80. console.log('Using bin', bin);
  81. const gpu = (_a = args['--gpu']) !== null && _a !== void 0 ? _a : 0;
  82. const timeout = (_b = args['--timeout']) !== null && _b !== void 0 ? _b : 5;
  83. const allowShards = (_c = args['--allow-shards']) !== null && _c !== void 0 ? _c : false;
  84. console.log('Using GPU', gpu);
  85. console.log('Using timeout', timeout);
  86. const mySeed = process.env.SEED;
  87. const totalDiff = BigInt('115792089237277217110272752943501742914102634520085823245724998868298727686144');
  88. let bestGiver = { address: '', coins: 0 };
  89. function updateBestGivers(liteClient, myAddress) {
  90. return __awaiter(this, void 0, void 0, function* () {
  91. const whitelistGivers = allowShards ? [...givers] : givers.filter((giver) => {
  92. const shardMaxDepth = 1;
  93. const giverAddress = core_1.Address.parse(giver.address);
  94. const myShard = new core_1.BitReader(new core_1.BitString(myAddress.hash, 0, 1024)).loadUint(shardMaxDepth);
  95. const giverShard = new core_1.BitReader(new core_1.BitString(giverAddress.hash, 0, 1024)).loadUint(shardMaxDepth);
  96. if (myShard === giverShard) {
  97. return true;
  98. }
  99. return false;
  100. });
  101. console.log('Whitelist: ', whitelistGivers.length);
  102. if (liteClient instanceof ton_1.TonClient4) {
  103. const lastInfo = yield CallForSuccess(() => liteClient.getLastBlock());
  104. let newBestGiber = { address: '', coins: 0 };
  105. yield Promise.all(whitelistGivers.map((giver) => __awaiter(this, void 0, void 0, function* () {
  106. const stack = yield CallForSuccess(() => liteClient.runMethod(lastInfo.last.seqno, core_1.Address.parse(giver.address), 'get_pow_params', []));
  107. // const powStack = Cell.fromBase64(powInfo.result as string)
  108. // const stack = parseTuple(powStack)
  109. const reader = new core_1.TupleReader(stack.result);
  110. const seed = reader.readBigNumber();
  111. const complexity = reader.readBigNumber();
  112. const iterations = reader.readBigNumber();
  113. const hashes = totalDiff / complexity;
  114. const coinsPerHash = giver.reward / Number(hashes);
  115. if (coinsPerHash > newBestGiber.coins) {
  116. newBestGiber = { address: giver.address, coins: coinsPerHash };
  117. }
  118. })));
  119. bestGiver = newBestGiber;
  120. }
  121. else if (liteClient instanceof ton_lite_client_1.LiteClient) {
  122. const lastInfo = yield liteClient.getMasterchainInfo();
  123. let newBestGiber = { address: '', coins: 0 };
  124. yield Promise.all(whitelistGivers.map((giver) => __awaiter(this, void 0, void 0, function* () {
  125. const powInfo = yield liteClient.runMethod(core_1.Address.parse(giver.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. const hashes = totalDiff / complexity;
  133. const coinsPerHash = giver.reward / Number(hashes);
  134. if (coinsPerHash > newBestGiber.coins) {
  135. newBestGiber = { address: giver.address, coins: coinsPerHash };
  136. }
  137. })));
  138. bestGiver = newBestGiber;
  139. }
  140. });
  141. }
  142. function getNextMaster(liteClient) {
  143. return __awaiter(this, void 0, void 0, function* () {
  144. if (liteClient instanceof ton_lite_client_1.LiteClient) {
  145. const info = yield liteClient.getMasterchainInfo();
  146. const nextInfo = yield liteClient.getMasterchainInfo({ awaitSeqno: info.last.seqno + 1 });
  147. return nextInfo.last;
  148. }
  149. else {
  150. const info = yield liteClient.getLastBlock();
  151. while (true) {
  152. try {
  153. const nextInfo = yield liteClient.getBlock(info.last.seqno + 1);
  154. return nextInfo.shards.find(s => s.workchain === -1);
  155. }
  156. catch (e) {
  157. //
  158. }
  159. }
  160. // const nextInfo = await liteClient.getBlock(info.last.seqno + 1)
  161. // return info.last.seqno + 1
  162. }
  163. });
  164. }
  165. function getPowInfo(liteClient, address, lastInfoRoot) {
  166. return __awaiter(this, void 0, void 0, function* () {
  167. // console.log('getPowInfo', address, lastInfoRoot)
  168. if (liteClient instanceof ton_1.TonClient4) {
  169. const lastInfo = lastInfoRoot !== null && lastInfoRoot !== void 0 ? lastInfoRoot : (yield CallForSuccess(() => liteClient.getLastBlock())).last;
  170. const powInfo = yield CallForSuccess(() => liteClient.runMethod(lastInfo.seqno, address, 'get_pow_params', []));
  171. const reader = new core_1.TupleReader(powInfo.result);
  172. const seed = reader.readBigNumber();
  173. const complexity = reader.readBigNumber();
  174. const iterations = reader.readBigNumber();
  175. return [seed, complexity, iterations];
  176. }
  177. else if (liteClient instanceof ton_lite_client_1.LiteClient) {
  178. // console.log('lastInfoRoot', lastInfoRoot)
  179. const lastInfo = lastInfoRoot !== null && lastInfoRoot !== void 0 ? lastInfoRoot : (yield liteClient.getMasterchainInfo()).last;
  180. const powInfo = yield liteClient.runMethod(address, 'get_pow_params', Buffer.from([]), lastInfo, { awaitSeqno: lastInfo.seqno, timeout: 100 });
  181. const powStack = core_1.Cell.fromBase64(powInfo.result);
  182. const stack = (0, core_1.parseTuple)(powStack);
  183. const reader = new core_1.TupleReader(stack);
  184. const seed = reader.readBigNumber();
  185. const complexity = reader.readBigNumber();
  186. const iterations = reader.readBigNumber();
  187. return [seed, complexity, iterations];
  188. }
  189. throw new Error('invalid client');
  190. });
  191. }
  192. let go = true;
  193. let i = 0;
  194. function main() {
  195. var _a;
  196. return __awaiter(this, void 0, void 0, function* () {
  197. let liteClient;
  198. if (!args['--api']) {
  199. console.log('Using TonHub API');
  200. liteClient = yield (0, client_1.getTon4Client)();
  201. }
  202. else {
  203. if (args['--api'] === 'lite') {
  204. console.log('Using LiteServer API');
  205. liteClient = yield (0, client_1.getLiteClient)((_a = args['-c']) !== null && _a !== void 0 ? _a : 'https://ton-blockchain.github.io/global.config.json');
  206. }
  207. else {
  208. console.log('Using TonHub API');
  209. liteClient = yield (0, client_1.getTon4Client)();
  210. }
  211. }
  212. const keyPair = yield (0, crypto_1.mnemonicToWalletKey)(mySeed.split(' '));
  213. const wallet = ton_2.WalletContractV4.create({
  214. workchain: 0,
  215. publicKey: keyPair.publicKey
  216. });
  217. const walletv3r2 = ton_1.WalletContractV3R2.create({
  218. workchain: 0,
  219. publicKey: keyPair.publicKey
  220. });
  221. if (args['--wallet'] === 'highload') {
  222. console.log('Using highload wallet', wallet.address.toString({ bounceable: false, urlSafe: true }));
  223. }
  224. else {
  225. console.log('Using v4r2 wallet', wallet.address.toString({ bounceable: false, urlSafe: true }));
  226. }
  227. const opened = liteClient.open(wallet);
  228. yield updateBestGivers(liteClient, wallet.address);
  229. setInterval(() => {
  230. updateBestGivers(liteClient, wallet.address);
  231. }, 1000);
  232. while (go) {
  233. // console.log('waiting master')
  234. const nextMaster = yield getNextMaster(liteClient);
  235. console.log('got next master');
  236. const giverAddress = bestGiver.address;
  237. const [seed, complexity, iterations] = yield getPowInfo(liteClient, core_1.Address.parse(giverAddress), nextMaster);
  238. console.log('got giver address', giverAddress);
  239. const randomName = (yield (0, crypto_1.getSecureRandomBytes)(8)).toString('hex') + '.boc';
  240. const path = `bocs/${randomName}`;
  241. const command = `${bin} -g ${gpu} -F 128 -t ${timeout} ${wallet.address.toString({ urlSafe: true, bounceable: true })} ${seed} ${complexity} ${iterations} ${giverAddress} ${path}`;
  242. try {
  243. const output = (0, child_process_1.execSync)(command, { encoding: 'utf-8', stdio: "pipe" }); // the default is 'buffer'
  244. }
  245. catch (e) {
  246. }
  247. let mined = undefined;
  248. try {
  249. mined = fs_1.default.readFileSync(path);
  250. fs_1.default.rmSync(path);
  251. }
  252. catch (e) {
  253. //
  254. }
  255. if (!mined) {
  256. console.log(`${new Date()}: not mined`, seed, i++);
  257. }
  258. if (mined) {
  259. // const [newSeed] = await getPowInfo(liteClient, Address.parse(giverAddress))
  260. // if (newSeed !== seed) {
  261. // console.log('Mined already too late seed')
  262. // continue
  263. // }
  264. console.log(`${new Date()}: mined`, seed, i++);
  265. let w = opened;
  266. let seqno = 0;
  267. try {
  268. seqno = yield CallForSuccess(() => w.getSeqno());
  269. }
  270. catch (e) {
  271. //
  272. }
  273. sendMinedBoc(wallet, seqno, keyPair, giverAddress, core_1.Cell.fromBoc(mined)[0].asSlice().loadRef());
  274. // let seqnov3 = 0
  275. // try {
  276. // seqnov3 = await CallForSuccess(() => liteClient.open(walletv3r2).getSeqno())
  277. // } catch (e) {
  278. // //
  279. // }
  280. // sendMinedBoc(walletv3r2, seqnov3, keyPair, giverAddress, Cell.fromBoc(mined as Buffer)[0].asSlice().loadRef())
  281. // for (let j = 0; j < 5; j++) {
  282. // try {
  283. // await CallForSuccess(() => {
  284. // return w.sendTransfer({
  285. // seqno,
  286. // secretKey: keyPair.secretKey,
  287. // messages: [internal({
  288. // to: giverAddress,
  289. // value: toNano('0.05'),
  290. // bounce: true,
  291. // body: Cell.fromBoc(mined as Buffer)[0].asSlice().loadRef(),
  292. // })],
  293. // sendMode: 3 as any,
  294. // })
  295. // })
  296. // break
  297. // } catch (e) {
  298. // if (j === 4) {
  299. // throw e
  300. // }
  301. // //
  302. // }
  303. // }
  304. }
  305. }
  306. });
  307. }
  308. main();
  309. function sendMinedBoc(wallet, seqno, keyPair, giverAddress, boc) {
  310. var _a;
  311. return __awaiter(this, void 0, void 0, function* () {
  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 ton4Client = yield (0, client_1.getTon4Client)();
  314. const tonOrbsClient = yield (0, client_1.getTon4ClientOrbs)();
  315. const toncenterClient = yield (0, client_1.getTonCenterClient)();
  316. const w1 = liteServerClient.open(wallet);
  317. const w2 = ton4Client.open(wallet);
  318. const w3 = tonOrbsClient.open(wallet);
  319. const w4 = toncenterClient.open(wallet);
  320. const wallets = [w1, w2, w3];
  321. // const transferBoc = w1.createTransfer({
  322. // seqno,
  323. // secretKey: keyPair.secretKey,
  324. // messages: [internal({
  325. // to: giverAddress,
  326. // value: toNano('0.05'),
  327. // bounce: true,
  328. // body: boc,
  329. // })],
  330. // sendMode: 3 as any,
  331. // })
  332. // console.log('send seqno', seqno)
  333. // const ext = external({
  334. // to: Address.parse(giverAddress),
  335. // body: transferBoc
  336. // })
  337. // const dataBoc = beginCell().store(storeMessage(ext)).endCell()
  338. // toncenterClient.sendFile(dataBoc.toBoc()).then(() => {
  339. // console.log('toncenter success')
  340. // }).catch(e => {
  341. // //
  342. // console.log('toncenter send error', e)
  343. // })
  344. // w4.sendTransfer({
  345. // seqno,
  346. // secretKey: keyPair.secretKey,
  347. // messages: [internal({
  348. // to: giverAddress,
  349. // value: toNano('0.05'),
  350. // bounce: true,
  351. // body: boc,
  352. // })],
  353. // sendMode: 3 as any,
  354. // })
  355. for (let i = 0; i < 3; i++) {
  356. for (const w of wallets) {
  357. w.sendTransfer({
  358. seqno,
  359. secretKey: keyPair.secretKey,
  360. messages: [(0, core_1.internal)({
  361. to: giverAddress,
  362. value: (0, core_1.toNano)('0.05'),
  363. bounce: true,
  364. body: boc,
  365. })],
  366. sendMode: 3,
  367. }).catch(e => {
  368. //
  369. });
  370. }
  371. }
  372. });
  373. }
  374. // Function to call ton api untill we get response.
  375. // Because testnet is pretty unstable we need to make sure response is final
  376. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  377. function CallForSuccess(toCall, attempts = 20, delayMs = 100) {
  378. return __awaiter(this, void 0, void 0, function* () {
  379. if (typeof toCall !== 'function') {
  380. throw new Error('unknown input');
  381. }
  382. let i = 0;
  383. let lastError;
  384. while (i < attempts) {
  385. try {
  386. const res = yield toCall();
  387. return res;
  388. }
  389. catch (err) {
  390. lastError = err;
  391. i++;
  392. yield delay(delayMs);
  393. }
  394. }
  395. console.log('error after attempts', i);
  396. throw lastError;
  397. });
  398. }
  399. exports.CallForSuccess = CallForSuccess;
  400. function delay(ms) {
  401. return new Promise((resolve) => {
  402. setTimeout(resolve, ms);
  403. });
  404. }
  405. exports.delay = delay;