diff --git a/cronjobs/README b/cronjobs/README deleted file mode 100644 index f8f87124..00000000 --- a/cronjobs/README +++ /dev/null @@ -1,22 +0,0 @@ - -Install: --------- - -These scripts should not really be placed inside of the webroot. They should be run -from the shell via a cronjob. Set something up like this: - -# m h dom mon dow command - * * * * * /full/path/to/pool_update.sh 1>/dev/null 2>/dev/null - -Also be sure to define in each of these scripts the full path to the include directory. -See the top of each script in the cronjob directory for details. - - - -Notes: ------- -These scripts (from version 2.x.x forward) are intended to run every 60 secs. Best results will be achieved -if you configure your server to run them at the same interval. You risk missing new block information being -inserted into the database the longer you set the interval between these scripts running. Database load has -been significantly improved from version 2.x.x forward and it should now be perfectly safe to run these -scripts every 60 secs. diff --git a/cronjobs/archive.php b/cronjobs/archive.php deleted file mode 100644 index df9b0bc8..00000000 --- a/cronjobs/archive.php +++ /dev/null @@ -1,58 +0,0 @@ -getblocknumber(); -$num_blocks_old = ($currentBlockNumber - 10); - -if (!$num_blocks_old) { die($num_blocks_old); } - -// get all shares by user id from shares_history and move to shares_uncounted - - $sql = "SELECT DISTINCT p.associatedUserId, blockNumber, sum(s.valid) as valid, IFNULL(sum(si.invalid),0) as invalid, max(maxId) as maxId FROM ". - "(SELECT DISTINCT username, max(blockNumber) as blockNumber, count(id) as valid, max(id) as maxId FROM shares_history ". - "WHERE counted='0' AND our_result='Y' AND blockNumber <= '" .$num_blocks_old. "' GROUP BY username) s ". - "LEFT JOIN ". - "(SELECT DISTINCT username, count(id) as invalid FROM shares_history ". - "WHERE counted='0' AND our_result='N' AND blockNumber <= '" .$num_blocks_old. "' GROUP BY username) si ". - "ON s.username=si.username ". - "INNER JOIN pool_worker p ON p.username = s.username ". - "GROUP BY associatedUserId"; - - -$sharesQ = mysql_query($sql); -$i = 0; -$maxId = 0; -$shareInputSql = ""; - -while ($sharesR = mysql_fetch_object($sharesQ)) { - if ($sharesR->maxId > $maxId) - $maxId = $sharesR->maxId; - if ($i == 0) { - $shareInputSql = "INSERT INTO shares_uncounted (blockNumber, userId, count, invalid, counted, score) VALUES "; - } - if ($i > 0) { - $shareInputSql .= ","; - } - $i++; - $shareInputSql .= "($sharesR->blockNumber,$sharesR->associatedUserId,$sharesR->valid,$sharesR->invalid,0,0)"; - if ($i > 20) - { - mysql_query($shareInputSql); - $shareInputSql = ""; - $i = 0; - } -} -if (strlen($shareInputSql) > 0) - mysql_query($shareInputSql); - -//Remove counted shares from shares_history - mysql_query("DELETE FROM shares_history WHERE counted = '0' AND id <= $maxId AND blockNumber <= '" .$num_blocks_old. "'"); - -?> diff --git a/cronjobs/cronjob.php b/cronjobs/cronjob.php deleted file mode 100644 index ab7e4a99..00000000 --- a/cronjobs/cronjob.php +++ /dev/null @@ -1,364 +0,0 @@ -getblocknumber(); -$difficulty = $bitcoinController->query("getdifficulty"); - -//Get site percentage -$sitePercent = 0; -$sitePercentQ = mysql_query("SELECT value FROM settings WHERE setting='sitepercent'"); -if ($sitePercentR = mysql_fetch_object($sitePercentQ)) $sitePercent = $sitePercentR->value; - -//Setup score variables -$c = .00001; -$f=1; -$f = $sitePercent / 100; -$p = 1.0/$difficulty; -$r = log(1.0-$p+$p/$c); -$B = 50; -$los = log(1/(exp($r)-1)); - -//Query bitcoind for list of transactions -$transactions = $bitcoinController->query('listtransactions', '', '240'); -$numAccounts = count($transactions); - -for($i = 0; $i < $numAccounts; $i++){ - // Check for 50BTC in each transaction (even when immature so we can start tracking confirms) - if($transactions[$i]["amount"] >= 50 && ($transactions[$i]["category"] == "immature" || $transactions[$i]["category"] == "immature")) { - - // At this point we may have found a block, Check to see if this accountAddres is already added to `networkBlocks` - $accountExistsQ = mysql_query("SELECT id FROM networkBlocks WHERE accountAddress = '".$transactions[$i]["txid"]."' ORDER BY blockNumber DESC LIMIT 0,1")or die(mysql_error()); - $accountExists = mysql_num_rows($accountExistsQ); - - // We have a new immature transaction for 50 BTC or more - make an entry in `networkBlocks` so we can start tracking the confirms - if(!$accountExists){ - $assoc_block = ($currentBlockNumber + 1) - $transactions[$i]["confirmations"]; - $assoc_timestamp = $transactions[$i]["time"]; - $finder = mysql_fetch_object(mysql_query("SELECT DISTINCT id, username FROM shares where upstream_result = 'Y'")); - - // save the winning share and username (if we know it) - if ($finder) { - $last_winning_share = $finder->id; - $username = $finder->username; - mysql_query("INSERT INTO winning_shares (blockNumber, username) VALUES ('" .$assoc_block. "', '" .$username. "')"); - } else { - mysql_query("INSERT INTO winning_shares (blockNumber, username) VALUES ('" .$assoc_block. "', 'unknown')"); - } - - // save the block info so we can track confirms - mysql_query("INSERT INTO `networkBlocks` (`blockNumber`, `timestamp`, `accountAddress`, `confirms`, `difficulty`) ". - "VALUES ('$assoc_block', '$assoc_timestamp', '" .$transactions[$i]["txid"]. "', '" .$transactions[$i]["confirmations"]. "', '$difficulty')"); - - // score and move shares from this block to shares_history - $shareInputQ = ""; - $i=0; - $lastId = 0; - $lastScore = 0; - - if ($finder) { - $getAllShares = mysql_query("SELECT `id`, `rem_host`, `username`, `our_result`, `upstream_result`, `reason`, `solution`, time FROM `shares` WHERE id <='" .$last_winning_share. "' ORDER BY `id` ASC"); - } else { - $getAllShares = mysql_query("SELECT `id`, `rem_host`, `username`, `our_result`, `upstream_result`, `reason`, `solution`, time FROM `shares` ORDER BY `id` ASC"); - } - - while($share = mysql_fetch_array($getAllShares)){ - if ($i==0) - $shareInputQ = "INSERT INTO `shares_history` (`blockNumber`, `rem_host`, `username`, `our_result`, `upstream_result`, `reason`, `solution`, time, score) VALUES "; - $i++; - if($i > 1){ - $shareInputQ .= ","; - } - $score = $lastScore + $r; - $shareInputQ .="('".$assoc_block."', - '".$share["rem_host"]."', - '".$share["username"]."', - '".$share["our_result"]."', - '".$share["upstream_result"]."', - '".$share["reason"]."', - '".$share["solution"]."', - '".$share["time"]."', - ".$score.")"; - $lastId = $share["id"]; - $lastScore = $score; - if ($i > 5) { - //Add to `shares_history` - $shareHistoryQ = mysql_query($shareInputQ); - - //If the add to shares_history was successful, lets clean up `shares` table - if($shareHistoryQ){ - //Delete all from shares whoms "id" is less then $lastId (keep everything that didnt get moved. Its probably from the new round. - mysql_query("DELETE FROM shares WHERE id <= ".$lastId); - } - $i = 0; - } - } - // less than five share entries? still do the same as above. - $shareHistoryQ = mysql_query($shareInputQ); - if($shareHistoryQ){ - //Delete all from shares whoms "id" is less then $lastId to prevent new "hard-earned" shares to be deleted - mysql_query("DELETE FROM shares WHERE id <= ".$lastId); - } - // Count number of shares we needed to solve this block - - // get last block number we found - $last_winning_blockQ = mysql_query("SELECT DISTINCT blockNumber FROM winning_shares ORDER BY blockNumber DESC LIMIT 1,1"); - $last_winning_blockObj = mysql_fetch_object($last_winning_blockQ); - $last_winning_block = $last_winning_blockObj->blockNumber; - - $block_share_countQ = mysql_query("SELECT sum(su_count) as total FROM (". - "SELECT sum(count) as su_count FROM shares_uncounted where blockNumber > " .$last_winning_block. " ". - "and blockNumber <= " .$assoc_block. " ". - "UNION SELECT count(id) as sh_count from shares_history where blockNumber <= " .$assoc_block. " AND blockNumber > " .$last_winning_block. " AND our_result != 'N' ". - ") a"); - $block_share_countObj = mysql_fetch_object($block_share_countQ); - - if($block_share_countObj) { - mysql_query("UPDATE `winning_shares` SET `shareCount` = " .$block_share_countObj->total. " WHERE blockNumber = " .$assoc_block); - } - } - } -} - - - -///// Update confirms ///// - -// run thru list of transactions we got from bitcoind and update their confirms (when immature) -for($i = 0; $i < $numAccounts; $i++){ - //if ($transactions[$i]["category"] = "receive") - if (($transactions[$i]["category"] = "immature") || ($transactions[$i]["category"] = "immature")){ - //Check to see if this account was one of the winning accounts from `networkBlocks` - $arrayAddress = $transactions[$i]["txid"]; - $winningAccountQ = mysql_query("SELECT id FROM networkBlocks WHERE accountAddress = '".$arrayAddress."' LIMIT 0,1"); - $winningAccount = mysql_num_rows($winningAccountQ); - - if($winningAccount > 0){ - //This is a winning account - $winningAccountObj = mysql_fetch_object($winningAccountQ); - $winningId = $winningAccountObj->id; - $confirms = $transactions[$i]["confirmations"]; - - //Update X amount of confirms - mysql_query("UPDATE networkBlocks SET confirms = '".$confirms."' WHERE id = ".$winningId); - } - } -} - - - - -///// Check for new network block and score and move shares to shares_history if true /// - -// refresh the current block number data -$currentBlockNumber = $bitcoinController->getblocknumber(); - -// check if we have it in the database (if so we exit because we already did this and we were the block finder) -$inDatabaseQ = mysql_query("SELECT `id` FROM `networkBlocks` WHERE `blockNumber` = '$currentBlockNumber' LIMIT 0,1"); -$inDatabase = mysql_num_rows($inDatabaseQ); -$finder = mysql_fetch_object(mysql_query("SELECT DISTINCT id, username FROM shares where upstream_result = 'Y'")); - -if(!$inDatabase){ - // make an entry in the DB for this new block - $currentTime = time(); - mysql_query("INSERT INTO `networkBlocks` (`blockNumber`, `timestamp`, `difficulty`) VALUES ('$currentBlockNumber', '$currentTime', '$difficulty')"); - - // score and move shares from this block to shares_history - $shareInputQ = ""; - $i=0; - $lastId = 0; - $lastScore = 0; - - $getAllShares = mysql_query("SELECT `id`, `rem_host`, `username`, `our_result`, `upstream_result`, `reason`, `solution`, time FROM `shares` ORDER BY `id` ASC"); - - while($share = mysql_fetch_array($getAllShares)){ - if ($i==0) - $shareInputQ = "INSERT INTO `shares_history` (`blockNumber`, `rem_host`, `username`, `our_result`, `upstream_result`, `reason`, `solution`, time, score) VALUES "; - $i++; - if($i > 1){ - $shareInputQ .= ","; - } - $score = $lastScore + $r; - $shareInputQ .="('".$currentBlockNumber."', - '".$share["rem_host"]."', - '".$share["username"]."', - '".$share["our_result"]."', - '".$share["upstream_result"]."', - '".$share["reason"]."', - '".$share["solution"]."', - '".$share["time"]."', - ".$score.")"; - $lastId = $share["id"]; - $lastScore = $score; - if ($i > 5) { - //Add to `shares_history` - $shareHistoryQ = mysql_query($shareInputQ); - - //If the add to shares_history was successful, lets clean up `shares` table - if($shareHistoryQ){ - //Delete all from shares whoms "id" is less then $lastId (keep everything that didnt get moved. Its probably from the new round. - mysql_query("DELETE FROM shares WHERE id <= ".$lastId); - } - $i = 0; - } - } - // less than five share entries? still do the same as above. - $shareHistoryQ = mysql_query($shareInputQ); - if($shareHistoryQ) { - //Delete all from shares whoms "id" is less then $lastId to prevent new "hard-earned" shares to be deleted - mysql_query("DELETE FROM shares WHERE id <= ".$lastId); - //exec("cd /sites/mmc/cronjobs/; /usr/bin/php archive.php"); - } -} - - - - -///// Proportional Payout Method ///// - -// Get uncounted share total -$overallReward = 0; -$blocksQ = mysql_query("SELECT DISTINCT s.blockNumber FROM shares_uncounted s, networkBlocks n WHERE s.blockNumber = n.blocknumber AND s.counted=0 AND n.confirms > 119 ORDER BY s.blockNumber ASC"); - -while ($blocks = mysql_fetch_object($blocksQ)) { - $block = $blocks->blockNumber; - - // LastNshares - mark all shares below the $lastNshares threshold counted - $l_bound = 0; - $total = 0; - $lastNshares = 1000000; - - $sql = mysql_query("SELECT blockNumber, count FROM ( ". - "SELECT blockNumber, count FROM `shares_uncounted` WHERE blockNumber <= " .$block. " ". - "UNION SELECT blockNumber, count FROM `shares_counted` WHERE blockNumber <= " .$block. " AND blockNumber > ".($block - 1000)." ". - ")a ORDER BY blockNumber DESC"); - - while ($result = mysql_fetch_object($sql)) { - - // increment $total with each row returned - $total = $total + $result->count; - - // if $lastNshares criteria is met, and $l_bound is not our whole count, set everything below $l_bound as counted = 1 - if ($total >= $lastNshares) { - $l_bound = $result->blockNumber; - - if ($l_bound < $block) { - mysql_query("UPDATE shares_uncounted SET counted = 1 WHERE blockNumber < ".$l_bound); - } - break; - } - } - - $totalRoundSharesQ = mysql_query("SELECT sum(id) as id FROM ( ". - "SELECT sum(count) as id FROM shares_uncounted WHERE blockNumber <= ".$block." AND blockNumber >= ".$l_bound." ". - "UNION SELECT sum(count) as id FROM shares_counted WHERE blockNumber <= " .$block. " AND blockNumber >= ".$l_bound."". - " )a"); - - if ($totalRoundSharesR = mysql_fetch_object($totalRoundSharesQ)) { - $totalRoundShares = $totalRoundSharesR->id; - - $userListCountQ = mysql_query("SELECT userId, sum(id) as id FROM ( ". - "SELECT DISTINCT userId, sum(count) as id FROM shares_uncounted WHERE blockNumber <= ".$block." AND blockNumber >= ".$l_bound." GROUP BY userId ". - "UNION DISTINCT SELECT userId, sum(count) as id FROM shares_counted WHERE blockNumber <= " .$block. " AND blockNumber >= ".$l_bound." GROUP BY userId ". - " )a GROUP BY userId"); - - while ($userListCountR = mysql_fetch_object($userListCountQ)) { - $userInfoR = mysql_fetch_object(mysql_query("SELECT DISTINCT username, donate_percent FROM webUsers WHERE id = '" .$userListCountR->userId. "'")); - - $username = $userInfoR->username; - $uncountedShares = $userListCountR->id; - $shareRatio = $uncountedShares/$totalRoundShares; - $ownerId = $userListCountR->userId; - $donatePercent = $userInfoR->donate_percent; - - //Take out site percent unless user is of early adopter account type - $account_type = account_type($ownerId); - if ($account_type == 0) { - // is normal account - $predonateAmount = (1-$f)*(50*$shareRatio); - $predonateAmount = rtrim(sprintf("%f",$predonateAmount ),"0"); - $totalReward = $predonateAmount - ($predonateAmount * ($sitePercent/100)); - } else { - // is early adopter round 1 0% lifetime fees - $predonateAmount = 0.9999*(50*$shareRatio); - $predonateAmount = rtrim(sprintf("%f",$predonateAmount ),"0"); - $totalReward = $predonateAmount; - } - - if ($predonateAmount > 0.00000001) { - - //Take out donation - $totalReward = $totalReward - ($totalReward * ($donatePercent/100)); - - //Round Down to 8 digits - $totalReward = $totalReward * 100000000; - $totalReward = floor($totalReward); - $totalReward = $totalReward/100000000; - - //Get total site reward - $donateAmount = round(($predonateAmount - $totalReward), 8); - - $overallReward += $totalReward; - - //Update account balance & site ledger - mysql_query("UPDATE accountBalance SET balance = balance + ".$totalReward." WHERE userId = ".$ownerId); - - mysql_query("INSERT INTO ledger (userId, transType, amount, feeAmount, assocBlock) ". - " VALUES ". - "('$ownerId', 'Credit', '$totalReward', '$donateAmount', '$block')"); - } - mysql_query("UPDATE shares_uncounted SET counted = 1 WHERE userId='".$ownerId."' AND blockNumber <= ".$block); - } - // update site wallet with our reward from this block - if (isset($B)) { - $poolReward = $B -$overallReward; - } - //mysql_query("UPDATE settings SET value = value +".$poolReward." WHERE setting='sitebalance'"); - mv_uncountedToCounted(); - } -} - -function mv_uncountedToCounted() { - // clean counted shares_uncounted and move to shares_counted - $sql = "SELECT DISTINCT * FROM shares_uncounted WHERE counted=1"; - - $sharesQ = mysql_query($sql); - $i = 0; - //$maxId = 0; - $shareInputSql = ""; - - while ($sharesR = mysql_fetch_object($sharesQ)) { - //if ($sharesR->maxId > $maxId) - // $maxId = $sharesR->maxId; - if ($i == 0) { - $shareInputSql = "INSERT INTO shares_counted (blockNumber, userId, count, invalid, counted, score) VALUES "; - } - if ($i > 0) { - $shareInputSql .= ","; - } - $i++; - $shareInputSql .= "($sharesR->blockNumber,$sharesR->userId,$sharesR->count,$sharesR->invalid,$sharesR->counted,$sharesR->score)"; - if ($i > 20) - { - mysql_query($shareInputSql); - $shareInputSql = ""; - $i = 0; - } - } - - // if not empty, Insert - if (strlen($shareInputSql) > 0) - mysql_query($shareInputSql); - - //Remove counted shares from shares_uncounted (this should empty it completely or something went wrong. - mysql_query("DELETE FROM shares_uncounted WHERE counted = '1'"); -} -?> diff --git a/cronjobs/findblock.php b/cronjobs/findblock.php new file mode 100644 index 00000000..e313db57 --- /dev/null +++ b/cronjobs/findblock.php @@ -0,0 +1,57 @@ +getLast()->blockhash; +if (!$strLastBlockHash) { + $strLastBlockHash = ''; +} + +try { + $aTransactions = $bitcoin->query('listsinceblock', $strLastBlockHash); +} catch (Exception $e) { + echo "Unable to connect to bitcoin RPC\n"; + exit(1); +} + +foreach ($aTransactions['transactions'] as $iIndex => $aData) { + if ( $aData['category'] == 'generate' || $aData['category'] == 'immature' ) { + $aBlockInfo = $bitcoin->query('getblock', $aData['blockhash']); + $aData['height'] = $aBlockInfo['height']; + if ( ! $block->addBlock($aData) ) { + echo "Failed to add block: " . $aData['height'] , "\n"; + echo "Error : " . $block->getError() . "\n"; + } + } +} +?> diff --git a/cronjobs/hashrate.php b/cronjobs/hashrate.php deleted file mode 100644 index 6bd54987..00000000 --- a/cronjobs/hashrate.php +++ /dev/null @@ -1,63 +0,0 @@ - DATE_SUB(now(), INTERVAL 10 MINUTE) ". - "GROUP BY username) ". - "UNION ". - "(SELECT count(id) as id, username ". - "FROM shares_history ". - "WHERE time > DATE_SUB(now(), INTERVAL 10 MINUTE) ". - "GROUP BY username)) a ". - "ON p.username=a.username ". - "GROUP BY username"; -$result = mysql_query($sql); -while ($resultrow = mysql_fetch_object($result)) { - $hashrate = $resultrow->id; - $hashrate = round((($hashrate*4294967296)/600)/1000000, 0); - mysql_query("UPDATE pool_worker SET hashrate = $hashrate WHERE username = '$resultrow->username'"); -} - -//Total Hashrate (more exact than adding) -$sql = "SELECT sum(a.id) as id FROM ". - "((SELECT count(id) as id FROM shares WHERE time > DATE_SUB(now(), INTERVAL 10 MINUTE)) ". - "UNION ". - "(SELECT count(id) as id FROM shares_history WHERE time > DATE_SUB(now(), INTERVAL 10 MINUTE)) ". - ") a "; -$result = mysql_query($sql); -if ($resultrow = mysql_fetch_object($result)) { - $hashrate = $resultrow->id; - $hashrate = round((($hashrate*4294967296)/600)/1000000, 0); - mysql_query("UPDATE settings SET value = '$hashrate' WHERE setting='currenthashrate'"); -} - -//Hashrate by user -$sql = "SELECT u.id, IFNULL(sum(p.hashrate),0) as hashrate ". - "FROM webUsers u LEFT JOIN pool_worker p ". - "ON p.associatedUserId = u.id ". - "GROUP BY id"; -$result = mysql_query($sql); -while ($resultrow = mysql_fetch_object($result)) { - mysql_query("UPDATE webUsers SET hashrate = $resultrow->hashrate WHERE id = $resultrow->id"); - - // Enable this for lots of stats for graphing - if ($resultrow->hashrate > 0) { - mysql_query("INSERT INTO userHashrates (userId, hashrate) VALUES ($resultrow->id, $resultrow->hashrate)"); // active users hashrate - } -} - -mysql_query("INSERT INTO userHashrates (userId, hashrate) VALUES (0, $hashrate)"); // the pool total hashrate - -$currentTime = time(); -mysql_query("update settings set value='$currentTime' where setting='statstime'"); - -// Clean up the userHashrate table (anything older than 4 days) -mysql_query("DELETE FROM userHashrates WHERE timestamp < DATE_SUB(now(), INTERVAL 96 HOUR)"); - -?> diff --git a/cronjobs/payout.php b/cronjobs/payout.php deleted file mode 100644 index 4bf5c851..00000000 --- a/cronjobs/payout.php +++ /dev/null @@ -1,40 +0,0 @@ -= 0.10 AND balance > threshold"); -while ($resultR = mysql_fetch_object($resultQ)) { - $currentBalance = $resultR->balance; - $paid = $resultR->paid; - $paymentAddress = $resultR->sendAddress; - $userId = $resultR->userId; - - if ($paymentAddress != '') - { - $isValidAddress = $bitcoinController->validateaddress($paymentAddress); - if($isValidAddress){ - // Subtract TX fee & calculate total amount the pool will pay - $currentBalance = $currentBalance - 0.0005; - $tot_paid = $resultR->paid + $currentBalance; - - // Send the BTC! - // debug - // echo "sending: ". $currentBalance . " to ". $paymentAddress; - - if($bitcoinController->sendtoaddress($paymentAddress, $currentBalance)) { - // Reduce balance amount to zero, update total paid amount, and make a ledger entry - mysql_query("UPDATE `accountBalance` SET balance = '0', paid = '".$tot_paid."' WHERE `userId` = '".$userId."'"); - - mysql_query("INSERT INTO ledger (userId, transType, amount, sendAddress) ". - " VALUES ". - "('$userId', 'Debit_ATP', '$currentBalance', '$paymentAddress')"); - - } - } - } -} diff --git a/cronjobs/pool_update.sh b/cronjobs/pool_update.sh deleted file mode 100644 index e34ba857..00000000 --- a/cronjobs/pool_update.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# -# This is where all the magic happens. These scripts count shares, calculate payouts, -# calculate user hashrates, decide when we have found a block and what to do about it, -# and determine if workers are alive or dead. They are the the meat of this package. -# - -## Make sure this matches the location of your -## of your php binary. -PHP_BIN="/usr/bin/php"; - -#################################################################################### -PID=$$; -PIDFILE=/var/run/pool_update.pid - -if [ -e $PIDFILE ]; then - echo "Already running. I cannot be twice invoked."; - exit -else - echo $PID > $PIDFILE - cd /sites/mmc/cronjobs/ - echo -e "\ncronjob.php\n-------------"; time $PHP_BIN cronjob.php; sleep 1; - echo -e "\nshares.php\n-------------"; time $PHP_BIN shares.php; sleep 1; - echo -e "\npayout.php\n-------------"; time $PHP_BIN payout.php; sleep 1; - echo -e "\nworkers.php\n-------------"; time $PHP_BIN workers.php; sleep 1; - echo -e "\nhashrate.php\n-------------"; time $PHP_BIN hashrate.php; sleep 1; - echo -e "\narchive.php\n-------------"; time $PHP_BIN archive.php; sleep 1; - $PHP_BIN tickers.php & - rm -rf $PIDFILE -fi diff --git a/cronjobs/shares.php b/cronjobs/shares.php deleted file mode 100644 index cf89ce59..00000000 --- a/cronjobs/shares.php +++ /dev/null @@ -1,56 +0,0 @@ -valid, stale_share_count = $pastSharesR->invalid WHERE id = $pastSharesR->userId"); - } -} catch (Exception $ex) {} - -///// Update current round shares - -// reset counters -mysql_query("UPDATE webUsers SET shares_this_round=0"); - -try { - $sql = "SELECT SUM( id ) AS id, a.associatedUserId ". - "FROM ( ". - "SELECT COUNT( s.id ) AS id, p.associatedUserId ". - "FROM shares s, pool_worker p ". - "WHERE p.username = s.username ". - "AND s.our_result = 'Y' ". - "GROUP BY p.associatedUserId ". - "UNION SELECT COUNT( s.id ) AS id, p.associatedUserId ". - "FROM shares_history s, pool_worker p ". - "WHERE p.username = s.username ". - "AND s.our_result = 'Y' ". - "AND s.counted = '0' ". - "GROUP BY p.associatedUserId ". - ")a ". - "GROUP BY associatedUserId"; - - $result = mysql_query($sql); - $totalsharesthisround = 0; - while ($row = mysql_fetch_object($result)) { - mysql_query("UPDATE webUsers SET shares_this_round = $row->id WHERE id = $row->associatedUserId"); - $totalsharesthisround += $row->id; - } - - $currentSharesQ = mysql_query("SELECT DISTINCT userId, sum(count) AS valid, sum(invalid) AS invalid, id FROM shares_uncounted GROUP BY userId"); - while ($currentSharesR = mysql_fetch_object($currentSharesQ)) { - mysql_query("UPDATE webUsers SET shares_this_round = (shares_this_round + $currentSharesR->valid) ". - "WHERE id = $currentSharesR->userId"); - $totalsharesthisround += $currentSharesR->valid; - } - - mysql_query("UPDATE settings SET value = '$totalsharesthisround' WHERE setting='currentroundshares'"); -} catch (Exception $ex) {} - -?> diff --git a/cronjobs/tickers.php b/cronjobs/tickers.php deleted file mode 100644 index abc8f63d..00000000 --- a/cronjobs/tickers.php +++ /dev/null @@ -1,33 +0,0 @@ -. -// - -//Set page starter variables// -$includeDirectory = "/sites/mmc/www/includes/"; - -//Include site functions -include($includeDirectory."requiredFunctions.php"); - - - // Update MtGox last price via curl, 3 second timeout on connection - $mtgox_ticker = exec("/usr/bin/curl -q -s --connect-timeout 3 'https://mtgox.com/code/data/ticker.php'"); - if (!is_null($mtgox_ticker)) { - $ticker_obj = json_decode($mtgox_ticker); - if (intval($ticker_obj->ticker->last) > 0) { - $settings->setsetting('mtgoxlast', round($ticker_obj->ticker->last, 4)); - } - } - -?> diff --git a/cronjobs/workers.php b/cronjobs/workers.php deleted file mode 100644 index 5ff264e6..00000000 --- a/cronjobs/workers.php +++ /dev/null @@ -1,56 +0,0 @@ -query("getdifficulty"); - //$difficulty = '1'; - -//Get site percentage fee -$sitePercent = 0; -$sitePercentQ = mysql_query("SELECT value FROM settings WHERE setting='sitepercent'"); -if ($sitePercentR = mysql_fetch_object($sitePercentQ)) $sitePercent = $sitePercentR->value; - -// set up some scoring variables -$c = .00000001; -$f = $sitePercent / 100; -$p = 1.0/$difficulty; -$r = log(1.0-$p+$p/$c); -$B = 50; -$los = log(1/(exp($r)-1)); - -// Check for if worker is active (submitted shares in the last 10 mins) -$currentWorkers = 0; -try { - $sql ="SELECT sum(a.id) IS NOT NULL AS active, p.username FROM pool_worker p LEFT JOIN ". - "(SELECT count(id) AS id, username FROM shares WHERE time > DATE_SUB(now(), INTERVAL 10 MINUTE) group by username ". - "UNION ". - "SELECT count(id) AS id, username FROM shares_history WHERE time > DATE_SUB(now(), INTERVAL 10 MINUTE) group by username) a ON p.username=a.username group by username"; - $result = mysql_query($sql); - while ($resultObj = mysql_fetch_object($result)) { - if ($resultObj->active == 1) - $currentWorkers += 1; - mysql_query("UPDATE pool_worker p SET active=".$resultObj->active." WHERE username='".$resultObj->username."'"); - } - - // Update number of workers in our pool status - $settings->setsetting('currentworkers', $currentWorkers); - -} catch (Exception $e) {} - - - // Calculate estimated round earnings for each user - - //Proportional estimate - $totalRoundShares = $settings->getsetting("currentroundshares"); - - //if ($totalRoundShares < $difficulty) $totalRoundShares = $difficulty; - mysql_query("UPDATE webUsers SET round_estimate = round((1-".$f.")*50*(shares_this_round/".$totalRoundShares.")*(1-(donate_percent/100)), 8)"); - - // comment the one line below out if you want to disable 0% fees for first 35 users - mysql_query("UPDATE webUsers SET round_estimate = round(0.9999*50*(shares_this_round/".$totalRoundShares.")*(1-(donate_percent/100)), 8) WHERE account_type = '9'"); - diff --git a/public/include/autoloader.inc.php b/public/include/autoloader.inc.php new file mode 100644 index 00000000..1cd74202 --- /dev/null +++ b/public/include/autoloader.inc.php @@ -0,0 +1,10 @@ +debug = $debug; + $this->mysqli = $mysqli; + $this->debug->append("Instantiated Block class", 2); + } + + // get and set methods + private function setErrorMessage($msg) { + $this->sError = $msg; + } + public function getError() { + return $this->sError; + } + + public function getLast() { + $stmt = $this->mysqli->prepare("SELECT * FROM $this->table ORDER BY height DESC LIMIT 1"); + if ($this->checkStmt($stmt)) { + $stmt->execute(); + $result = $stmt->get_result(); + $stmt->close(); + return $result->fetch_object(); + } + return false; + } + + public function addBlock($block) { + $stmt = $this->mysqli->prepare("INSERT INTO $this->table (height, blockhash, confirmations, amount, time) VALUES (?, ?, ?, ?, ?)"); + if ($this->checkStmt($stmt)) { + $stmt->bind_param('isidi', $block['height'], $block['blockhash'], $block['confirmations'], $block['amount'], $block['time']); + if (!$stmt->execute()) { + $this->debug->append("Failed to execute statement: " . $stmt->error); + $stmt->close(); + return false; + } + $stmt->close(); + return true; + } + return false; + } + + private function checkStmt($bState) { + if ($bState ===! true) { + $this->debug->append("Failed to prepare statement: " . $this->mysqli->error); + $this->setErrorMessage('Internal application Error'); + return false; + } + return true; + } +} + +$block = new Block($debug, $mysqli, SALT); diff --git a/public/include/classes/debug.class.php b/public/include/classes/debug.class.php index fa7b13b8..f0c549fc 100644 --- a/public/include/classes/debug.class.php +++ b/public/include/classes/debug.class.php @@ -17,7 +17,7 @@ class Debug { /** * @var integer $DEBUG enable (1) or disable (0) debugging */ - private static $DEBUG; + private $DEBUG; /** * @var array $debugInfo Data array with debugging information @@ -27,7 +27,7 @@ class Debug { /** * @var float $startTime Start time of our debugger */ - private static $floatStartTime; + private $floatStartTime; /** * Construct our class diff --git a/public/include/smarty.inc.php b/public/include/smarty.inc.php index 465edba5..b2e67f37 100644 --- a/public/include/smarty.inc.php +++ b/public/include/smarty.inc.php @@ -5,10 +5,10 @@ if (!defined('SECURITY')) die('Hacking attempt'); $debug->append('Loading Smarty libraries', 2); -define('SMARTY_DIR', INCLUDE_DIR . '/smarty/libs/'); +define('SMARTY_DIR', BASEPATH . INCLUDE_DIR . '/smarty/libs/'); // Include the actual smarty class file -include(INCLUDE_DIR . '/smarty/libs/Smarty.class.php'); +include(SMARTY_DIR . 'Smarty.class.php'); // We initialize smarty here $debug->append('Instantiating Smarty Object', 3); diff --git a/public/index.php b/public/index.php index 708d9272..ceddd9a5 100644 --- a/public/index.php +++ b/public/index.php @@ -18,6 +18,9 @@ limitations under the License. */ +// This should be okay +define("BASEPATH", "./"); + // Our security check define("SECURITY", 1); @@ -26,17 +29,11 @@ session_start(); $session_id = session_id(); // Include our configuration (holding defines for the requires) -require_once('include/config/global.inc.php'); +require_once(BASEPATH . 'include/config/global.inc.php'); // Load Classes, they name defines the $ variable used // We include all needed files here, even though our templates could load them themself -require_once(CLASS_DIR . '/debug.class.php'); -require_once(CLASS_DIR . '/bitcoin.class.php'); -require_once(INCLUDE_DIR . '/database.inc.php'); -require_once(INCLUDE_DIR . '/smarty.inc.php'); -// Load classes that need the above as dependencies -require_once(CLASS_DIR . '/user.class.php'); -require_once(CLASS_DIR . '/settings.class.php'); +require_once(INCLUDE_DIR . '/autoloader.inc.php'); // Create our pages array from existing files if (is_dir(INCLUDE_DIR . '/pages/')) {