Guest User

Untitled

a guest
Oct 29th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.50 KB | None | 0 0
  1. var mysql = require('mysql');
  2. var log4js = require('log4js');
  3. var io = require('socket.io')(8000);
  4. var request = require('request');
  5. var fs = require('fs');
  6. var md5 = require('md5');
  7. var sha256 = require('sha256');
  8. var math = require('mathjs');
  9. var crashNumber = 100;
  10. var crashState = 'NULL';
  11. var crashAt;
  12. var timp = 700;
  13. var intervalul;
  14. var isStatedSet = 0;
  15. var rCAt;
  16. var instaCrash = 0;
  17. var HaShGame;
  18. var timerC1;
  19. var timerC2;
  20. var timerC3;
  21. var timerC4;
  22. var timerC5;
  23. var timerC6;
  24. var timerC7;
  25. var timerC8;
  26. var timerC9;
  27. var timerC10;
  28. var timerC11;
  29. var timerC12;
  30. var CRbr = 1;
  31. var usersCr = {};
  32. var CRusersAmount = {};
  33. var CRcurrentBets = [];
  34.  
  35.  
  36. log4js.configure({
  37. appenders: {
  38. console: { type: 'console' },
  39. file: { type: 'file', filename: 'logs/site.log' }
  40. },
  41. categories: { default: { appenders: ['file','console' ], level: 'debug' }
  42. }});
  43. var logger = log4js.getLogger();
  44.  
  45. var pool = mysql.createPool({
  46. connectionLimit : 10,
  47. database: 'roulette',
  48. host: 'localhost',
  49. user: 'root',
  50. password: 'jemoeder123'
  51. });
  52.  
  53. process.on('uncaughtException', function (err) {
  54. logger.trace('Strange error');
  55. logger.debug(err);
  56. });
  57.  
  58. /* */
  59. var accept = 30;
  60. var wait = 10;
  61. var br = 3;
  62. var chat = 2;
  63. var chatb = 200000;
  64. var maxbet = 10000000;
  65. var minbet = 100;
  66. var q1 = 2;
  67. var q2 = 14;
  68. var timer = -1;
  69. var users = {};
  70. var roll = 0;
  71. var currentBets = [];
  72. var historyRolls = [];
  73. var usersBr = {};
  74. var usersAmount = {};
  75. var currentSums = {
  76. '0-0': 0,
  77. '1-7': 0,
  78. '8-14': 0
  79. };
  80.  
  81. var canPlayersBet = 1;
  82.  
  83. var currentRollid = 0;
  84. var pause = false;
  85. var hash = '';
  86. var last_message = {};
  87. /* */
  88.  
  89. load();
  90. startCrashGame();
  91.  
  92. var prices;
  93. request('http://backpack.tf/api/IGetMarketPrices/v1/?key=59eb9bdbcf6c75077328834b&appid=730', function(error, response, body) {
  94. prices = JSON.parse(body);
  95. if(prices.response.success == 0) {
  96. logger.warn('It was not possible to load prices. Prices taken from the cache');
  97. if(fs.existsSync(__dirname + '/prices.txt')){
  98. prices = JSON.parse(fs.readFileSync(__dirname + '/var/www/prices.txt'));
  99. logger.warn('Prices have been retrieved from the cache');
  100. } else {
  101. logger.error('No prices in cache');
  102. process.exit(0);
  103. }
  104. if(fs.existsSync(__dirname + '/var/www/prices.txt')){
  105. prices = JSON.parse(fs.readFileSync(__dirname + '/var/www/prices.txt'));
  106. logger.warn('/var/www/prices.txt Loaded cached');
  107. } else {
  108. logger.error('No /var/www/prices.txt in cache');
  109. process.exit(0);
  110. }
  111. } else {
  112. fs.writeFileSync('/var/www/prices.txt', body);
  113. logger.trace('Prices loaded successfully');
  114. }
  115. });
  116.  
  117. updateHash();
  118. function updateHash() {
  119. query('SELECT * FROM `hash` ORDER BY `id` DESC LIMIT 1', function(err, row) {
  120. if(err) {
  121. logger.error('Cant get the hash, stopping');
  122. logger.debug(err);
  123. process.exit(0);
  124. return;
  125. }
  126. if(row.length == 0) {
  127. logger.error('Wrong hash found, stopping');
  128. process.exit(0);
  129. } else {
  130. if(hash != row[0].hash) logger.warn('Loaded hash'+row[0].hash);
  131. hash = row[0].hash;
  132. }
  133. });
  134. }
  135.  
  136. io.on('connection', function(socket) {
  137. var user = false;
  138. socket.on('hash', function(hash) {
  139. query('SELECT * FROM `users` WHERE `hash` = '+pool.escape(hash), function(err, row) {
  140. if((err) || (!row.length)) return socket.disconnect();
  141. user = row[0];
  142. socket.join(user.steamid);
  143. socket.join(user.steamid);
  144. users[user.steamid] = {
  145. socket: socket.id,
  146. balance: parseInt(row[0].balance)
  147. }
  148. socket.emit('message', {
  149. accept: accept,
  150. balance: row[0].balance,
  151. br: br,
  152. chat: chat,
  153. chatb: chatb,
  154. count: timer-wait,
  155. icon: row[0].avatar,
  156. maxbet: maxbet,
  157. minbet: minbet,
  158. name: row[0].name,
  159. rank: row[0].rank,
  160. rolls: historyRolls,
  161. type: 'hello',
  162. user: row[0].steamid
  163. });
  164. socket.emit('message', {
  165. type: 'logins',
  166. count: Object.size(io.sockets.connected)
  167. });
  168. currentBets.forEach(function(itm) {
  169. socket.emit('message', {
  170. type: 'bet',
  171. bet: {
  172. amount: itm.amount,
  173. betid: itm.betid,
  174. icon: itm.icon,
  175. lower: itm.lower,
  176. name: itm.name,
  177. rollid: itm.rollid,
  178. upper: itm.upper,
  179. user: itm.user,
  180. won: null
  181. },
  182. sums: {
  183. 0: currentSums['0-0'],
  184. 1: currentSums['1-7'],
  185. 2: currentSums['8-14'],
  186. }
  187. });
  188. });
  189. });
  190. });
  191. CRcurrentBets.forEach(function(itm) {
  192. socket.emit('message', {
  193. type: 'crbet',
  194. bet: {
  195. autoCashout: itm.autoCash,
  196. amount: itm.amount,
  197. betid: itm.betid,
  198. icon: itm.icon,
  199. name: itm.name,
  200. user: itm.user,
  201. won: '0'
  202. }
  203. });
  204. });
  205. socket.on('mes', function(m) {
  206. if(!user) return;
  207. logger.debug(m);
  208. if(m.type == "bet") return setBet(m, user, socket);
  209. if(m.type == "crbet") {
  210. if(m.mtype == 'joinCrash') {
  211. return setTimeout(CRsetBet(m, user, socket), 250);
  212. }else if(m.mtype == 'withdraw') {
  213. return CrashCashout(m, user, socket);
  214. }
  215. }
  216. if(m.type == "balance") return getBalance(user, socket);
  217. if(m.type == "chat") return ch(m, user, socket);
  218. });
  219. socket.on('disconnect', function() {
  220. io.sockets.emit('message', {
  221. type: 'logins',
  222. count: Object.size(io.sockets.connected)
  223. });
  224. delete users[user.steamid];
  225. socket.leave(user.steamid);
  226. })
  227. });
  228.  
  229. function ch(m, user, socket) {
  230. if(m.msg) {
  231. var res = null;
  232. if (res = /^\/send ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  233. logger.trace('problem with translating from russian'+res[2]+' user '+res[1]);
  234. query('SELECT `balance` FROM `users` WHERE `steamid` = '+pool.escape(user.steamid), function(err, row) {
  235. if((err) || (!row.length)) {
  236. logger.error('Could not find user to send the coins');
  237. logger.debug(err);
  238. socket.emit('message', {
  239. type: 'error',
  240. enable: false,
  241. error: 'Error: You are not DB.'
  242. });
  243. return;
  244. }
  245. if(row[0].balance < res[2]) {
  246. socket.emit('message', {
  247. type: 'error',
  248. enable: false,
  249. error: 'Error: Insufficient funds.'
  250. });
  251. } else if(res[2] <= 0) {
  252. socket.emit('message', {
  253. type: 'error',
  254. enable: false,
  255. error: 'Error: Amount must be greater than 0.'
  256. });
  257. } else {
  258. query('SELECT `name` FROM `users` WHERE `steamid` = '+pool.escape(res[1]), function(err2, row2) {
  259. if((err) || (!row.length)) {
  260. logger.error('Could not get people to move');
  261. logger.debug(err);
  262. socket.emit('message', {
  263. type: 'error',
  264. enable: false,
  265. error: 'Error: Unknown receiver.'
  266. });
  267. return;
  268. }
  269. query('UPDATE `users` SET `balance` = `balance` - '+res[2]+' WHERE `steamid` = '+pool.escape(user.steamid));
  270. query('UPDATE `users` SET `balance` = `balance` + '+res[2]+' WHERE `steamid` = '+pool.escape(res[1]));
  271. query('INSERT INTO `transfers` SET `from1` = '+pool.escape(user.steamid)+', `to1` = '+pool.escape(res[1])+', `amount` = '+pool.escape(res[2])+', `time` = '+pool.escape(time()));
  272. socket.emit('message', {
  273. type: 'alert',
  274. alert: 'You sent '+res[2]+' coins to '+row2[0].name+'.'
  275. });
  276. getBalance(user, socket);
  277. });
  278. }
  279. });
  280. }else {
  281. query('SELECT SUM(`amount`) AS castor FROM `bets` WHERE `user` = '+pool.escape(user.steamid), function(err, row) {
  282. if((err) || (!row.length)) {
  283. logger.error('Failed to get the person to transfer');
  284. logger.debug(err);
  285. socket.emit('message', {
  286. type: 'error',
  287. enable: false,
  288. error: 'Error: Unknown receiver.'
  289. });
  290. return;
  291. }
  292. if(row[0].castor <= chatb) {
  293. socket.emit('message', {
  294. type: 'error',
  295. enable: false,
  296. error: 'Chat unlocks after 200,000 coins have been played. You need: '+pool.escape(row[0].castor-chatb + ' coins')
  297. });
  298. } else if (res = /^\/mute ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  299. if(user.rank > 0) {
  300. var t = time();
  301. query('UPDATE `users` SET `mute` = '+pool.escape(parseInt(t)+parseInt(res[2]))+' WHERE `steamid` = '+pool.escape(res[1]));
  302. socket.emit('message', {
  303. type: 'alert',
  304. alert: 'You muted '+res[1]+' to '+res[2]
  305. });
  306. }
  307. } else {
  308. query('SELECT `mute` FROM `users` WHERE `steamid` = '+pool.escape(user.steamid), function(err, row) {
  309. if(err) return;
  310. if(row[0].mute > time()) {
  311. socket.emit('message', {
  312. type: 'alert',
  313. alert: 'You are muted '+(row[0].mute-time() + ' more seconds')
  314. });
  315. return;
  316. } else if (res = /^\/ban ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  317. if(user.rank == 1) {
  318. var t = time();
  319. query('UPDATE `users` SET `ban` = 1 WHERE `steamid` = '+pool.escape(res[1]));
  320. socket.emit('message', {
  321. type: 'alert',
  322. alert: 'You ban '+res[1]+' '+res[2]
  323. });
  324. return;
  325. }
  326. }
  327. else if (res = /^\/unban ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  328. if(user.rank == 1) {
  329. var t = time();
  330. query('UPDATE `users` SET `ban` = 0 WHERE `steamid` = '+pool.escape(res[1]));
  331. socket.emit('message', {
  332. type: 'alert',
  333. alert: 'You unban '+res[1]+' '+res[2]
  334. });
  335. return;
  336. }
  337. }
  338. else if (res = /^\/banwithdraw ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  339. if(user.rank == 1) {
  340. var t = time();
  341. query('UPDATE `users` SET `banwithdraw` = 1 WHERE `steamid` = '+pool.escape(res[1]));
  342. socket.emit('message', {
  343. type: 'alert',
  344. alert: 'You ban '+(res[1]+' '+res[2] + ' to withdraw')
  345. });
  346. return;
  347. }
  348. }
  349. else if (res = /^\/unbanwithdraw ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  350. if(user.rank == 1) {
  351. var t = time();
  352. query('UPDATE `users` SET `banwithdraw` = 0 WHERE `steamid` = '+pool.escape(res[1]));
  353. socket.emit('message', {
  354. type: 'alert',
  355. alert: 'You unban '+(res[1]+' '+res[2] + ' to withdraw')
  356. });
  357. return;
  358. }
  359. }
  360. else if (res = /^\/setbalance ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  361. if(user.rank == 1) {
  362. var t = time();
  363. query('UPDATE `users` SET `balance` = '+res[2]+' WHERE `steamid` = '+pool.escape(res[1]));
  364. socket.emit('message', {
  365. type: 'alert',
  366. alert: 'You set '+res[1]+' balance to '+res[2]
  367. });
  368. return;
  369. }
  370. }
  371. else if (res = /^\/setrank ([0-9]*) ([0-9]*)/.exec(m.msg)) {
  372. if(user.rank == 1) {
  373. var t = time();
  374. query('UPDATE `users` SET `rank` = '+res[2]+' WHERE `steamid` = '+pool.escape(res[1]));
  375. socket.emit('message', {
  376. type: 'alert',
  377. alert: 'You set '+res[1]+' rank to '+res[2]
  378. });
  379. return;
  380. }
  381. }
  382. else if (res = /^\/ranks ([0-9]*)/.exec(m.msg)) {
  383. if(user.rank == 1) {
  384. var t = time();
  385. socket.emit('message', {
  386. type: 'alert',
  387. alert: '\n1- Admin \n2- Mod \n3- Twitch \n4- V.I.P \n5- Developer \n6- YouTube \n7- Support'
  388. });
  389. return;
  390. }
  391. }
  392. io.sockets.emit('message', {
  393. type: 'chat',
  394. msg: safe_tags_replace(m.msg),
  395. name: user.name,
  396. icon: user.avatar,
  397. user: user.steamid,
  398. rank: user.rank,
  399. lang: m.lang,
  400. hide: m.hide
  401. });
  402. });
  403. }
  404. });
  405. }
  406. }
  407. }
  408.  
  409. function getBalance(user, socket) {
  410. query('SELECT `balance` FROM `users` WHERE `steamid` = '+pool.escape(user.steamid), function(err, row) {
  411. if((err) || (!row.length)) {
  412. logger.error('Could not get a person into balance');
  413. logger.debug(err);
  414. socket.emit('message', {
  415. type: 'error',
  416. enable: true,
  417. error: 'Error: You are not DB.'
  418. });
  419. return;
  420. }
  421. socket.emit('message', {
  422. type: 'balance',
  423. balance: row[0].balance
  424. });
  425. if(user.steamid) users[user.steamid].balance = parseInt(row[0].balance);
  426. })
  427. }
  428.  
  429. function setBet(m, user, socket) {
  430. if((usersBr[user.steamid] !== undefined) && (usersBr[user.steamid] == br)) {
  431. socket.emit('message', {
  432. type: 'error',
  433. enable: true,
  434. error: 'You\'ve already placed '+usersBr[user.steamid]+'/'+br+' bets this roll.'
  435. });
  436. return;
  437. }
  438. if((m.amount < minbet) || (m.amount > maxbet)) {
  439. socket.emit('message', {
  440. type: 'error',
  441. enable: true,
  442. error: 'Min. bet: 100 coin!'
  443. });
  444. return;
  445. }
  446. if(pause) {
  447. socket.emit('message', {
  448. type: 'error',
  449. enable: false,
  450. error: 'Betting for this round is closed.'
  451. });
  452. return;
  453. }
  454. if(m.upper - m.lower > 6){
  455. logger.warn("User tried to place an invalid bid!! (Might be hacking)");
  456. socket.emit('message', {
  457. type: 'error',
  458. enable: true,
  459. error: 'Don\'t cheat!'
  460. });
  461. return;
  462. } else {
  463. if(m.lower != 0 && m.lower != 1 && m.lower != 8){
  464. logger.warn("User is trying some weird offset!! (Might be hacking)");
  465. logger.warn("User tried to place an invalid bid!! (Might be hacking)");
  466. socket.emit('message', {
  467. type: 'error',
  468. enable: true,
  469. error: 'Invalid bet boundaries. Don\'t cheat!'
  470. });
  471. return;
  472. }
  473. if(m.lower == 0){
  474. m.upper = 0;
  475. } else {
  476. m.upper = m.lower + 6;
  477. }
  478. }
  479. var isnum = /^\d+$/.test(m.amount);
  480. if(!isnum){
  481. socket.emit('message', {
  482. type: 'error',
  483. enable: true,
  484. error: 'Invalid bet'
  485. });
  486. return;
  487. }
  488. var start_time = new Date();
  489. query('SELECT `balance` FROM `users` WHERE `steamid` = '+pool.escape(user.steamid), function(err, row) {
  490. if((err) || (!row.length)) {
  491. logger.error('Could not get people to rate');
  492. logger.debug(err);
  493. socket.emit('message', {
  494. type: 'error',
  495. enable: true,
  496. error: 'You are not DB!'
  497. });
  498. return;
  499. }
  500. if(row[0].balance >= m.amount) {
  501. query('UPDATE `users` SET `balance` = `balance` - '+parseInt(m.amount)+' WHERE `steamid` = '+pool.escape(user.steamid), function(err2, row2) {
  502. if(err2) {
  503. logger.error('There is not enough points.');
  504. logger.debug(err);
  505. socket.emit('message', {
  506. type: 'error',
  507. enable: true,
  508. error: 'You dont have enough points!'
  509. });
  510. return;
  511. }
  512. query('INSERT INTO `bets` SET `user` = '+pool.escape(user.steamid)+', `amount` = '+pool.escape(m.amount)+', `lower` = '+pool.escape(m.lower)+', `upper` = '+pool.escape(m.upper), function(err3, row3) {
  513. if(err3) {
  514. logger.error('Add error rate in the database');
  515. logger.debug(err);
  516. return;
  517. }
  518. var end = new Date();
  519. if(usersBr[user.steamid] === undefined) {
  520. usersBr[user.steamid] = 1;
  521. } else {
  522. usersBr[user.steamid]++;
  523. }
  524. if(usersAmount[user.steamid] === undefined) {
  525. usersAmount[user.steamid] = {
  526. '0-0': 0,
  527. '1-7': 0,
  528. '8-14': 0
  529. };
  530. }
  531. usersAmount[user.steamid][m.lower+'-'+m.upper] += parseInt(m.amount);
  532. currentSums[m.lower+'-'+m.upper] += m.amount;
  533. socket.emit('message', {
  534. type: 'betconfirm',
  535. bet: {
  536. betid: row3.insertId,
  537. lower: m.lower,
  538. upper: m.upper,
  539. amount: usersAmount[user.steamid][m.lower+'-'+m.upper]
  540. },
  541. balance: row[0].balance-m.amount,
  542. mybr: usersBr[user.steamid],
  543. br: br,
  544. exec: (end.getTime()-start_time.getTime()).toFixed(3)
  545. });
  546. users[user.steamid].balance = row[0].balance-m.amount;
  547. io.sockets.emit('message', {
  548. type: 'bet',
  549. bet: {
  550. amount: usersAmount[user.steamid][m.lower+'-'+m.upper],
  551. betid: row3.insertId,
  552. icon: user.avatar,
  553. lower: m.lower,
  554. name: user.name,
  555. rollid: currentRollid,
  556. upper: m.upper,
  557. user: user.steamid,
  558. won: null
  559. },
  560. sums: {
  561. 0: currentSums['0-0'],
  562. 1: currentSums['1-7'],
  563. 2: currentSums['8-14'],
  564. }
  565. });
  566. currentBets.push({
  567. amount: m.amount,
  568. betid: row3.insertId,
  569. icon: user.avatar,
  570. lower: m.lower,
  571. name: user.name,
  572. rollid: currentRollid,
  573. upper: m.upper,
  574. user: user.steamid,
  575. });
  576. logger.debug('I bet #'+row3.insertId+' amount '+m.amount);
  577. checkTimer();
  578. })
  579. });
  580. } else {
  581. socket.emit('message', {
  582. type: 'error',
  583. enable: true,
  584. error: 'You dont any money!'
  585. });
  586. }
  587. });
  588. }
  589.  
  590. function checkTimer() {
  591. if((currentBets.length > 0) && (timer == -1) && (!pause)) {
  592. logger.trace('Starts timer');
  593. timer = accept+wait;
  594. timerID = setInterval(function() {
  595. logger.trace('Timer: '+timer+' Site timer: '+(timer-wait));
  596. if (timer == wait) {
  597. pause = true;
  598. logger.trace('Pause is on');
  599. var inprog = getRandomInt(0, (currentBets.length/4).toFixed(0));
  600. io.sockets.emit('message', {
  601. type: 'preroll',
  602. totalbets: currentBets.length-inprog,
  603. inprog: inprog,
  604. sums: {
  605. 0: currentSums['0-0'],
  606. 1: currentSums['1-7'],
  607. 2: currentSums['8-14'],
  608. }
  609. });
  610. }
  611. if (timer == wait-2) {
  612. logger.trace('load timer');
  613. toWin(); // Choosing the winner
  614. }
  615. if(timer == 0) {
  616. logger.trace('Reset Tipo');
  617. timer = accept+wait;
  618. currentBets = [];
  619. historyRolls.push({id: currentRollid, roll: roll});
  620. if(historyRolls.length > 10) historyRolls.slice(1);
  621. usersBr = {}; // how many users have
  622. usersAmount = {}; // how many users have coins
  623. currentSums = {
  624. '0-0': 0,
  625. '1-7': 0,
  626. '8-14': 0
  627. };
  628. currentRollid = currentRollid+1;
  629. pause = false;
  630. }
  631. timer--;
  632. }, 1000);
  633. }
  634. }
  635.  
  636. function toWin() {
  637. var sh = sha256(hash+'-'+currentRollid);
  638. roll = sh.substr(0, 8);
  639. roll = parseInt(roll, 16);
  640. roll = math.abs(roll) % 15;
  641. logger.trace('Tipo dropped '+roll);
  642. var r = '';
  643. var s = q1;
  644. var wins = {
  645. '0-0': 0,
  646. '1-7': 0,
  647. '8-14': 0
  648. }
  649. if(roll == 0) { r = '0-0'; s = q2; wins['0-0'] = currentSums['0-0']*s; }
  650. if((roll > 0) && (roll < 8)) { r = '1-7'; wins['1-7'] = currentSums['1-7']*s; }
  651. if((roll > 7) && (roll < 15)) { r = '8-14'; wins['8-14'] = currentSums['8-14']*s; }
  652. logger.debug(currentBets);
  653. logger.debug(usersBr);
  654. logger.debug(usersAmount);
  655. logger.debug(currentSums);
  656. for(key in users) {
  657. if(usersAmount[key] === undefined) {
  658. var balance = null;
  659. var won = 0;
  660. } else {
  661. var balance = parseInt(users[key].balance)+usersAmount[key][r]*s;
  662. var won = usersAmount[key][r]*s;
  663. }
  664. if (io.sockets.connected[users[key].socket]) io.sockets.connected[users[key].socket].emit('message', {
  665. balance: balance,
  666. count: accept,
  667. nets: [{
  668. lower: 0,
  669. samount: currentSums['0-0'],
  670. swon: wins['0-0'],
  671. upper: 0
  672. }, {
  673. lower: 1,
  674. samount: currentSums['1-7'],
  675. swon: wins['1-7'],
  676. upper: 7
  677. }, {
  678. lower: 8,
  679. samount: currentSums['8-14'],
  680. swon: wins['8-14'],
  681. upper: 14
  682. }
  683. ],
  684. roll: roll,
  685. rollid: currentRollid+1,
  686. type: "roll",
  687. wait: wait-2,
  688. wobble: getRandomArbitary(0, 1),
  689. won: won
  690. });
  691. }
  692. currentBets.forEach(function(itm) {
  693. if((roll >= itm.lower) && (roll <= itm.upper)) {
  694. logger.debug('Rate #'+itm.betid+' sum '+itm.amount+' win '+(itm.amount*s));
  695. query('UPDATE `users` SET `balance` = `balance` + '+itm.amount*s+' WHERE `steamid` = '+pool.escape(itm.user));
  696. }
  697. });
  698. query('UPDATE `rolls` SET `roll` = '+pool.escape(roll)+', `hash` = '+pool.escape(hash)+', `time` = '+pool.escape(time())+' WHERE `id` = '+pool.escape(currentRollid));
  699. query('INSERT INTO `rolls` SET `roll` = -1');
  700. updateHash();
  701. }
  702.  
  703.  
  704.  
  705.  
  706.  
  707.  
  708.  
  709.  
  710.  
  711. /* */
  712. var tagsToReplace = {
  713. '&': '&amp;',
  714. '<': '&lt;',
  715. '>': '&gt;',
  716. 'script': '&nsbp;'
  717. };
  718.  
  719. function replaceTag(tag) {
  720. return tagsToReplace[tag] || tag;
  721. }
  722.  
  723. function safe_tags_replace(str) {
  724. return str.replace(/[&<>]/g, replaceTag);
  725. }
  726. Object.size = function(obj) {
  727. var size = 0,
  728. key;
  729. for (key in obj) {
  730. if (obj.hasOwnProperty(key)) size++;
  731. }
  732. return size;
  733. };
  734. function getRandomInt(min, max) {
  735. return Math.floor(Math.random() * (max - min + 1)) + min;
  736. }
  737. function getRandomArbitary(min, max) {
  738. return Math.random() * (max - min) + min;
  739. }
  740.  
  741. function query(sql, callback) {
  742. if (typeof callback === 'undefined') {
  743. callback = function() {};
  744. }
  745. pool.getConnection(function(err, connection) {
  746. if(err) return callback(err);
  747. logger.info('Id connection with database: '+connection.threadId);
  748. connection.query(sql, function(err, rows) {
  749. if(err) return callback(err);
  750. connection.release();
  751. return callback(null, rows);
  752. });
  753. });
  754. }
  755. function load() {
  756. query('SET NAMES utf8');
  757. query('SELECT `id` FROM `rolls` ORDER BY `id` DESC LIMIT 1', function(err, row) {
  758. if((err) || (!row.length)) {
  759. logger.error('you could not get the number last game');
  760. logger.debug(err);
  761. process.exit(0);
  762. return;
  763. }
  764. currentRollid = row[0].id;
  765. logger.trace('the current number of rolling'+currentRollid);
  766. });
  767. loadHistory();
  768. setTimeout(function() { io.listen(8080); }, 3000);
  769. }
  770. function loadHistory() {
  771. query('SELECT * FROM `rolls` ORDER BY `id` LIMIT 10', function(err, row) {
  772. if(err) {
  773. logger.error('Failed to load the list of establishments');
  774. logger.debug(err);
  775. process.exit(0);
  776. }
  777. logger.trace('loaded the history of plants');
  778. row.forEach(function(itm) {
  779. if(itm.roll != -1) historyRolls.push(itm);
  780. });
  781. });
  782. }
  783.  
  784. function time() {
  785. return parseInt(new Date().getTime()/1000)
  786. }
  787. function send100Crash() {
  788. io.sockets.emit('message', {
  789. type: 'urcarecrash',
  790. grafic: crashNumber
  791. });
  792. }
  793.  
  794. function CrashCashout(m, user, socket) {
  795. var crashPoint = crashNumber;
  796.  
  797. if(crashState != 'STARTED') {
  798. socket.emit('message', {
  799. type: 'error',
  800. error: 'The game is ended'
  801. })
  802. return;
  803. }
  804.  
  805. if(CRusersAmount[user.steamid]['cashedOut'] == '0') {
  806. var profit = parseInt(CRusersAmount[user.steamid]['amount']/2*(crashPoint)/100) - CRusersAmount[user.steamid]['amount']/2;
  807.  
  808. io.sockets.emit('message', {
  809. type: 'crashCashout',
  810. playerSTEAMID: user.steamid,
  811. playerNAME: user.name,
  812. playerAMOUNT: CRusersAmount[user.steamid]['amount'],
  813. playerCASHOUT: crashPoint,
  814. playerPROFIT: profit
  815. });
  816. CRusersAmount[user.steamid]['cashedOut'] = '1';
  817. CRusersAmount[user.steamid]['autoCashout'] = crashPoint/100;
  818. CRusersAmount[user.steamid]['profit'] = profit;
  819.  
  820. socket.emit('message', {
  821. type: 'changeBTNCrash',
  822. amount: CRusersAmount[user.steamid]['amount']/2+profit
  823. });
  824.  
  825. logger.debug('[CASHOUT] UPDATED BALANCE OF '+user.steamid+' WITH + '+profit+' [CASHOUT: '+crashPoint/100+'x]');
  826. query('UPDATE `users` SET `balance`=`balance`+'+parseInt(profit+CRusersAmount[user.steamid]['amount']/2)+' WHERE `steamid`='+pool.escape(user.steamid));
  827. query('UPDATE `crbets` SET `autoCashout`='+pool.escape(crashPoint)+', `cashedOut`=1 ORDER BY id DESC LIMIT 1');
  828. }else {
  829. socket.emit('message', {
  830. type: 'error',
  831. error: 'You have already cashed out!'
  832. });
  833. }
  834. }
  835.  
  836. function checkCashouts() {
  837. CRcurrentBets.forEach(function(itm) {
  838. if(itm.amount >= 1) {
  839.  
  840. if(CRusersAmount[itm.user]['cashedOut'] == '0') {
  841. var monii = itm.amount*(crashNumber/100);
  842.  
  843. io.sockets.in(itm.user).emit('message', {
  844. type: 'withdrawBTN',
  845. money: monii
  846. });
  847. }
  848.  
  849. }
  850.  
  851. if(itm.betid !== undefined && itm.autoCashout == crashNumber && itm.amount >= 1){
  852. if(CRusersAmount[itm.user]['cashedOut'] == '0') {
  853. var profit = parseInt(CRusersAmount[itm.user]['amount']/2*(itm.autoCashout)/100) - CRusersAmount[itm.user]['amount']/2;
  854.  
  855. io.sockets.emit('message', {
  856. type: 'crashCashout',
  857. playerBETID: itm.betid,
  858. playerSTEAMID: itm.user,
  859. playerNAME: itm.name,
  860. playerAMOUNT: itm.amount,
  861. playerCASHOUT: itm.autoCashout,
  862. playerPROFIT: profit
  863. });
  864.  
  865. CRusersAmount[itm.user]['cashedOut'] = '1';
  866. CRusersAmount[itm.user]['autoCashout'] = itm.autoCashout/100;
  867. CRusersAmount[itm.user]['profit'] = profit;
  868.  
  869. io.sockets.in(itm.user).emit('message', {
  870. type: 'changeBTNCrash',
  871. amount: CRusersAmount[itm.user]['amount']/2+profit
  872. });
  873.  
  874. logger.debug('[AUTO CASHOUT] UPDATED BALANCE OF '+itm.user+' WITH + '+profit+' [CASHOUT: '+itm.autoCashout/100+'x]');
  875. query('UPDATE `users` SET `balance`=`balance`+'+pool.escape(profit+CRusersAmount[itm.user]['amount']/2)+' WHERE `steamid`='+pool.escape(itm.user));
  876. query('UPDATE `crbets` SET `cashedOut`=1 WHERE `id`='+pool.escape(itm.betid));
  877. }
  878. }
  879. });
  880. }
  881.  
  882.  
  883. function reluareCrash() {
  884. if(crashNumber <= 100) {
  885. send100Crash();
  886. }
  887. setTimeout(function() {
  888. CRcurrentBets.forEach(function(itm) {
  889. logger.debug('[CRASH] BetID: #' + itm.betid + ' || User: ' + itm.user + ' || AutoCashout: ' + itm.autoCashout + ' || Suma: ' + itm.amount + ' || Won: ' + itm.won);
  890. });
  891.  
  892. io.sockets.emit('message', {
  893. type: 'crashed',
  894. crashmanule: rCAt
  895. });
  896.  
  897. CRcurrentBets = [];
  898. usersCr = {};
  899. CRusersAmount = {};
  900. crashState = 'ENDED';
  901. query('INSERT INTO `crash` SET `crashAt`='+pool.escape(rCAt)+',`hash`='+pool.escape(HaShGame));
  902.  
  903. setTimeout(function() {
  904. startCrashGame();
  905.  
  906. io.sockets.emit('message', {
  907. type: 'removeQCR'
  908. });
  909. }, 5000);
  910. }, 25);
  911. }
  912.  
  913. function getCrashAmount() {
  914. if(crashNumber == 120) {
  915. clearInterval(timerC1);
  916. startTimer(2);
  917. }else if(crashNumber == 165) {
  918. clearInterval(timerC2);
  919. startTimer(3);
  920. }else if(crashNumber == 203) {
  921. clearInterval(timerC3);
  922. startTimer(4);
  923. }else if(crashNumber == 310) {
  924. clearInterval(timerC4);
  925. startTimer(5);
  926. }else if(crashNumber == 560) {
  927. clearInterval(timerC5);
  928. startTimer(6);
  929. }else if(crashNumber == 800) {
  930. clearInterval(timerC6);
  931. startTimer(7);
  932. }else if(crashNumber == 1200) {
  933. clearInterval(timerC7);
  934. startTimer(8);
  935. }else if(crashNumber == 3566) {
  936. clearInterval(timerC8);
  937. startTimer(9);
  938. }else if(crashNumber == 7248) {
  939. clearInterval(timerC9);
  940. startTimer(10);
  941. }else if(crashNumber == 10258) {
  942. clearInterval(timerC10);
  943. startTimer(11);
  944. }else if(crashNumber == 49210) {
  945. clearInterval(timerC11);
  946. startTimer(12);
  947. }
  948. }
  949.  
  950. function CRsetBet(m, user, socket) {
  951. if(canPlayersBet == '1') {
  952. if((usersCr[user.steamid] !== undefined) && (usersCr[user.steamid] == CRbr)) {
  953. socket.emit('message', {
  954. type: 'error',
  955. enable: true,
  956. error: 'You have already joined the crash.'
  957. });
  958. return;
  959. }
  960. if((m.amount < minbet) || (m.amount > maxbet)) {
  961. socket.emit('message', {
  962. type: 'error',
  963. enable: true,
  964. error: 'Invalid bet amount ['+minbet+'-'+maxbet+'].'
  965. });
  966. return;
  967. }
  968. if(crashState != 'STARTING' && usersCr[user.steamid] != CRbr) {
  969. socket.emit('message', {
  970. type: 'error',
  971. enable: true,
  972. error: 'The game have been already started!'
  973. });
  974. return;
  975. }
  976.  
  977. var start_time = new Date();
  978. query('SELECT `balance` FROM `users` WHERE `steamid` = '+pool.escape(user.steamid), function(err, row) {
  979. if((err) || (!row.length)) {
  980. logger.error('Failed to find DB');
  981. logger.debug(err);
  982. socket.emit('message', {
  983. type: 'error',
  984. enable: true,
  985. error: 'You are not DB'
  986. });
  987. return;
  988. }
  989. if(row[0].balance >= m.amount) {
  990. query('UPDATE `users` SET `balance` = `balance` - '+parseInt(m.amount)+' WHERE `steamid` = '+pool.escape(user.steamid), function(err2, row2) {
  991. if(err2) {
  992. logger.error('Error in withdraw');
  993. logger.debug(err);
  994. socket.emit('message', {
  995. type: 'error',
  996. enable: true,
  997. error: 'You dont have enough points'
  998. });
  999. return;
  1000. }
  1001. query('INSERT INTO `crbets` SET `user` = '+pool.escape(user.steamid)+', `amount` = '+pool.escape(m.amount)+', `autoCashout` = '+pool.escape(m.autoCash), function(err3, row3) {
  1002. if(err3) {
  1003. logger.error('Error in DB');
  1004. logger.debug(err);
  1005. return;
  1006. }
  1007. var end = new Date();
  1008. if(usersCr[user.steamid] === undefined) {
  1009. usersCr[user.steamid] = 1;
  1010. }
  1011. if(CRusersAmount[user.steamid] === undefined) {
  1012. CRusersAmount[user.steamid] = {
  1013. 'amount': m.amount,
  1014. 'autoCashout': m.autoCash,
  1015. 'cashedOut': '0',
  1016. 'profit': 0
  1017. };
  1018. }
  1019. CRusersAmount[user.steamid]['amount'] += parseInt(m.amount);
  1020. socket.emit('message', {
  1021. type: 'crbetconfirm',
  1022. bet: {
  1023. betid: row3.insertId,
  1024. amount: m.amount,
  1025. autoCashout: m.autoCash
  1026. },
  1027. balance: row[0].balance-m.amount,
  1028. mybr: usersCr[user.steamid],
  1029. br: CRbr,
  1030. exec: (end.getTime()-start_time.getTime()).toFixed(3)
  1031. });
  1032. users[user.steamid].balance = row[0].balance-m.amount;
  1033. io.sockets.emit('message', {
  1034. type: 'crbet',
  1035. bet: {
  1036. cashedOut: '0',
  1037.  
  1038. amount: m.amount,
  1039. autoCashout: m.autoCash,
  1040. betid: row3.insertId,
  1041. icon: user.avatar,
  1042. name: user.name,
  1043. user: user.steamid
  1044. }
  1045. });
  1046. CRcurrentBets.push({
  1047. cashedOut: '0',
  1048. autoCashout: m.autoCash,
  1049. amount: m.amount,
  1050. betid: row3.insertId,
  1051. icon: user.avatar,
  1052. name: user.name,
  1053. user: user.steamid,
  1054. won: '0'
  1055. });
  1056. socket.emit('message', {
  1057. type: 'setIsPlaying'
  1058. });
  1059. logger.debug('CRBet confirmed #'+row3.insertId+' | Amount: '+m.amount+' | AutoCashout: '+m.autoCash+' | User: '+pool.escape(user.steamid));
  1060. checkTimer();
  1061. })
  1062. });
  1063. } else {
  1064. socket.emit('message', {
  1065. type: 'error',
  1066. enable: true,
  1067. error: 'Error: You dont have any money.'
  1068. });
  1069. }
  1070. });
  1071. }else {
  1072. socket.emit('message', {
  1073. type: 'error',
  1074. enable: true,
  1075. error: 'Error: You cannot bet, because the bet is offline.'
  1076. });
  1077. }
  1078. }
  1079.  
  1080. function stopTimers() {
  1081. clearInterval(timerC1);
  1082. clearInterval(timerC2);
  1083. clearInterval(timerC3);
  1084. clearInterval(timerC4);
  1085. clearInterval(timerC5);
  1086. clearInterval(timerC6);
  1087. clearInterval(timerC7);
  1088. clearInterval(timerC8);
  1089. clearInterval(timerC9);
  1090. clearInterval(timerC10);
  1091. clearInterval(timerC11);
  1092. clearInterval(timerC12);
  1093. }
  1094.  
  1095. function startTimer(number) {
  1096. if(number == 1) {
  1097. timerC1 = setInterval(function() {
  1098. crashNumber += 1;
  1099. getCrashAmount();
  1100. checkCashouts();
  1101.  
  1102. if(crashNumber == crashAt) {
  1103. reluareCrash();
  1104. stopTimers();
  1105. }
  1106.  
  1107. io.sockets.emit('message', {
  1108. type: 'urcarecrash',
  1109. grafic: crashNumber
  1110. });
  1111. }, 200);
  1112. }else if(number == 2) {
  1113. timerC2 = setInterval(function() {
  1114. crashNumber += 1;
  1115. getCrashAmount();
  1116. checkCashouts();
  1117.  
  1118. if(crashNumber == crashAt) {
  1119. reluareCrash();
  1120. stopTimers();
  1121. }
  1122.  
  1123. io.sockets.emit('message', {
  1124. type: 'urcarecrash',
  1125. grafic: crashNumber
  1126. });
  1127. }, 150);
  1128. }else if(number == 3) {
  1129. timerC3 = setInterval(function() {
  1130. crashNumber += 1;
  1131. getCrashAmount();
  1132. checkCashouts();
  1133.  
  1134. if(crashNumber == crashAt) {
  1135. reluareCrash();
  1136. stopTimers();
  1137. }
  1138.  
  1139. io.sockets.emit('message', {
  1140. type: 'urcarecrash',
  1141. grafic: crashNumber
  1142. });
  1143. }, 130);
  1144. }else if(number == 4) {
  1145. timerC4 = setInterval(function() {
  1146. crashNumber += 1;
  1147. getCrashAmount();
  1148. checkCashouts();
  1149.  
  1150. if(crashNumber == crashAt) {
  1151. reluareCrash();
  1152. stopTimers();
  1153. }
  1154.  
  1155. io.sockets.emit('message', {
  1156. type: 'urcarecrash',
  1157. grafic: crashNumber
  1158. });
  1159. }, 100);
  1160. }else if(number == 5) {
  1161. timerC5 = setInterval(function() {
  1162. crashNumber += 1;
  1163. getCrashAmount();
  1164. checkCashouts();
  1165.  
  1166. if(crashNumber == crashAt) {
  1167. reluareCrash();
  1168. stopTimers();
  1169. }
  1170.  
  1171. io.sockets.emit('message', {
  1172. type: 'urcarecrash',
  1173. grafic: crashNumber
  1174. });
  1175. }, 80);
  1176. }else if(number == 6) {
  1177. timerC6 = setInterval(function() {
  1178. crashNumber += 1;
  1179. getCrashAmount();
  1180. checkCashouts();
  1181.  
  1182. if(crashNumber == crashAt) {
  1183. reluareCrash();
  1184. stopTimers();
  1185. }
  1186.  
  1187. io.sockets.emit('message', {
  1188. type: 'urcarecrash',
  1189. grafic: crashNumber
  1190. });
  1191. }, 60);
  1192. }else if(number == 7) {
  1193. timerC7 = setInterval(function() {
  1194. crashNumber += 1;
  1195. getCrashAmount();
  1196. checkCashouts();
  1197.  
  1198. if(crashNumber == crashAt) {
  1199. reluareCrash();
  1200. stopTimers();
  1201. }
  1202.  
  1203. io.sockets.emit('message', {
  1204. type: 'urcarecrash',
  1205. grafic: crashNumber
  1206. });
  1207. }, 30);
  1208. }else if(number == 8) {
  1209. timerC8 = setInterval(function() {
  1210. crashNumber += 1;
  1211. getCrashAmount();
  1212. checkCashouts();
  1213.  
  1214. if(crashNumber == crashAt) {
  1215. reluareCrash();
  1216. stopTimers();
  1217. }
  1218.  
  1219. io.sockets.emit('message', {
  1220. type: 'urcarecrash',
  1221. grafic: crashNumber
  1222. });
  1223. }, 15);
  1224. }else if(number == 9) {
  1225. timerC9 = setInterval(function() {
  1226. crashNumber += 1;
  1227. getCrashAmount();
  1228. checkCashouts();
  1229.  
  1230. if(crashNumber == crashAt) {
  1231. reluareCrash();
  1232. stopTimers();
  1233. }
  1234.  
  1235. io.sockets.emit('message', {
  1236. type: 'urcarecrash',
  1237. grafic: crashNumber
  1238. });
  1239. }, 0.1);
  1240. }else if(number == 10) {
  1241. timerC10 = setInterval(function() {
  1242. crashNumber += 1;
  1243. getCrashAmount();
  1244. checkCashouts();
  1245.  
  1246. if(crashNumber == crashAt) {
  1247. reluareCrash();
  1248. stopTimers();
  1249. }
  1250.  
  1251. io.sockets.emit('message', {
  1252. type: 'urcarecrash',
  1253. grafic: crashNumber
  1254. });
  1255. }, 0.01);
  1256. }else if(number == 11) {
  1257. timerC11 = setInterval(function() {
  1258. crashNumber += 1;
  1259. getCrashAmount();
  1260. checkCashouts();
  1261.  
  1262. if(crashNumber == crashAt) {
  1263. reluareCrash();
  1264. stopTimers();
  1265. }
  1266.  
  1267. io.sockets.emit('message', {
  1268. type: 'urcarecrash',
  1269. grafic: crashNumber
  1270. });
  1271. }, 0.001);
  1272. }else if(number == 12) {
  1273. timerC12 = setInterval(function() {
  1274. crashNumber += 1;
  1275. getCrashAmount();
  1276. checkCashouts();
  1277.  
  1278. if(crashNumber == crashAt) {
  1279. reluareCrash();
  1280. stopTimers();
  1281. }
  1282.  
  1283. io.sockets.emit('message', {
  1284. type: 'urcarecrash',
  1285. grafic: crashNumber
  1286. });
  1287. }, 0.0001);
  1288. }
  1289. }
  1290.  
  1291. function sendCrashAmount() {
  1292. if(isStatedSet == 0) {
  1293. crashState = 'STARTED';
  1294. isStatedSet = 1;
  1295. }
  1296.  
  1297. if(instaCrash == 1) {
  1298.  
  1299. reluareCrash();
  1300. instaCrash = 0;
  1301.  
  1302. CRcurrentBets = [];
  1303. usersCr = {};
  1304. CRusersAmount = {};
  1305.  
  1306. io.sockets.emit('message', {
  1307. type: 'crashed',
  1308. crashmanule: rCAt
  1309. });
  1310.  
  1311. crashState = 'ENDED';
  1312. }else {
  1313. startTimer(1);
  1314. }
  1315. }
  1316.  
  1317.  
  1318. function startCrashGame() {
  1319. var timpEmis;
  1320.  
  1321.  
  1322. crashState = 'STARTING';
  1323. timp = 700;
  1324. crashNumber = 100;
  1325.  
  1326. isStatedSet = 0;
  1327.  
  1328. var crypto = require('crypto');
  1329.  
  1330. var serverSeed = 'Test';
  1331.  
  1332. var genGameHash = function(serverSeed) {
  1333. return crypto.createHash('sha256').update(serverSeed).digest('hex');
  1334. };
  1335.  
  1336. var crashPointFromHash = function(serverSeed) {
  1337. var hash = crypto.createHmac('sha256', serverSeed).digest('hex');
  1338.  
  1339. var divisible = function divisible(hash, mod) {
  1340. var val = 0;
  1341.  
  1342. var o = hash.length % 4;
  1343. for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
  1344. val = ((val << 16) + parseInt(hash.substring(i, i+4), 16)) % mod;
  1345. }
  1346.  
  1347. return val === 0;
  1348. };
  1349.  
  1350. var INSTANT_CRASH_PERCENTAGE = 5;
  1351. if (divisible(hash, 100 / parseInt(INSTANT_CRASH_PERCENTAGE, 10)))
  1352. return 0;
  1353.  
  1354. var h = parseInt(hash.slice(0,52/4),16);
  1355. var e = Math.pow(2,52);
  1356.  
  1357. return Math.floor((100 * e - h) / (e - h));
  1358. };
  1359.  
  1360. serverSeed = genGameHash(serverSeed+time());
  1361.  
  1362. var terminatingHash = genGameHash(serverSeed);
  1363. var crashhh = crashPointFromHash(serverSeed);
  1364. rCAt = crashhh;
  1365. crashAt = rCAt;
  1366. logger.debug('New hash game: ' + terminatingHash + ' with crashPoint: ' + (crashhh / 100).toFixed(2) +'x');
  1367. HaShGame = terminatingHash;
  1368.  
  1369.  
  1370.  
  1371.  
  1372. if(rCAt <= 100) {
  1373. instaCrash = 1;
  1374. }
  1375.  
  1376. intervalul = setInterval(function() {
  1377. timp = timp - 10;
  1378. timpEmis = timp;
  1379.  
  1380. if(timp == 0){
  1381. sendCrashAmount();
  1382.  
  1383. setTimeout(function() {
  1384. clearInterval(intervalul);
  1385. }, 10);
  1386. }
  1387.  
  1388. io.sockets.emit('message', {
  1389. type: 'startcrash',
  1390. time: timpEmis
  1391. });
  1392.  
  1393. }, 100);
  1394. }
Add Comment
Please, Sign In to add comment