示例#1
0
function getBalance($address, \DateInterval $maxCacheAge = null)
{
    if (empty($address) || trim($address) == '') {
        throw new InvalidAddress("Empty string/value is not valid");
    }
    $satoshis = null;
    $updatedAt = null;
    $needsUpdated = false;
    try {
        $row = DB\selectExactlyOne('bitcoin_addresses', 'address = ?', array($address));
        $satoshis = intval($row['satoshis']);
        if ($maxCacheAge) {
            $updatedAt = new DateTime($row['updated_at']);
            $expiresAt = $updatedAt->add($maxCacheAge);
            $now = new DateTime('now');
            if ($expiresAt->getTimestamp() < $now->getTimestamp()) {
                $needsUpdated = true;
            }
        }
    } catch (DB\NoMatchingRecords $_) {
        $needsUpdated = true;
    }
    if ($needsUpdated) {
        # Since we don't want to have two or three (or more) processes all trying to query
        # Blockchain.info at the same time, we use a lock to assure only one attempt is made
        # to update the cache.
        $lockObtained = withLock($address, function () use($address) {
            $satoshis = BlockchainDotInfo\getBalanceInSatoshis($address);
            cacheBalance($address, $satoshis);
        });
        if (!$lockObtained) {
            if ($satoshis === null) {
                Log\error("Failed to obtain lock for and no cached balance exists for Bitcoin address " . "{$address}; defaulting to zero");
            }
            $oneHourAgo = new DateTime('1 hour ago');
            if ($updatedAt && $updatedAt->getTimestamp() < $oneHourAgo->getTimestamp()) {
                Log\error("Balance for Bitcoin address {$address} has not been updated for " . "more than one hour");
            }
        }
    }
    //  $btcBalance = $satoshis / satoshisPerBTC();
    //  $balanceWithPrecision = $currency == 'BTC' ? $btcBalance : fromBTC($btcBalance, $currency);
    //  return $balanceWithPrecision;
    return new AmountOfBitcoin($satoshis);
}
 private function getCountryCodeForIP()
 {
     try {
         $ip = $_SERVER['REMOTE_ADDR'];
         $rawJSON = HttpSimple\get('https://freegeoip.net/json/' . $ip);
         $info = json_decode($rawJSON);
         if (!is_object($info) || !isset($info->country_code)) {
             Log\warn("Web-service at FreeGeoIP.net did not return expected value for IP address {$ip}");
             return null;
         } else {
             return $info->country_code;
         }
     } catch (\SpareParts\WebClient\NetworkError $e) {
         Log\error("Network error occurred when attempting to lookup IP adress info: " . $e->getMessage());
         return null;
     }
 }