SHARE
TWEET

Untitled

a guest Jul 19th, 2019 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const   redis = require('../redis'),
  2.         constants = require('../constants'),
  3.         satoshi = constants.satoshi,
  4.         contract = constants.contract,
  5.         minimalWithdraw = constants.minimalWithdraw,
  6.         maxWithdrawNoKyc = constants.maxWithdrawNoKyc,
  7.         bitcoinIP = require('../constants').bitcoinIP,
  8.         bitcoinPort = require('../constants').bitcoinPort,
  9.         bitcoinUser = require('../constants').bitcoinUser,
  10.         bitcoinPassword = require('../constants').bitcoinPassword,
  11.         { spawn } = require('child_process'),
  12.         ObjectID = require('mongodb').ObjectID,
  13.         mongo = require('../mongo');
  14.  
  15. const withdraw = function withdraw(id, cluster, json, ip, callback){
  16.    
  17.     json['ad'] = String(json['ad']);
  18.     json['q'] = parseFloat(String(json['q']));
  19.    
  20.     if(checkBTC(json['ad']) == false){
  21.         callback(JSON.stringify({error : true, message : "A valid address must be provided.", my_id : json['my_id']}));
  22.         return;
  23.     }
  24.    
  25.     if(isNaN(json['q']) || json['q'] <= 0){
  26.         callback(JSON.stringify({error : true, message : "Quantity must be a number", my_id : json['my_id']}));
  27.         return;
  28.     }
  29.    
  30.     if(json['q'] < minimalWithdraw){
  31.         callback(JSON.stringify({error : true, message : "Quantity must be a number greater or equal to "+minimalWithdraw+" BTC", my_id : json['my_id']}));
  32.         return;
  33.     }
  34.    
  35.     redis[cluster].hmget(id, 'free', 'locked', function(err, result){
  36.         if(err){
  37.             callback(JSON.stringify({error : true, message : "The operation failed, please try again.", my_id : json['my_id']}));
  38.             return;
  39.         }
  40.        
  41.         let free = Number(result[0]),   locked = Number(result[1]);
  42.  
  43.         free -= json['q'] * satoshi;
  44.  
  45.         if(free < 0){
  46.             callback(JSON.stringify({error : true, message : "Not enough funds.", my_id : json['my_id']}));
  47.             return;
  48.         }
  49.  
  50.         if(free < locked){
  51.             callback(JSON.stringify({error : true, message : "You must keep funds to reduce your positions.", my_id : json['my_id']}));
  52.             return;        
  53.         }
  54.        
  55.         withdrawBTC(id, cluster, json, ip, callback, result, free, locked, result['kyc'], cpt_withdraw);
  56.     });
  57. }
  58.  
  59. function withdrawBTC(id, cluster, json, ip, callback, result, free, locked, kyc, cpt_withdraw){
  60.     try{
  61.         const address = json['ad'], qte = json['q'], now = Date.now()
  62.        
  63.         const mult = [
  64.             ['hincrby', id, 'free', qte * satoshi * -1],
  65.             ['hincrby', id, 'cpt_withdraw', qte * satoshi],
  66.             ['lpush', id+'l', JSON.stringify({d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC requested', ip:ip})]
  67.         ];
  68.        
  69.         if(now - json['t'] > 2000){
  70.             callback(JSON.stringify({error : true, message : "The operation failed, please try again.", my_id : json['my_id']}));
  71.             return;                    
  72.         }
  73.  
  74.         redis[cluster].multi(mult).exec(function(err, result){
  75.             if(err){
  76.                 callback(JSON.stringify({error : true, message : "The operation failed, please try again.", my_id : json['my_id']}));
  77.                 return;
  78.             }
  79.                                    
  80.             mongo.insert(cluster, {id:id, d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC to '+address+' requested', ip:ip}, 'logs');
  81.            
  82.             const sendtoaddress = spawn('bitcoin-cli', ['-rpcconnect='+bitcoinIP, '-rpcport='+bitcoinPort, '-rpcuser='+bitcoinUser, '-rpcpassword='+bitcoinPassword, 'sendtoaddress', address, qte, "", id, true]);
  83.             let result_command = "";
  84.            
  85.             sendtoaddress.stdout.on('data', (data) => {result_command+=data;});
  86.  
  87.             sendtoaddress.stderr.on('data', (data) => {});
  88.            
  89.             sendtoaddress.on('error', (code) => {});
  90.  
  91.             sendtoaddress.on('close', (code) => {
  92.                 if(code != 0){
  93.                     callback(JSON.stringify({error : true, message : "Please contact the support.", my_id : json['my_id'], free:(free / satoshi).toFixed(8)}));
  94.                     mongo.insert(cluster, {id:id, d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC to '+address+' failed', ip:ip}, 'logs');
  95.                     redis[cluster].lpush(id+'l', JSON.stringify({d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC failed', ip:ip}));
  96.                 }else{
  97.                     result_command = result_command.substr(0, result_command.length - 1);
  98.                     const bal = [now, "BTC Withdraw to "+address, qte * -1];
  99.                     const mult = [
  100.                         ['lpush', id+'b', JSON.stringify(bal)],
  101.                         ['lpush', id+'l', JSON.stringify({d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC confirmed', ip:ip})]
  102.                     ];
  103.                     redis[cluster].multi(mult).exec(function(err, result){
  104.                         if(!err){
  105.                             mongo.insert(cluster, {id:id, d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC to '+address+' confirmed', ip:ip}, 'logs');
  106.                             mongo.insert(cluster, {id:id, d:now, l:'BTC Withdraw to '+address, q:bal[2], txid:result_command}, 'balance');
  107.                             callback(JSON.stringify({error: false, message : "Withdraw confirmed txid:"+result_command, txid:result_command, my_id : json['my_id'], free:(free / satoshi).toFixed(8)}));
  108.                         }else{
  109.                             mongo.insert(cluster, {id:id, d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC to '+address+' failed', ip:ip}, 'logs');
  110.                             redis[cluster].lpush(id+'l', JSON.stringify({d:now, l:'Withdraw of '+Number(qte).toFixed(8)+' BTC failed', ip:ip}));
  111.                             callback(JSON.stringify({error: true, message : "Please contact the support.", my_id : json['my_id'], free:(free / satoshi).toFixed(8)}));
  112.                         }
  113.                     });
  114.                 }
  115.             });
  116.         });
  117.     }catch(e){
  118.         console.log(e);
  119.         callback(JSON.stringify({error : true, message : "The operation failed, please try again.", my_id : json['my_id']}));
  120.     }  
  121. }
  122.  
  123. function isChecksumAddress (address) {
  124.     address = address.replace('0x','');
  125.     var addressHash = sha3(address.toLowerCase());
  126.     for (var i = 0; i < 40; i++ ) {
  127.             if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
  128.                 return false;
  129.             }
  130.     }
  131.     return true;
  132. };
  133.  
  134.  
  135. function checkBTC(address) {
  136.   var decoded = base58_decode(address);    
  137.   if (decoded.length != 25) return false;
  138.   var cksum = decoded.substr(decoded.length - 4);
  139.   var rest = decoded.substr(0, decoded.length - 4);  
  140.   const firsthex2a = hex2a(crypto.createHash('sha256').update(rest, 'ascii').digest('hex'));
  141.   var good_cksum = hex2a(crypto.createHash('sha256').update(firsthex2a, 'ascii').digest('hex')).substr(0, 4);
  142.   if (cksum != good_cksum) return false;
  143.   return true;
  144. }
  145.  
  146. var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  147. var ALPHABET_MAP = {}
  148. for(var i = 0; i < ALPHABET.length; i++) {
  149.   ALPHABET_MAP[ALPHABET.charAt(i)] = i
  150. }
  151. var BASE = 58
  152. function base58_decode(string) {
  153.   if (string.length === 0) return []
  154.  
  155.   var i, j, bytes = [0]
  156.   for (i = 0; i < string.length; i++) {
  157.     var c = string[i]
  158.     if (!(c in ALPHABET_MAP)) return "";
  159.  
  160.     for (j = 0; j < bytes.length; j++) bytes[j] *= BASE
  161.     bytes[0] += ALPHABET_MAP[c]
  162.  
  163.     var carry = 0
  164.     for (j = 0; j < bytes.length; ++j) {
  165.       bytes[j] += carry
  166.  
  167.       carry = bytes[j] >> 8
  168.       bytes[j] &= 0xff
  169.     }
  170.  
  171.     while (carry) {
  172.       bytes.push(carry & 0xff)
  173.  
  174.       carry >>= 8
  175.     }
  176.   }
  177.  
  178.   // deal with leading zeros
  179.   for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0)
  180.  
  181.   bytes = bytes.reverse()
  182.   output = '';
  183.   for (i=0; i<bytes.length; i++) {
  184.      output += String.fromCharCode(bytes[i]);
  185.   }
  186.   return output;
  187. }
  188.  
  189. function hex2a(hex) {
  190.     var str = '';
  191.     for (var i = 0; i < hex.length; i += 2)
  192.             str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  193.     return str;
  194. }
  195.  
  196. function a2hex(str) {
  197.     var aHex = "0123456789abcdef";
  198.     var l = str.length;
  199.     var nBuf;
  200.     var strBuf;
  201.     var strOut = "";
  202.     for (var i = 0; i < l; i++) {
  203.         nBuf = str.charCodeAt(i);
  204.         strBuf = aHex[Math.floor(nBuf/16)];
  205.         strBuf += aHex[nBuf % 16];
  206.         strOut += strBuf;
  207.     }
  208.     return strOut;
  209. }
  210.  
  211. function pow(big, exp) {
  212.     if (exp == 0) return int2bigInt(1, 1, 0);
  213.     var i;
  214.     var newbig = big;
  215.     for (i = 1; i < exp; i++) {
  216.         newbig = mult(newbig, big);
  217.     }
  218.  
  219.     return newbig;
  220. }
  221.  
  222. function repeat(s, n){
  223.     var a = [];
  224.     while(a.length < n){
  225.             a.push(s);
  226.     }
  227.     return a.join('');
  228. }
  229.  
  230. module.exports.withdraw = withdraw;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top