Example #1
0
 function FindNewGenerations($bitcoinController)
 {
     $blockcount = 0;
     $username = '';
     //Get list of last 200 transactions
     $transactions = $bitcoinController->query("listtransactions", "*", "200");
     //Go through all the transactions check if there is 50BTC inside
     $numAccounts = count($transactions);
     for ($i = 0; $i < $numAccounts; $i++) {
         //Check for 50BTC inside only if they are in the generate category
         if ($transactions[$i]["category"] == "generate" || $transactions[$i]["category"] == "immature") {
             //At this point we may or may not have found a block,
             //Check to see if this account addres 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 sqlerr(__FILE__, __LINE__);
             $accountExists = mysql_num_rows($accountExistsQ);
             //Insert txid into latest network block
             if (!$accountExists) {
                 //Get last winning block
                 $lastSuccessfullBlockQ = mysql_query("SELECT blockNumber, id, username FROM winning_shares ORDER BY id DESC LIMIT 1") or sqlerr(__FILE__, __LINE__);
                 $lastSuccessfullBlockR = mysql_fetch_object($lastSuccessfullBlockQ);
                 $timestamp = $transactions[$i]["time"];
                 $id = $lastSuccessfullBlockR->id;
                 $rpcType = "http";
                 // http or https
                 $rpcUsername = "******";
                 // username
                 $rpcPassword = "******";
                 // password
                 $rpcHost = "localhost";
                 $rpcPort = 9000;
                 $bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost, $rpcPort);
                 $currentBlockNumber = $bitcoinController->getblocknumber();
                 $confirms = $transactions[$i]["confirmations"];
                 $lastBlockNumber = $currentBlockNumber + 1 - $confirms;
                 $stats = new Stats();
                 mysql_query("INSERT INTO networkBlocks (blockNumber, timestamp, accountAddress, confirms) " . "VALUES ('{$lastBlockNumber}', '{$timestamp}', '" . $transactions[$i]["txid"] . "', '" . $transactions[$i]["confirmations"] . "')") or sqlerr(__FILE__, __LINE__);
                 $stats = new Stats();
                 $lastwinningid = $stats->lastWinningShareId();
                 $shareQ = mysql_query("SELECT sum(shares) as total from rounddetails WHERE blockNumber = {$lastBlockNumber}");
                 $shareC = mysql_fetch_object($shareQ);
                 $winningShareQ = mysql_query("SELECT id, username FROM shares where upstream_result = 'Y' AND id > {$lastwinningid}") or sqlerr(__FILE__, __LINE__);
                 while ($winningShareR = mysql_fetch_object($winningShareQ)) {
                     mysql_query("INSERT INTO winning_shares (blockNumber, username, share_id) VALUES ({$lastBlockNumber},'{$winningShareR->username}',{$winningShareR->id})") or sqlerr(__FILE__, __LINE__);
                     removeCache("last_winning_share_id");
                 }
                 //					$q = "UPDATE winning_shares SET amount = " . $transactions[$i]["amount"] . ", timestamp = " . $timestamp . ", txid = '".$transactions[$i]["txid"] . "', type = '" . $transactions[$i]["category"] . "', shares = ". $shareC->total . " WHERE blockNumber = $lastBlockNumber";
                 $q = "UPDATE winning_shares SET amount = " . $transactions[$i]["amount"] . ", timestamp = " . $timestamp . ", txid = '" . $transactions[$i]["txid"] . "', type = '" . $transactions[$i]["category"] . "' WHERE blockNumber = {$lastBlockNumber}";
                 echo $q;
                 mysql_query($q) or sqlerr(__FILE__, __LINE__);
                 $username = $lastSuccessfullBlockR->username;
                 $splitUsername = explode(".", $username);
                 $realUsername = $splitUsername[0];
                 $blockcount = $blockcount + 1;
                 $username .= $realUsername . ' ';
             }
         }
     }
 }
 public function getdifficulty()
 {
     $this->oDebug->append("STA " . __METHOD__, 4);
     if ($data = $this->memcache->get(__FUNCTION__)) {
         return $data;
     }
     $data = parent::getdifficulty();
     // Check for PoS/PoW coins
     if (is_array($data) && array_key_exists('proof-of-work', $data)) {
         $data = $data['proof-of-work'];
     }
     return $this->memcache->setCache(__FUNCTION__, $data, 30);
 }
<?php

require_once './lib/bitcoin.php';
$scheme = 'http';
$username = '******';
$password = '******';
$address = "localhost";
// Local
$port = 18332;
// Testnet
$bitcoin_client = new BitcoinClient($scheme, $username, $password, $address, $port);
if ($bitcoin_client->can_connect() !== TRUE) {
    echo 'The Bitcoin server is presently unavailable. Please contact the site administrator.';
    exit;
}
/**
 * Process Bitcoin checkout.
 *
 * @param string $separator
 * @param integer $sessionid
 * @todo Document better
 */
function gateway_bitcoin($separator, $sessionid)
{
    global $wpdb, $wpsc_cart;
    include_once "library/bitcoin.inc";
    $bitcoin_client = new BitcoinClient(get_option("bitcoin_scheme"), get_option("bitcoin_username"), get_option("bitcoin_password"), get_option("bitcoin_address"), get_option("bitcoin_port"), get_option("bitcoin_certificate_path"));
    if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
        bitcoin_checkout_fail($session, 'The Bitcoin server is presently unavailable. Please contact the site administrator.', $fault);
        return;
    }
    $row = $wpdb->get_row("SELECT id,totalprice FROM " . WPSC_TABLE_PURCHASE_LOGS . " WHERE sessionid=" . $sessionid);
    $label = $row->id . " " . $row->totalprice;
    try {
        $address = $bitcoin_client->query("getnewaddress", $label);
    } catch (BitcoinClientException $e) {
        bitcoin_checkout_fail($session, 'The Bitcoin server is presently unavailable. Please contact the site administrator.', $e->getMessage());
        return;
    }
    if (!Bitcoin::checkAddress($address)) {
        bitcoin_checkout_fail($session, 'The Bitcoin server returned an invalid address. Please contact the site administrator.', $e->getMessage());
        return;
    }
    //var_dump($_SESSION);
    unset($_SESSION['WpscGatewayErrorMessage']);
    // Set the transaction to pending payment and log the Bitcoin address as its transaction ID
    $wpdb->query("UPDATE " . WPSC_TABLE_PURCHASE_LOGS . " SET processed='1', transactid='" . $address . "' WHERE sessionid=" . $sessionid);
    $_SESSION['bitcoin'] = 'success';
    $_SESSION['bitcoin_address_display'] = $address;
    $_SESSION['bitcoin_address_mail'] = $address;
    header("Location: " . get_option('transact_url') . $separator . "sessionid=" . $sessionid);
    exit;
}
Example #5
0
		<div id="header">
			<div id="logo">
				<table width="100%" cellspacing="0" cellpadding="0" border="0">
					<tr>
					<td rowspan="2"><img src="images/logo.png"></td>
					<td align="right" valign="bottom" id="currentRates">
<?
echo "<table class=\"hashrate\">";
$result = apc_fetch("serverstats:common");
if ($result !== FALSE) {
    echo $result;
} else {
    $output = '';
    $ourHashrate = $settings->getsetting('currenthashrate');
    $output .= "<tr><td>Current Hashrate</td><td>".number_format($ourHashrate/1000,3)." MH/s</td></tr>";
    $bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
    $networkHashrate = (intval($bitcoinController->query('getnetworkhashps'))/1000);
    $output .= "<tr><td>Network Hashrate</td><td>".number_format($networkHashrate/1000, 3)." MH/s </td></tr>";
    $output .= "<tr><td>Info</td><td>We are ".number_format($ourHashrate/$networkHashrate*100, 2)."%</td></tr>";
    $output .= "<tr><td>Current Workers</td><td>".$settings->getsetting('currentworkers')."</td></tr>";
    echo $output;
    apc_store("serverstats:common", $output, 20);
}
?>
</table>

					</tr>
				</table>
			</div>
		</div>
		<?php 
Example #6
0
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 	  BTC Donations: 163Pv9cUDJTNUbadV4HMRQSSj3ipwLURRc
$includeDirectory = "/var/www/includes/";
include $includeDirectory . "requiredFunctions.php";
//Verify source of cron job request
if (isset($cronRemoteIP) && $_SERVER['REMOTE_ADDR'] !== $cronRemoteIP) {
    die(header("Location: /"));
}
lock("money.php");
//mysql_query('SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE');
//mysql_query('BEGIN');
/////////Pay users who have reached their threshold payout
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
$resultQ = mysql_query("select userId, cast(balance as decimal(16,8)) as balance, IFNULL(paid, 0) as paid, IFNULL(sendAddress, '') as sendAddress FROM accountBalance WHERE CAST(threshold AS decimal(16,8)) >= 0.1 AND CAST(balance AS decimal(16,8)) >= CAST(threshold AS decimal(16,8))");
while ($resultR = mysql_fetch_object($resultQ)) {
    $currentBalance = $resultR->balance;
    $paid = $resultR->paid;
    $paymentAddress = $resultR->sendAddress;
    $userId = $resultR->userId;
    //echo "Payment: $paid , User: $userId , Current Balance: $currentBalance<br>";
    if ($paymentAddress != '') {
        $isValidAddress = $bitcoinController->validateaddress($paymentAddress);
        if ($isValidAddress) {
            //Subtract TX feee
            //$currentBalance = $currentBalance - 0.01;
            //Send money//
            if ($bitcoinController->sendtoaddress($paymentAddress, $currentBalance)) {
                //Reduce balance amount to zero
Example #7
0
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 	  BTC Donations: 163Pv9cUDJTNUbadV4HMRQSSj3ipwLURRc
$pageTitle = "- Admin Panel";
include "includes/header.php";
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
$goodMessage = "";
$returnError = "";
//Scince this is the Admin panel we'll make sure the user is logged in and "isAdmin" enabled boolean; If this is not a logged in user that is enabled as admin, redirect to a 404 error page
if (!$cookieValid || $isAdmin != 1) {
    header('Location: /');
    exit;
}
if (isset($_POST["act"]) && isset($_POST["authPin"])) {
    if (isset($_POST["authPin"])) {
        $inputAuthPin = hash("sha256", $_POST["authPin"] . $salt);
    } else {
        $inputAuthPin = NULL;
    }
    //Make sure an authPin is set and valid when $act is active
    if ($_POST["act"] && $authPin == $inputAuthPin) {
Example #8
0
    public $confirmations;
    public $txid;
    public $time;
    public function __construct($address, $category, $amount, $fee, $confirmations, $txid, $time)
    {
        $this->address = $address;
        $this->category = $category;
        $this->amount = $amount;
        $this->fee = $fee;
        $this->confirmations = $confirmations;
        $this->txid = $txid;
        $this->time = $time;
    }
}
$accounts = array();
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
$bitAccounts = $bitcoinController->query("listaccounts");
foreach ($bitAccounts as $name => $balance) {
    $account = new BAccount($name, $balance);
    $accounts[] = $account;
    $bitTransactions = $bitcoinController->query("listtransactions", $name, 10000);
    foreach ($bitTransactions as $bitT) {
        $account->txns[] = new BTxn(@$bitT['address'], $bitT['category'], $bitT['amount'], @$bitT['fee'], $bitT['confirmations'], $bitT['txid'], $bitT['time']);
    }
    usort($account->txns, function ($a, $b) {
        return $b->time - $a->time;
    });
}
?>
<html>
    <head>
Example #9
0
$apikey = mysql_real_escape_string($_GET["api_key"]);
$useridq = mysql_query("SELECT id FROM webUsers WHERE api_key = '" . $apikey . "'") or sqlerr(__FILE__, __LINE__);
$userida = mysql_fetch_object($useridq);
$id = $userida->id;
$user = new User();
/*
$estq = mysql_query("SELECT estimate FROM roundDetails WHERE userId = '$id' ORDER BY estimate DESC");
$esta = mysql_fetch_object($estq);
if($esta->estimate == NULL) {
$user->last_paid = '0'; } ELSE {
$user->last_paid = $esta->estimate;}
*/
$blockq = mysql_query("SELECT blockNumber FROM networkBlocks WHERE confirms > '0' ORDER BY blockNumber DESC");
$blocka = mysql_fetch_object($blockq);
$user->last_block = $blocka->blockNumber;
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
$user->current_block = $bitcoinController->query("getblocknumber");
$resultU = mysql_query("SELECT u.id, u.hashrate, u.round_estimate, shares_this_round, b.balance, b.paid from webUsers u, accountBalance b WHERE u.id = b.userId AND u.api_key='" . $apikey . "'");
if ($userobj = mysql_fetch_object($resultU)) {
    $userid = $userobj->id;
    $user->current_balance = $userobj->balance;
    $user->hashrate = $userobj->hashrate;
    $user->payout_history = $userobj->paid;
    $user->round_estimate = $userobj->round_estimate;
    $user->shares_this_round = $userobj->shares_this_round;
}
if (isset($_GET["api_key"])) {
    $userQ = mysql_query("SELECT id FROM webUsers WHERE api_key = '" . $apikey . "'");
    $userA = mysql_fetch_object($userQ);
    $userId1 = $userA->id;
    $resultW = mysql_query("SELECT username, hashrate, active, hashes FROM pool_worker WHERE associatedUserId={$userId1}");
Example #10
0
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 	  BTC Donations: 163Pv9cUDJTNUbadV4HMRQSSj3ipwLURRc
error_reporting(E_ALL);
ini_set('display_errors', '1');
$includeDirectory = "/var/www/includes/";
include $includeDirectory . "requiredFunctions.php";
//Verify source of cron job request
if (isset($cronRemoteIP) && $_SERVER['REMOTE_ADDR'] !== $cronRemoteIP) {
    die(header("Location: /"));
}
lock("workers.php");
mysql_query("BEGIN");
/////////Update workers
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
//Get difficulty
$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 = 0.001;
$f = 1;
if ($sitePercent > 0) {
    $f = $sitePercent / 100;
} else {
    $f = -$c / (1 - $c);
 /**
  * Process the payment
  * @param string $order_number
  * @param float $order_total
  * @param array $d
  * @return boolean true if bitcoin
  */
 function process_payment($order_number, $order_total, &$d)
 {
     include_once CLASSPATH . "payment/ps_bitcoin.cfg.php";
     // TODO: handle conversions via to-be-written converter script
     // it's also available as global $vendor_currency
     //"currency_code" => $_SESSION['vendor_currency'],
     global $vmLogger;
     $bitcoin_client = new BitcoinClient(BITCOIN_SCHEME, BITCOIN_USERNAME, BITCOIN_PASSWORD, BITCOIN_HOST, BITCOIN_PORT, BITCOIN_CERTIFICATE);
     if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
         $vmLogger->err("The Bitcoin server is presently unavailable. Please contact the site administrator.");
         return false;
     }
     // stuff the (long) order number, the total order price and a timestamp into the bitcoin address's label
     $label = $order_number . " " . number_format($order_total, 2, ".", "") . " " . time();
     try {
         $address = $bitcoin_client->query("getnewaddress", $label);
     } catch (BitcoinClientException $e) {
         $vmLogger->err("The Bitcoin server was unable to generate an address for your payment. Please contact the site administrator.");
         return false;
     }
     if (!Bitcoin::checkAddress($address)) {
         $vmLogger->err("The Bitcoin server returned an invalid address. Please contact the site administrator.");
         return false;
     }
     // stuff the payment address into the session so the "extra info" code can access it
     // TODO: There's gotta be a better way...
     $_SESSION["bitcoin_address"] = $address;
     $d['include_comment'] = "Y";
     $d['order_comment'] = "Please send your payment to Bitcoin address " . $address;
     return true;
 }
/*** END VirtueMart part ***/
global $vmLogger;
// slurp in all the open Bitcoin transactions
$sql = "select #__{vm}_orders.order_id,order_payment_name,order_number,order_total ";
$sql .= "from #__{vm}_order_payment left join #__{vm}_orders on #__{vm}_orders.order_id = #__{vm}_order_payment.order_id ";
// TODO: Extract "BC" in some intelligent, safe manner
$sql .= "where payment_method_id=(select payment_method_id from #__{vm}_payment_method where payment_method_code='BC') and order_status='" . BITCOIN_PENDING_STATUS . "'";
$db = new ps_DB();
$db->query($sql);
if (!$db->next_record()) {
    die("No open Bitcoin transactions");
}
require_once CLASSPATH . 'ps_order.php';
require_once CLASSPATH . "payment/ps_bitcoin.php";
// prepare the JSON-RPC client
$bitcoin_client = new BitcoinClient(BITCOIN_SCHEME, BITCOIN_USERNAME, BITCOIN_PASSWORD, BITCOIN_HOST, BITCOIN_PORT, BITCOIN_CERTIFICATE);
if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
    $vmLogger->err("Bitcoin cronjob: Unable to connect to Bitcoin server, fault: " . $fault);
    die("Bitcoin cronjob: Unable to connect to Bitcoin server, fault: " . $fault);
}
//$bitcoin_client->setDebug(2);
// loop through the open transactions
do {
    // check for transaction completion
    $address = $db->f("order_payment_name");
    try {
        $paid = $bitcoin_client->query("getreceivedbyaddress", $address, intval(BITCOIN_CONFIRMS));
    } catch (BitcoinClientException $e) {
        $vmLogger->err("Bitcoin server communication failed on getreceivedbyaddress " . $address . " with fault string " . $e->getMessage());
        continue;
    }
Example #13
0
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 	  BTC Donations: 163Pv9cUDJTNUbadV4HMRQSSj3ipwLURRc
//
//    Improved Stats written by Tom Lightspeed (tomlightspeed@gmail.com + http://facebook.com/tomlightspeed)
//    Developed Socially for http://ozco.in
//    If you liked my work, want changes/etc please contact me or donate 16p56JHwLna29dFhTRcTAurj4Zc2eScxTD.
//    Special thanks to Wayno, Graet & Ycros from #ozcoin on freenode.net for their help :-)
//    Additional thanks to Krany from #ozcoin on freenode.net.
//    May the force be with you.
$pageTitle = "- Stats";
include "includes/header.php";
$numberResults = 30;
$last_no_blocks_found = 5;
$onion_winners = 10;
$bitcoinController = new BitcoinClient($rpcType, $rpcUsername, $rpcPassword, $rpcHost);
$difficulty = $bitcoinController->query("getdifficulty");
//time = difficulty * 2**32 / hashrate
// hashrate is in Mhash/s
function CalculateTimePerBlock($btc_difficulty, $_hashrate)
{
    if ($btc_difficulty > 0 && $_hashrate > 0) {
        $find_time_hours = $btc_difficulty * bcpow(2, 32) / ($_hashrate * bcpow(10, 6)) / 3600;
    } else {
        $find_time_hours = 0;
    }
    return $find_time_hours;
}
function CoinsPerDay($time_per_block, $btc_block)
{
    if ($time_per_block > 0 && $btc_block > 0) {