コード例 #1
1
 public function postWithdraw()
 {
     $amount = Bitcoin::toSatoshi(floatval(Input::get('amount', 0)));
     $address = Input::get('address');
     if ($amount < Config::get('bitcoin.minimum_withdrawal')) {
         return Redirect::back()->withInput()->with('error', 'Amount is less than the minimum.');
     } else {
         if ($amount > Auth::user()->getBalance()) {
             return Redirect::back()->withInput()->with('error', 'You do not have the required funds.');
         }
     }
     if (!Bitcoin::checkAddress($address)) {
         return Redirect::back()->withInput()->with('error', 'Invalid bitcoin address.');
     }
     $api_url = 'https://blockchain.info/merchant/' . urlencode(Config::get('bitcoin.guid')) . '/payment';
     $api_url .= '?password='******'bitcoin.password'));
     $api_url .= '&to=' . urlencode($address);
     $withdraw_amount = $amount - Config::get('bitcoin.withdrawal_fee');
     $api_url .= '&amount=' . urlencode($withdraw_amount);
     $response = file_get_contents($api_url);
     $response = json_decode($response);
     if (!property_exists($response, 'tx_hash')) {
         return Redirect::back()->withInput()->with('error', $response->error);
     } else {
         Auth::user()->subtractFromBalance($amount);
     }
     $withdraw = new Withdraw();
     $withdraw->user_id = Auth::user()->id;
     $withdraw->amount = $amount;
     $withdraw->btc_address = $address;
     $withdraw->transaction_hash = $response->tx_hash;
     if (property_exists($response, 'notice')) {
         $withdraw->notice = $response->notice;
     }
     if (property_exists($response, 'message')) {
         $withdraw->message = $response->message;
     }
     if (!$withdraw->save()) {
         Notify::alert('Withdraw couldn\'t be saved!');
     }
     return Redirect::back()->with('success', 'Withdraw processed.');
 }
コード例 #2
1
ファイル: renting.php プロジェクト: Bitcoinsulting/yiimp
function BackendUpdateDeposit()
{
    //	debuglog(__FUNCTION__);
    $btc = getdbosql('db_coins', "symbol='BTC'");
    if (!$btc) {
        return;
    }
    $remote = new Bitcoin($btc->rpcuser, $btc->rpcpasswd, $btc->rpchost, $btc->rpcport);
    $info = $remote->getinfo();
    if (!$info) {
        return;
    }
    if (!isset($info['blocks'])) {
        return;
    }
    $hash = $remote->getblockhash(intval($info['blocks']));
    if (!$hash) {
        return;
    }
    $block = $remote->getblock($hash);
    if (!$block) {
        return;
    }
    if (!isset($block['time'])) {
        return;
    }
    if ($block['time'] + 30 * 60 < time()) {
        return;
    }
    $list = $remote->listaccounts(1);
    foreach ($list as $r => $a) {
        if ($a == 0) {
            continue;
        }
        $b = preg_match('/renter-prod-([0-9]+)/', $r, $m);
        if (!$b) {
            continue;
        }
        $renter = getdbo('db_renters', $m[1]);
        if (!$renter) {
            continue;
        }
        $ts = $remote->listtransactions(yaamp_renter_account($renter), 1);
        if (!$ts || !isset($ts[0])) {
            continue;
        }
        $moved = $remote->move(yaamp_renter_account($renter), '', $a);
        if (!$moved) {
            continue;
        }
        debuglog("deposit {$renter->id} {$renter->address}, {$a}");
        $rentertx = new db_rentertxs();
        $rentertx->renterid = $renter->id;
        $rentertx->time = time();
        $rentertx->amount = $a;
        $rentertx->type = 'deposit';
        $rentertx->tx = isset($ts[0]['txid']) ? $ts[0]['txid'] : '';
        $rentertx->save();
        $renter->unconfirmed = 0;
        $renter->balance += $a;
        $renter->updated = time();
        $renter->save();
    }
    $list = $remote->listaccounts(0);
    foreach ($list as $r => $a) {
        if ($a == 0) {
            continue;
        }
        $b = preg_match('/renter-prod-([0-9]+)/', $r, $m);
        if (!$b) {
            continue;
        }
        $renter = getdbo('db_renters', $m[1]);
        if (!$renter) {
            continue;
        }
        debuglog("unconfirmed {$renter->id} {$renter->address}, {$a}");
        $renter->unconfirmed = $a;
        $renter->updated = time();
        $renter->save();
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    $received1 = $remote->getbalance('bittrex', 1);
    //nicehash payments
    if ($received1 > 0) {
        $moved = $remote->move('bittrex', '', $received1);
        debuglog("moved from bittrex {$received1}");
        dborun("update renters set balance=balance+{$received1} where id=7");
        dborun("update renters set custom_start=custom_start+{$received1} where id=7");
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////
    $fees = 0.0001;
    $list = getdbolist('db_rentertxs', "type='withdraw' and tx='scheduled'");
    foreach ($list as $tx) {
        $renter = getdbo('db_renters', $tx->renterid);
        if (!$renter) {
            continue;
        }
        //		debuglog("$renter->balance < $tx->amount + $fees");
        $tx->amount = bitcoinvaluetoa(min($tx->amount, $renter->balance - $fees));
        if ($tx->amount < $fees * 2) {
            $tx->tx = 'failed';
            $tx->save();
            continue;
        }
        debuglog("withdraw send {$renter->id} {$renter->address} sendtoaddress({$tx->address}, {$tx->amount})");
        $tx->tx = $remote->sendtoaddress($tx->address, round($tx->amount, 8));
        if (!$tx->tx) {
            $tx->tx = 'failed';
            $tx->save();
            continue;
        }
        $renter->balance -= $tx->amount + $fees;
        $renter->balance = max($renter->balance, 0);
        dborun("update renters set balance={$renter->balance} where id={$renter->id}");
        $tx->save();
        if ($renter->balance <= 0.0001) {
            dborun("update jobs set active=false, ready=false where id={$renter->id}");
        }
    }
}
コード例 #3
1
ファイル: my-two-cents.php プロジェクト: meitar/my-two-cents
 /**
  * @param array $input An array of of our unsanitized options.
  * @return array An array of sanitized options.
  */
 public function validateSettings($input)
 {
     $safe_input = array();
     foreach ($input as $k => $v) {
         switch ($k) {
             case 'receive_addresses':
                 if (empty($v)) {
                     $errmsg = __('Receive addresses cannot be empty.', 'my-two-cents');
                     add_settings_error($this->prefix . 'settings', 'empty-receive-addresses', $errmsg);
                 }
                 $addrs = array();
                 foreach (explode("\n", $v) as $line) {
                     $line = trim($line);
                     if (Bitcoin::checkAddress($line)) {
                         $addrs[] = $line;
                     } else {
                         error_log(sprintf(__('Rejecting invalid BitCoin receive address: %s', 'my-two-cents'), $line));
                     }
                 }
                 if (empty($addrs)) {
                     $errmsg = __('You must supply at least one valid BitCoin address.', 'my-two-cents');
                     add_settings_error($this->prefix . 'settings', 'no-valid-receive-addresses', $errmsg);
                 }
                 $safe_input[$k] = implode("\n", array_map('sanitize_text_field', $addrs));
                 break;
             case 'secret':
                 $safe_input[$k] = sanitize_text_field($v);
                 break;
             case 'qr_code_img_size':
             case 'use_txs_polling':
             case 'min_confirms':
             case 'debug':
                 $safe_input[$k] = intval($v);
                 break;
         }
     }
     return $safe_input;
 }
コード例 #4
0
 public function run()
 {
     $G = new Github();
     $req_url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     $path = parse_url($req_url, PHP_URL_PATH);
     $paths = explode("/", $path);
     $project_name = $paths[2] . '/' . $paths[3];
     $this->state['project_name'] = $project_name;
     $this->state['repo'] = $G->load_stored_repo($project_name);
     if ($this->state['repo']['status'] == 4) {
         if (!$this->state['repo']['public']) {
             $G->load_user();
         }
         $G->load_coin_owners($project_name);
         $this->state['date_minted'] = $G->date_minted;
         $this->state['last_commit'] = strftime("%b %d", strtotime(query_grab("SELECT max(commit_date) FROM commit_log WHERE repo = '" . $this->state['repo']['name'] . "'")));
         $this->state['asset_hash'] = $G->asset_hash;
         $this->state['cal'] = $G->schedule;
         $this->state['contributors'] = $G->contributors;
         $this->state['equity'] = $G->equity;
         $this->state['today'] = $G->today;
     } else {
         $G->load_user();
         $BTC = new Bitcoin();
         $BTC->generate_address($project_name);
         $this->state['btc_address'] = $BTC->input_address;
         $this->state['status'] = $BTC->status;
         $this->state['hash'] = $BTC->transaction_hash;
     }
     $this->_load("mint.html");
 }
コード例 #5
0
ファイル: orders.php プロジェクト: neofutur/BitPing.Net
 public static function createOrder($userid, $active, $confirmations, $notifications, $addresses)
 {
     $db = Database::getInstance();
     $db->startTransaction();
     $stmt = $db->prepare("INSERT INTO orders (uid, confirmations) VALUES (?, ?)");
     $stmt->bind_param("ii", $userid, $confirmations);
     $order_id = $db->insert($stmt);
     if ($order_id != null) {
         $stmt = $db->prepare("INSERT INTO order_notify (order_id, notify_id) VALUES (?, ?)");
         foreach ($notifications as $notification) {
             $stmt->bind_param("ii", $order_id, $notification);
             $db->insert($stmt);
         }
         $stmt = $db->prepare("INSERT INTO order_address (order_id, address) VALUES (?, ?)");
         $bc = new Bitcoin();
         foreach ($addresses as $address) {
             if ($bc->checkAddress($address)) {
                 $stmt->bind_param("is", $order_id, $address);
                 $db->insert($stmt);
             }
         }
         $db->commit();
     } else {
         $db->rollback();
     }
 }
コード例 #6
0
 public function actionIndex()
 {
     if (isset($_COOKIE['mainbtc'])) {
         return;
     }
     if (!LimitRequest('explorer')) {
         return;
     }
     $id = getiparam('id');
     $coin = getdbo('db_coins', $id);
     $height = getparam('height');
     if ($coin && intval($height) > 0) {
         $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
         $hash = $remote->getblockhash(intval($height));
     } else {
         $hash = getparam('hash');
     }
     $txid = getparam('txid');
     if ($coin && !empty($txid) && ctype_alnum($txid)) {
         $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
         $tx = $remote->getrawtransaction($txid, 1);
         $hash = $tx['blockhash'];
     }
     if ($coin && !empty($hash) && ctype_alnum($hash)) {
         $this->render('block', array('coin' => $coin, 'hash' => substr($hash, 0, 64)));
     } else {
         if ($coin) {
             $this->render('coin', array('coin' => $coin));
         } else {
             $this->render('index');
         }
     }
 }
コード例 #7
0
ファイル: order.php プロジェクト: neofutur/BitPing.Net
 public function setAddresses($addresses)
 {
     $db = Database::getInstance();
     $stmt = $db->prepare("DELETE FROM order_address WHERE order_id = ?");
     $stmt->bind_param("i", $this->orderid);
     $db->update($stmt);
     $stmt = $db->prepare("INSERT IGNORE INTO order_address (order_id, address) VALUES (?, ?)");
     $bc = new Bitcoin();
     foreach ($addresses as $address) {
         if ($bc->checkAddress($address)) {
             $stmt->bind_param("is", $this->orderid, $address);
             $db->update($stmt);
         }
     }
     $this->addresses = $addresses;
 }
コード例 #8
0
 public function run()
 {
     header("Content-type: text/plain");
     $req_url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
     $path = parse_url($req_url, PHP_URL_PATH);
     $paths = explode("/", $path);
     $secret = $paths[2];
     $BTC = new Bitcoin();
     //$BTC->generate_address();
     $BTC->process_incoming($_GET, $secret);
     if ($_GET['confirmations'] >= 6) {
         echo "*ok*";
         //XXX I'm worried this will be too slow to fire back an "OK" to blockchain, but cron is not firing reliably.
         $repo_name = query_grab("SELECT name FROM repo WHERE address = '" . escape($_GET['input_address']) . "'");
         $A = new Asset();
         $A->issue_asset($repo_name);
     }
     die;
 }
コード例 #9
0
 public function getBalance()
 {
     $api_url = 'https://blockchain.info/merchant/' . Config::get('bitcoin.guid') . '/balance';
     $api_url .= '?password='******'bitcoin.password'));
     $api_url .= '&address=' . urlencode(Config::get('bitcoin.wallet_address'));
     $api_url .= '&confirmations=0';
     $response = file_get_contents($api_url);
     $object = json_decode($response);
     return array('usd' => Bitcoin::toUSD($object->balance), 'btc' => Bitcoin::toBTC($object->balance), 'satoshi' => $object->balance);
 }
コード例 #10
0
ファイル: SiteController.php プロジェクト: zarethernet/yaamp
 public function actionUpdate()
 {
     if (!$this->admin) {
         return;
     }
     $coin = getdbo('db_coins', getiparam('id'));
     $txfee = $coin->txfee;
     if (isset($_POST['db_coins'])) {
         $coin->attributes = $_POST['db_coins'];
         if ($coin->save()) {
             if ($txfee != $coin->txfee) {
                 $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
                 $remote->settxfee($coin->txfee);
             }
             //	$this->redirect(array('admin'));
             $this->goback();
         }
     }
     $this->render('coin_form', array('update' => true, 'coin' => $coin));
 }
コード例 #11
0
ファイル: ApiController.php プロジェクト: kartx22/Otoru-Dice
 public function CreateWallet()
 {
     $wallet = Coin::BaseWallet();
     if (strtolower(Input::get('coin')) == 'btc') {
         $wallet = Bitcoin::CreateWallet();
     } elseif (strtolower(Input::get('coin')) == 'aur') {
         $wallet['CoinCode'] = 'aur';
         $wallet['Reply'] = 'Failure';
         $wallet['Err'] = 'Not Implemented Yet';
     }
     return $wallet;
 }
コード例 #12
0
 private static function base()
 {
     $rpc = new Bitcoin(RPCUSER, RPCPASS, RPCHOST, RPCPORT);
     $info = $rpc->getinfo();
     if ($rpc->status !== 200 && $rpc->error !== '') {
         return ['err' => 'failed to connect - node not reachable, or user/pass incorrect'];
     }
     $output['rpcace_version'] = ACEVERSION;
     $output['coin_name'] = COINNAME;
     $output['num_blocks'] = $info['blocks'];
     $output['num_connections'] = $info['connections'];
     $output['version'] = $info['version'];
     $output['protocol'] = $info['protocolversion'];
     $output['moneysupply'] = $info['moneysupply'];
     if (COINPOS === true) {
         $output['current_difficulty_pow'] = $info['difficulty']['proof-of-work'];
         $output['current_difficulty_pos'] = $info['difficulty']['proof-of-stake'];
     } else {
         $output['current_difficulty_pow'] = $info['difficulty'];
     }
     if (!($hashRate = @$rpc->getmininginfo()['netmhashps']) && !($hashRate = @$rpc->getmininginfo()['networkhashps'] / 1000000)) {
         $hashRate = $rpc->getnetworkhashps() / 1000000;
     }
     $output['hashrate_mhps'] = sprintf('%.2f', $hashRate);
     $mining = $rpc->getmininginfo();
     $output['stakeweight'] = $mining['netstakeweight'];
     return ['output' => $output, 'rpc' => $rpc];
 }
コード例 #13
0
 public function actionSellto()
 {
     if (!$this->admin) {
         return;
     }
     $market = getdbo('db_markets', getiparam('id'));
     $coin = getdbo('db_coins', $market->coinid);
     $amount = getparam('amount');
     $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
     $info = $remote->getinfo();
     if (!$info || !$info['balance']) {
         return false;
     }
     $deposit_info = $remote->validateaddress($market->deposit_address);
     if (!$deposit_info || !isset($deposit_info['isvalid']) || !$deposit_info['isvalid']) {
         user()->setFlash('error', "invalid address {$coin->name}, {$market->deposit_address}");
         $this->redirect(array('site/coin', 'id' => $coin->id));
     }
     $amount = min($amount, $info['balance'] - $info['paytxfee']);
     //		$amount = max($amount, $info['balance'] - $info['paytxfee']);
     $amount = round($amount, 8);
     debuglog("selling ({$market->deposit_address}, {$amount})");
     $tx = $remote->sendtoaddress($market->deposit_address, $amount);
     if (!$tx) {
         user()->setFlash('error', $remote->error);
         $this->redirect(array('site/coin', 'id' => $coin->id));
     }
     $exchange = new db_exchange();
     $exchange->market = $market->name;
     $exchange->coinid = $coin->id;
     $exchange->send_time = time();
     $exchange->quantity = $amount;
     $exchange->price_estimate = $coin->price;
     $exchange->status = 'waiting';
     $exchange->tx = $tx;
     $exchange->save();
     $this->redirect(array('site/coin', 'id' => $coin->id));
 }
コード例 #14
0
 public function postRegister()
 {
     $rules = array('email' => 'required|email|unique:users', 'password' => 'required|confirmed');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return array('success' => false, 'errors' => $validator->messages()->toJson());
     } else {
         $user = new User();
         $user->password = Hash::make(Input::get('password'));
         $user->email = Input::get('email');
         $user->deposit_btc_address = Bitcoin::createAddress();
         $user->save();
         Auth::loginUsingId($user->id);
         return array('success' => true);
     }
 }
コード例 #15
0
ファイル: Bet.php プロジェクト: mdominoni/binarybtc
 public function handleWinner()
 {
     if ($this->winner_paid) {
         return false;
     }
     $btc_price = Bitcoin::toUSD();
     if ($this->type == 'above') {
         $winner = $btc_price > $this->target_price ? $this->created_by_user_id : $this->accepted_by_user_id;
     } else {
         if ($this->type == 'under') {
             $winner = $btc_price < $this->target_price ? $this->created_by_user_id : $this->accepted_by_user_id;
         }
     }
     $this->winner_user_id = $winner;
     $winnings = (1 - Config::get('bitcoin.winnings_fee')) * (intval($this->bet_amount) + intval($this->cross_bet_amount));
     $winner_model = User::where('id', $winner)->first();
     $winner_model->addToBalance($winnings);
     Notify::alert("User {$winner} paid " . Bitcoin::toBTC($winnings) . " BTC");
     $this->winner_paid = 1;
     $this->save();
     return true;
 }
コード例 #16
0
ファイル: Coin.php プロジェクト: kartx22/Otoru-Dice
 public static function DiceGame($name, $coinCode)
 {
     $wallet_address = strtolower(strtolower($coinCode)) . "_wallet_address";
     $data['banner'] = URL::to('public/images/' . strtolower($coinCode) . '.png');
     $data['balance'] = User::Balance($coinCode);
     $data['coin'] = $coinCode;
     $data['title'] = $name;
     if ($coinCode == 'BTC') {
         $data['bankRoll'] = Bitcoin::CurrentPot();
     } else {
         if ($coinCode == 'AUR') {
             $data['bankRoll'] = Auroracoin::CurrentPot();
         }
     }
     if (!Auth::guest() && !Auth::user()->{$wallet_address}) {
         //$data['alert'] = "You currently don't have a wallet!!<br> Go to your <a href='account'>account</a> to make one.";
     }
     if (Session::get('alert')) {
         $data['alert'] = Session::get('alert');
     }
     return $data;
 }
コード例 #17
0
ファイル: login.php プロジェクト: vipjeffreylee/qt_wallet
    $host = $use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST']) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
    $host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
    return $host;
}
function full_url($s, $use_forwarded_host = false)
{
    return url_origin($s, $use_forwarded_host) . $s['REQUEST_URI'];
}
$absolute_url = full_url($_SERVER);
//End code adapted from http://stackoverflow.com/questions/6768793/get-the-full-url-in-php
if (isset($LOGIN_PAGE_DOMAIN_AND_PATH)) {
    $absolute_url = $LOGIN_PAGE_DOMAIN_AND_PATH;
}
// Using EasyBitcoin RPC client from https://github.com/aceat64/EasyBitcoin-PHP
require_once "includes/easybitcoin.php";
$bitshares = new Bitcoin($RPC_SERVER_USER, $RPC_SERVER_PASS, $RPC_SERVER_ADDRESS, $RPC_SERVER_PORT, $RPC_SERVER_PATH);
$bitshares->open($RPC_SERVER_WALLET);
$bitshares->unlock(2, $RPC_SERVER_WALLET_PASS);
if (isset($_REQUEST["client_key"])) {
    $loginPackage = $bitshares->wallet_login_finish($_REQUEST["server_key"], $_REQUEST["client_key"], $_REQUEST["signed_secret"]);
    if ($loginPackage == false) {
        echo "Sorry, your login session has expired. Redirecting you to login again.<script type='text/javascript'>setTimeout(function(){location.href='{$_SERVER['PHP_SELF']}'}, 3000)</script>";
        return;
    }
    $userAccount = $bitshares->blockchain_get_account($loginPackage["user_account_key"]);
    echo "Welcome, {$_REQUEST['client_name']}! You are now logged in.<br/>";
    if (isset($userAccount["public_data"]["gravatarID"])) {
        echo "<img src='http://www.gravatar.com/avatar/{$userAccount["public_data"]["gravatarID"]}' />";
    }
    if (isset($userAccount["delegate_info"])) {
        echo "<p>This is the VIP section, for delegates only.</p>";
コード例 #18
0
ファイル: payment.php プロジェクト: zarethernet/yaamp
function BackendCoinPayments($coin)
{
    //	debuglog("BackendCoinPayments $coin->symbol");
    $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
    $info = $remote->getinfo();
    if (!$info) {
        debuglog("{$coin->symbol} cant connect to coin");
        return;
    }
    $min = 0.001;
    // 	if(date("w", time()) == 0 && date("H", time()) > 12)		// sunday afternoon
    // 		$min = 0.0001;
    $users = getdbolist('db_accounts', "balance>{$min} and coinid={$coin->id}");
    if ($coin->symbol == 'MUE' || $coin->symbol == 'DIME') {
        foreach ($users as $user) {
            $user = getdbo('db_accounts', $user->id);
            if (!$user) {
                continue;
            }
            $amount = $user->balance;
            while ($user->balance > $min && $amount > $min) {
                debuglog("{$coin->symbol} sendtoaddress {$user->username} {$amount}");
                $tx = $remote->sendtoaddress($user->username, round($amount, 8));
                if (!$tx) {
                    debuglog("error {$remote->error}, {$user->username}, {$amount}");
                    if ($remote->error == 'transaction too large' || $remote->error == 'invalid amount') {
                        $amount /= 2;
                        continue;
                    }
                    break;
                }
                $payout = new db_payouts();
                $payout->account_id = $user->id;
                $payout->time = time();
                $payout->amount = bitcoinvaluetoa($amount);
                $payout->fee = 0;
                $payout->tx = $tx;
                $payout->save();
                $user->balance -= $amount;
                $user->save();
            }
        }
        debuglog("payment done");
        return;
    }
    $total_to_pay = 0;
    $addresses = array();
    foreach ($users as $user) {
        $total_to_pay += round($user->balance, 8);
        $addresses[$user->username] = round($user->balance, 8);
    }
    if (!$total_to_pay) {
        //	debuglog("nothing to pay");
        return;
    }
    if ($info['balance'] - 0.001 < $total_to_pay) {
        debuglog("{$coin->symbol} wallet insufficient funds for payment {$info['balance']} < {$total_to_pay}");
        return;
    }
    if ($coin->symbol == 'BTC') {
        global $cold_wallet_table;
        $balance = $info['balance'];
        $stats = getdbosql('db_stats', "1 order by time desc");
        $renter = dboscalar("select sum(balance) from renters");
        $pie = $balance - $total_to_pay - $renter - 1;
        debuglog("pie to split is {$pie}");
        if ($pie > 0) {
            foreach ($cold_wallet_table as $coldwallet => $percent) {
                $coldamount = round($pie * $percent, 8);
                if ($coldamount < $min) {
                    break;
                }
                debuglog("paying cold wallet {$coldwallet} {$coldamount}");
                $addresses[$coldwallet] = $coldamount;
                $total_to_pay += $coldamount;
            }
        }
    }
    debuglog("paying {$total_to_pay} {$coin->symbol} min is {$min}");
    $tx = $remote->sendmany('', $addresses, 1, '');
    if (!$tx) {
        debuglog($remote->error);
        return;
    }
    foreach ($users as $user) {
        $user = getdbo('db_accounts', $user->id);
        if (!$user) {
            continue;
        }
        $payout = new db_payouts();
        $payout->account_id = $user->id;
        $payout->time = time();
        $payout->amount = bitcoinvaluetoa($user->balance);
        $payout->fee = 0;
        $payout->tx = $tx;
        $payout->save();
        $user->balance = 0;
        $user->save();
    }
    debuglog("payment done");
    sleep(5);
}
コード例 #19
0
$rpcPort = 10086;
$abort = false;
$numAddresses = 100;
$txBufferSize = 150;
$resume = "{$rpcUser}-{$rpcPort}-tally.dat";
if (!isset($argv[1])) {
    die("Usage: php {$argv[0]} <output filename>\n");
}
function handleInt()
{
    global $abort;
    $abort = true;
}
pcntl_signal(SIGINT, 'handleInt');
require_once 'easybitcoin.php';
$rpc = new Bitcoin($rpcUser, $rpcPass, $rpcHost, $rpcPort);
$numBlocks = $rpc->getinfo()['blocks'];
if ($rpc->status !== 200 && $rpc->error !== '') {
    die("Failed to connect. Check your coin's .conf file and your RPC parameters.\n");
}
$i = $txTotal = 0;
if (file_exists($resume)) {
    $tally = unserialize(file_get_contents($resume));
    if ($tally['tally'] === true) {
        if ($numBlocks > $tally['last']) {
            $i = $tally['last'];
            $txTotal = $tally['txTotal'];
            $addresses = $tally['addresses'];
            $numAddresses = $tally['numAddresses'];
            echo "resuming from block {$i} - ";
        } else {
コード例 #20
0
ファイル: Bitcoin.php プロジェクト: mdominoni/binarybtc
 public static function toUSD($amount = 100000000, $satoshi = true)
 {
     $USDPerBTC = Cache::get('bitcoin_price');
     return $satoshi ? $USDPerBTC * Bitcoin::toBTC($amount) : $USDPerBTC * $amount;
 }
コード例 #21
0
ファイル: receive_bitcoin.php プロジェクト: MirellJ/wlox-cron
#!/usr/bin/php
<?php 
echo "Beginning Receive Bitcoin processing..." . PHP_EOL;
include 'common.php';
$CFG->session_active = true;
$transactions_dir = $CFG->dirroot . 'transactions/';
$total_received = 0;
$bitcoin = new Bitcoin($CFG->bitcoin_username, $CFG->bitcoin_passphrase, $CFG->bitcoin_host, $CFG->bitcoin_port, $CFG->bitcoin_protocol);
$bitcoin->settxfee($CFG->bitcoin_sending_fee);
$transactions = scandir($transactions_dir);
if (!$transactions) {
    echo 'done' . PHP_EOL;
    exit;
}
$email = SiteEmail::getRecord('new-deposit');
$sql = "SELECT transaction_id, id FROM requests WHERE request_status != {$CFG->request_completed_id} AND currency = {$CFG->btc_currency_id} AND request_type = {$CFG->request_deposit_id} ";
$result = db_query_array($sql);
if ($result) {
    foreach ($result as $row) {
        $requests[$row['transaction_id']] = $row['id'];
    }
}
$sql = "SELECT id, transaction_id FROM bitcoind_log ORDER BY `date` DESC LIMIT 0,100 ";
$result = db_query_array($sql);
if ($result) {
    foreach ($result as $row) {
        $transaction_log[$row['transaction_id']] = $row['id'];
    }
}
$addresses = array();
$user_balances = array();
コード例 #22
0
ファイル: blocks.php プロジェクト: Excalibur201010/yiimp
function MonitorBTC()
{
    //	debuglog(__FUNCTION__);
    $coin = getdbosql('db_coins', "symbol='BTC'");
    if (!$coin) {
        return;
    }
    $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
    if (!$remote) {
        return;
    }
    $mostrecent = 0;
    if ($coin->lastblock == null) {
        $coin->lastblock = '';
    }
    $list = $remote->listsinceblock($coin->lastblock);
    if (!$list) {
        return;
    }
    $coin->lastblock = $list['lastblock'];
    $coin->save();
    foreach ($list['transactions'] as $transaction) {
        if (!isset($transaction['blockhash'])) {
            continue;
        }
        if ($transaction['confirmations'] == 0) {
            continue;
        }
        if ($transaction['category'] != 'send') {
            continue;
        }
        if ($transaction['fee'] != -0.0001) {
            continue;
        }
        debuglog(__FUNCTION__);
        debuglog($transaction);
        $txurl = "https://blockchain.info/tx/{$transaction['txid']}";
        $b = mail(YAAMP_ADMIN_EMAIL, "withdraw {$transaction['amount']}", "<a href='{$txurl}'>{$transaction['address']}</a>");
        if (!$b) {
            debuglog('error sending email');
        }
    }
}
コード例 #23
0
ファイル: coin.php プロジェクト: Bitcoinsulting/yiimp
echo "<br>";
echo "<div class='main-left-box'>";
echo "<div class='main-left-title'>{$coin->name} Explorer</div>";
echo "<div class='main-left-inner'>";
echo "<table  class='dataGrid2'>";
echo "<thead>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Height</th>";
echo "<th>Diff</th>";
echo "<th>Transactions</th>";
echo "<th>Confirmations</th>";
echo "<th>Blockhash</th>";
echo "</tr>";
echo "</thead>";
$remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
for ($i = $coin->block_height; $i > $coin->block_height - 25; $i--) {
    $hash = $remote->getblockhash($i);
    if (!$hash) {
        continue;
    }
    $block = $remote->getblock($hash);
    if (!$block) {
        continue;
    }
    $d = datetoa2($block['time']);
    $confirms = isset($block['confirmations']) ? $block['confirmations'] : '';
    $tx = count($block['tx']);
    $diff = $block['difficulty'];
    //	debuglog($block);
    echo "<tr class='ssrow'>";
コード例 #24
0
ファイル: tx.php プロジェクト: zarethernet/yaamp
<?php

$remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
echo "<table class='dataGrid2'>";
echo "<thead>";
echo "<tr>";
echo "<th>Transaction Hash</th>";
echo "<th>Value</th>";
echo "<th>From (amount)</th>";
echo "<th>To (amount)</th>";
echo "</tr>";
echo "</thead>";
$tx = $remote->getrawtransaction($txhash, 1);
if (!$tx) {
    continue;
}
$valuetx = 0;
foreach ($tx['vout'] as $vout) {
    $valuetx += $vout['value'];
}
echo "<tr class='ssrow'>";
echo "<td><span style='font-family: monospace;'><a href='/explorer?id={$coin->id}&txid={$tx['txid']}'>{$tx['txid']}</a></span></td>";
echo "<td>{$valuetx}</td>";
echo "<td>";
foreach ($tx['vin'] as $vin) {
    if (isset($vin['coinbase'])) {
        echo "Generation";
    }
}
echo "</td>";
echo "<td>";
コード例 #25
0
ファイル: singularity.php プロジェクト: rexquigg/singularity
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/
require_once 'bitcoin.inc';
$common6 = file_get_contents('common6.txt');
$bitcoin = new Bitcoin();
function find_address($seeking)
{
    global $bitcoin;
    $decoded = $bitcoin->decodeBase58($seeking);
    if (!$decoded) {
        return false;
        //"invalid characters";
    }
    $length = strlen($decoded);
    if (!($length == 50)) {
        return false;
        //$length." data length impossible";
    }
    $hash160 = substr($decoded, 2, 40);
    return $bitcoin->hash160ToAddress($hash160);
コード例 #26
0
ファイル: tx.php プロジェクト: Bitcoinsulting/yiimp
echo "<div class='main-left-title'>Transactions from {$renter->address}</div>";
echo "<div class='main-left-inner'>";
echo "<table class='dataGrid2'>";
echo "<thead class=''>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Amount</th>";
echo "<th>Confirmations</th>";
echo "<th>Tx</th>";
echo "</tr>";
echo "</thead><tbody>";
$btc = getdbosql('db_coins', "symbol='BTC'");
if (!$btc) {
    return;
}
$remote = new Bitcoin($btc->rpcuser, $btc->rpcpasswd, $btc->rpchost, $btc->rpcport);
$ts = $remote->listtransactions(yaamp_renter_account($renter), 10);
$res_array = array();
foreach ($ts as $val) {
    $t = $val['time'];
    if ($t < $renter->created) {
        continue;
    }
    $res_array[$t] = $val;
}
krsort($res_array);
$total = 0;
foreach ($res_array as $transaction) {
    if ($transaction['category'] != 'receive') {
        continue;
    }
コード例 #27
0
ファイル: User.php プロジェクト: MirellJ/wlox-api
 public static function registerNew($info)
 {
     global $CFG;
     if (!is_array($info)) {
         return false;
     }
     $info['email'] = preg_replace("/[^0-9a-zA-Z@\\.\\!#\$%\\&\\*+_\\~\\?\\-]/", "", $info['email']);
     $exist_id = self::userExists($info['email']);
     if ($exist_id > 0) {
         $user_info = DB::getRecord('site_users', $exist_id, 0, 1);
         $email = SiteEmail::getRecord('register-existing');
         Email::send($CFG->form_email, $info['email'], $email['title'], $CFG->form_email_from, false, $email['content'], $user_info);
         return false;
     }
     $new_id = self::getNewId();
     if ($new_id > 0) {
         $sql = 'SELECT id FROM fee_schedule ORDER BY from_usd ASC LIMIT 0,1';
         $result = db_query_array($sql);
         $pass1 = self::randomPassword(12);
         //$info['first_name'] = preg_replace("/[^\pL a-zA-Z0-9@\s\._-]/u", "",$info['first_name']);
         //$info['last_name'] = preg_replace("/[^\pL a-zA-Z0-9@\s\._-]/u", "",$info['last_name']);
         //$info['country'] = preg_replace("/[^0-9]/", "",$info['country']);
         $info['user'] = $new_id;
         $info['pass'] = Encryption::hash($pass1);
         $info['date'] = date('Y-m-d H:i:s');
         $info['confirm_withdrawal_email_btc'] = 'Y';
         $info['confirm_withdrawal_email_bank'] = 'Y';
         $info['notify_deposit_btc'] = 'Y';
         $info['notify_deposit_bank'] = 'Y';
         $info['notify_withdraw_btc'] = 'Y';
         $info['notify_withdraw_bank'] = 'Y';
         $info['notify_login'] = '******';
         $info['no_logins'] = 'Y';
         $info['fee_schedule'] = $result[0]['id'];
         $info['default_currency'] = preg_replace("/[^0-9]/", "", $info['default_currency']);
         unset($info['terms']);
         $record_id = db_insert('site_users', $info);
         require_once '../lib/easybitcoin.php';
         $bitcoin = new Bitcoin($CFG->bitcoin_username, $CFG->bitcoin_passphrase, $CFG->bitcoin_host, $CFG->bitcoin_port, $CFG->bitcoin_protocol);
         $new_address = $bitcoin->getnewaddress($CFG->bitcoin_accountname);
         db_insert('bitcoin_addresses', array('address' => $new_address, 'site_user' => $record_id, 'date' => date('Y-m-d H:i:s')));
         $info['pass'] = $pass1;
         $email = SiteEmail::getRecord('register');
         Email::send($CFG->form_email, $info['email'], $email['title'], $CFG->form_email_from, false, $email['content'], $info);
         if ($CFG->email_notify_new_users) {
             $email = SiteEmail::getRecord('register-notify');
             $info['pass'] = false;
             Email::send($CFG->form_email, $CFG->support_email, $email['title'], $CFG->form_email_from, false, $email['content'], $info);
         }
         return true;
     }
 }
コード例 #28
0
ファイル: tx.php プロジェクト: neofutur/BitPing.Net
<?php

require "system/shared.php";
if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1") {
    die;
}
$arr = json_decode(file_get_contents('php://input'));
$data = $arr->params;
$bc = new Bitcoin();
$db = Database::getInstance();
$confirmations = 0;
foreach ($data as $tx) {
    $outputs = $tx->out;
    foreach ($outputs as $output) {
        $btc = $output->value;
        $value = $btc * 100000000;
        $script = $output->scriptPubKey;
        $scriptparts = explode(" ", $script);
        $hash = "";
        for ($i = 0; $i < count($scriptparts); $i++) {
            if ($scriptparts[$i] == "OP_HASH160") {
                $hash = $scriptparts[$i + 1];
                break;
            }
        }
        if ($hash != "") {
            $address = $bc->hash160ToAddress($hash);
            $txhash = $tx->hash;
            /*
                                    $stmt = $db->prepare("INSERT INTO `unconfirmed_tx` (`txhash`, `to`, `value`, `timestamp`) VALUES (?, ?, ?, NOW())");
                                    $stmt->bind_param('ssi', $txhash, $address, $value);
コード例 #29
0
 public function actionWithdraw()
 {
     $fees = 0.0001;
     $deposit = user()->getState('yaamp-deposit');
     if (!$deposit) {
         $this->render('login');
         return;
     }
     $renter = getrenterparam($deposit);
     if (!$renter) {
         $this->render('login');
         return;
     }
     $amount = getparam('withdraw_amount');
     $address = getparam('withdraw_address');
     $amount = floatval(bitcoinvaluetoa(min($amount, $renter->balance - $fees)));
     if ($amount < 0.001) {
         user()->setFlash('error', 'Minimum withdraw is 0.001');
         $this->redirect("/renting");
         return;
     }
     $coin = getdbosql('db_coins', "symbol='BTC'");
     if (!$coin) {
         return;
     }
     $remote = new Bitcoin($coin->rpcuser, $coin->rpcpasswd, $coin->rpchost, $coin->rpcport);
     $res = $remote->validateaddress($address);
     if (!$res || !isset($res['isvalid']) || !$res['isvalid']) {
         user()->setFlash('error', 'Invalid address');
         $this->redirect("/renting");
         return;
     }
     $rentertx = new db_rentertxs();
     $rentertx->renterid = $renter->id;
     $rentertx->time = time();
     $rentertx->amount = $amount;
     $rentertx->type = 'withdraw';
     $rentertx->address = $address;
     $rentertx->tx = 'scheduled';
     $rentertx->save();
     debuglog("withdraw scheduled {$renter->id} {$renter->address}, {$amount} to {$address}");
     user()->setFlash('message', "withdraw scheduled");
     $this->redirect("/renting");
 }
コード例 #30
0
/**
 * Connects to Bitcoin daemon and retrieves information, then writes to cache
 *
 * @param string $from_cache Whether to get the data from cache or not
 *
 * @return array
 */
function getData($from_cache = false)
{
    global $config;
    global $cache_message;
    // If we're getting data from cache, do it
    if ($from_cache === true && is_file($config['cache_file'])) {
        $cache = json_decode(file_get_contents($config['cache_file']), true);
        // Only proceed if the array is a cache - invalid otherwise
        if (is_array($cache)) {
            if ($cache['config_hash'] == md5(json_encode($config))) {
                if (time() < $cache['cache_expiry']) {
                    return $cache;
                }
            } else {
                $cache_message = 'Configuration has changed, cache has been refreshed.';
            }
        }
    }
    // Include EasyBitcoin library and set up connection
    include_once './php/easybitcoin.php';
    $bitcoin = new Bitcoin($config['rpc_user'], $config['rpc_pass'], $config['rpc_host'], $config['rpc_port']);
    // Setup SSL if configured
    if ($config['rpc_ssl'] === true) {
        $bitcoin->setSSL($config['rpc_ssl_ca']);
    }
    // Get info
    $data = $bitcoin->getinfo();
    // Handle errors if they happened
    if (!$data) {
        $return_data['error'] = $bitcoin->error;
        $return_data['status'] = $bitcoin->status;
        writeToCache($return_data);
        return $return_data;
    }
    // Get free disk space
    if ($config['display_free_disk_space'] === true) {
        $data['free_disk_space'] = getFreeDiskSpace();
    }
    if (isset($config['display_ip']) && $config['display_ip'] === true) {
        // Use bitcoind IP
        if ($config['use_bitcoind_ip'] === true) {
            $net_info = $bitcoin->getnetworkinfo();
            $data['node_ip'] = $net_info['localaddresses'][0]['address'];
        } else {
            $data['node_ip'] = $_SERVER['SERVER_ADDR'];
        }
    }
    // Add peer info
    if ($config['display_peer_info'] === true) {
        $data['peers'] = parsePeers($bitcoin->getpeerinfo());
    }
    // Node geolocation
    if ($config['display_ip_location'] === true && $config['display_ip'] === true) {
        $data['ip_location'] = getGeolocation($data['node_ip'], 'all');
    }
    // Bitcoin Daemon uptime
    if ($config['display_bitcoind_uptime'] === true || strcmp(PHP_OS, "Linux") == 0) {
        $data['bitcoind_uptime'] = getProcessUptime($config['bitcoind_process_name']);
    }
    // Get max height from bitnodes.21.co
    if ($config['display_max_height'] === true) {
        $bitnodes_ch = curl_init();
        curl_setopt($bitnodes_ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($bitnodes_ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($bitnodes_ch, CURLOPT_USERAGENT, 'Bitcoin Node Status Page');
        curl_setopt($bitnodes_ch, CURLOPT_URL, "https://bitnodes.21.co/api/v1/snapshots/");
        $exec_result = json_decode(curl_exec($bitnodes_ch), true);
        // Don't close handle if we reuse it
        if ($config['display_bitnodes_info'] !== true) {
            curl_close($bitnodes_ch);
        }
        $data['max_height'] = $exec_result['results'][0]['latest_height'];
        $data['node_height_percent'] = round($data['blocks'] / $data['max_height'] * 100, 1);
    }
    // Get node info from bitnodes.21.co
    if ($config['display_bitnodes_info'] === true) {
        if ($bitnodes_ch === false) {
            $bitnodes_ch = curl_init();
            curl_setopt($bitnodes_ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($bitnodes_ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($bitnodes_ch, CURLOPT_USERAGENT, 'Bitcoin Node Status Page');
        }
        // Get node info
        curl_setopt($bitnodes_ch, CURLOPT_URL, "https://getaddr.bitnodes.21.co/api/v1/nodes/" . $data['node_ip'] . "-8333/");
        $data['bitnodes_info'] = json_decode(curl_exec($bitnodes_ch), true);
        // Get latency info
        curl_setopt($bitnodes_ch, CURLOPT_URL, "https://getaddr.bitnodes.21.co/api/v1/nodes/" . $data['node_ip'] . "-8333/latency/");
        $latency = json_decode(curl_exec($bitnodes_ch), true);
        $data['bitnodes_info']['latest_latency'] = $latency['daily_latency'][0];
    }
    // Get chart data
    if ($config['display_chart'] === true & is_file($config['stats_file'])) {
        $data['chart'] = json_decode(file_get_contents($config['stats_file']), true);
    }
    writeToCache($data);
    return $data;
}