/** * @param $str string * @param $frombase int * @param $tobase int * * @return string * * Converts integers from base to another. */ public static function baseConvert($str, $frombase = 10, $tobase = 36) { $str = trim($str); if (intval($frombase) != 10) { $len = strlen($str); $q = 0; for ($i = 0; $i < $len; $i++) { $r = base_convert($str[$i], $frombase, 10); $q = bcadd(bcmul($q, $frombase), $r); } } else { $q = $str; } if (intval($tobase) != 10) { $s = ''; while (bccomp($q, '0', 0) > 0) { $r = intval(bcmod($q, $tobase)); $s = base_convert($r, 10, $tobase) . $s; $q = bcdiv($q, $tobase, 0); } } else { $s = $q; } return $s; }
/** * Replace bcpowmod() * * @category PHP * @package PHP_Compat * @license LGPL - http://www.gnu.org/licenses/lgpl.html * @copyright 2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**> * @link http://php.net/function.bcpowmod * @author Sara Golemon <*****@*****.**> * @version $Revision: 1.1 $ * @since PHP 5.0.0 * @require PHP 4.0.0 (user_error) */ function php_compat_bcpowmod($x, $y, $modulus, $scale = 0) { // Sanity check if (!is_scalar($x)) { user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING); return false; } if (!is_scalar($y)) { user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING); return false; } if (!is_scalar($modulus)) { user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING); return false; } if (!is_scalar($scale)) { user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING); return false; } $t = '1'; while (bccomp($y, '0')) { if (bccomp(bcmod($y, '2'), '0')) { $t = bcmod(bcmul($t, $x), $modulus); $y = bcsub($y, '1'); } $x = bcmod(bcmul($x, $x), $modulus); $y = bcdiv($y, '2'); } return $t; }
function bcinvert($a, $n) { // Sanity check if (!is_scalar($a)) { user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING); return false; } if (!is_scalar($n)) { user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING); return false; } $u1 = $v2 = '1'; $u2 = $v1 = '0'; $u3 = $n; $v3 = $a; while (bccomp($v3, '0')) { $q0 = bcdiv($u3, $v3); $t1 = bcsub($u1, bcmul($q0, $v1)); $t2 = bcsub($u2, bcmul($q0, $v2)); $t3 = bcsub($u3, bcmul($q0, $v3)); $u1 = $v1; $u2 = $v2; $u3 = $v3; $v1 = $t1; $v2 = $t2; $v3 = $t3; } if (bccomp($u2, '0') < 0) { return bcadd($u2, $n); } else { return bcmod($u2, $n); } }
function getStateTaxPayable() { //Arizona is a percent of federal tax rate. //However after 01-Jul-10 it changed to a straight percent of gross. $annual_income = $this->getAnnualTaxableIncome(); $rate = $this->getUserValue1(); Debug::text('Raw Rate: ' . $rate, __FILE__, __LINE__, __METHOD__, 10); //Because of the change from a percent of federal rate to a gross rate, //add some checks so if an employee's amount isn't changed we default to the closest rate. if ($rate >= 39.5) { $rate = 5.1; } elseif ($rate >= 33.1) { $rate = 4.2; } elseif ($rate >= 26.7) { $rate = 3.6; } elseif ($rate >= 24.5) { $rate = 2.7; } elseif ($rate >= 20.3) { $rate = 1.8; } elseif ($rate >= 10.7) { $rate = 1.3; } Debug::text(' Adjusted Rate: ' . $rate, __FILE__, __LINE__, __METHOD__, 10); $retval = bcmul($annual_income, bcdiv($rate, 100)); if ($retval < 0) { $retval = 0; } Debug::text('State Annual Tax Payable: ' . $retval, __FILE__, __LINE__, __METHOD__, 10); return $retval; }
public static function checkAddress($address) { $origbase58 = $address; $dec = "0"; for ($i = 0; $i < strlen($address); $i++) { $dec = bcadd(bcmul($dec, "58", 0), strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", substr($address, $i, 1)), 0); } $address = ""; while (bccomp($dec, 0) == 1) { $dv = bcdiv($dec, "16", 0); $rem = (int) bcmod($dec, "16"); $dec = $dv; $address = $address . substr("0123456789ABCDEF", $rem, 1); } $address = strrev($address); for ($i = 0; $i < strlen($origbase58) && substr($origbase58, $i, 1) == "1"; $i++) { $address = "00" . $address; } if (strlen($address) % 2 != 0) { $address = "0" . $address; } if (strlen($address) != 50) { return false; } if (hexdec(substr($address, 0, 2)) > 0) { return false; } return substr(strtoupper(hash("sha256", hash("sha256", pack("H*", substr($address, 0, strlen($address) - 8)), true))), 0, 8) == substr($address, strlen($address) - 8); }
public static function makeLine($data, $do, &$errors) { //net value is unit-price * quantity if (!isset($data['tax_value'])) { //tax (in the UK at least) is dependent on the tax_rate of the item, and the tax status of the customer. //this function is a wrapper to a call to a config-dependent method $data['tax_percentage'] = calc_tax_percentage($data['tax_rate_id'], $data['tax_status_id'], $data['net_value']); $data['tax_value'] = round(bcmul($data['net_value'], $data['tax_percentage'], 4), 2); $data['tax_rate_percent'] = bcmul($data['tax_percentage'], 100); } else { $tax_rate = DataObjectFactory::Factory('TaxRate'); $tax_rate->load($data['tax_rate_id']); $data['tax_rate_percent'] = $tax_rate->percentage; } //gross value is net + tax; use bcadd to format the data $data['tax_value'] = bcadd($data['tax_value'], 0); $data['gross_value'] = bcadd($data['net_value'], $data['tax_value']); //then convert to the base currency if ($data['rate'] == 1) { $data['base_net_value'] = $data['net_value']; $data['base_tax_value'] = $data['tax_value']; $data['base_gross_value'] = $data['gross_value']; } else { $data['base_net_value'] = round(bcdiv($data['net_value'], $data['rate'], 4), 2); $data['base_tax_value'] = round(bcdiv($data['tax_value'], $data['rate'], 4), 2); $data['base_gross_value'] = round(bcadd($data['base_tax_value'], $data['base_net_value']), 2); } //and to the twin-currency $data['twin_net_value'] = round(bcmul($data['base_net_value'], $data['twin_rate'], 4), 2); $data['twin_tax_value'] = round(bcmul($data['base_tax_value'], $data['twin_rate'], 4), 2); $data['twin_gross_value'] = round(bcadd($data['twin_tax_value'], $data['twin_net_value']), 2); return DataObject::Factory($data, $errors, $do); }
/** * This method will multiply the two given operands with the bcmath extension * when available, otherwise it will use the default mathematical operations. * * @param string $left The left arithmetic operand. * @param string $right The right arithmetic operand. * * @return string */ public static function mul($left, $right) { if (function_exists('bcmul')) { return bcmul($left, $right); } return (string) ((int) $left * (int) $right); }
public static function ReadInt64($str, $pos) { $hi = sprintf("%u", self::ReadInt32($str, $pos)); $lo = sprintf("%u", self::ReadInt32($str, $pos + 4)); $int64 = bcadd(bcmul($hi, "4294967296"), $lo); return $int64; }
public function multiply(Number $precision, $scale = null) { $scale = $this->scale($scale); $result = bcmul($this->value, $precision->getValue(), self::MAX_PRECISION); $diff = $this->round($result, $scale); return new self($diff, $scale); }
/** * @return Twig_SimpleFunction */ public function formatAccountPerspective() : Twig_SimpleFunction { return new Twig_SimpleFunction('formatAccountPerspective', function (TransactionJournal $journal, Account $account) { $cache = new CacheProperties(); $cache->addProperty('formatAccountPerspective'); $cache->addProperty($journal->id); $cache->addProperty($account->id); if ($cache->has()) { return $cache->get(); } // get the account amount: $transactions = $journal->transactions()->where('transactions.account_id', $account->id)->get(['transactions.*']); $amount = '0'; foreach ($transactions as $transaction) { $amount = bcadd($amount, strval($transaction->amount)); } if ($journal->isTransfer()) { $amount = bcmul($amount, '-1'); } // check if this sum is the same as the journal: $journalSum = TransactionJournal::amount($journal); $full = Amount::formatJournal($journal); if (bccomp($journalSum, $amount) === 0 || bccomp(bcmul($journalSum, '-1'), $amount) === 0) { $cache->store($full); return $full; } $formatted = Amount::format($amount, true); if ($journal->isTransfer()) { $formatted = '<span class="text-info">' . Amount::format($amount) . '</span>'; } $str = $formatted . ' (' . $full . ')'; $cache->store($str); return $str; }); }
function bcfact($fact, $scale = 100) { if ($fact == 1) { return 1; } return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale); }
/** * Convert a large arbitrary number between arbitrary bases * * Works the same as the php version but supports large arbitrary numbers by using BCMath * * @see http://php.net/manual/en/function.base-convert.php * @see http://php.net/manual/en/function.base-convert.php#109660 * @param string $number * @param int $frombase * @param int $tobase * @return string */ function base_convert($number, $frombase, $tobase) { if ($frombase == $tobase) { return $number; } $number = trim($number); if ($frombase != 10) { $len = strlen($number); $fromDec = 0; for ($i = 0; $i < $len; $i++) { $v = \base_convert($number[$i], $frombase, 10); $fromDec = bcadd(bcmul($fromDec, $frombase, 0), $v, 0); } } else { $fromDec = $number; } if ($tobase != 10) { $result = ''; while (bccomp($fromDec, '0', 0) > 0) { $v = intval(bcmod($fromDec, $tobase)); $result = \base_convert($v, 10, $tobase) . $result; $fromDec = bcdiv($fromDec, $tobase, 0); } } else { $result = $fromDec; } return (string) $result; }
/** * * {@inheritDoc} * * @see \PhalconRest\Libraries\Payments\Processor::chargeCard() */ public function chargeCard($data) { // assume we use stored card for now, will support a new card soon if ($data['amount'] < 10) { throw new \Exception('Charge amount must exceed $10.'); } // convert amount to decimal // then convert to cents cuz that is what stripe wants $amount = bcmul(number_format($data['amount'], 2), 100); // set base charge data, add card on file or new card $chargeData = ["amount" => $amount, "currency" => "usd", "description" => "SMORES Payment"]; if (isset($data['card_id'])) { // verify that the external_id exists in the database $card = $this->findCard($data['card_id']); $chargeData['source'] = $data['card_id']; $chargeData['customer'] = $data['account_id']; } else { // maybe this is a one time card? $chargeData['source'] = ['address_zip' => $data['zip'], 'number' => $data['number'], 'object' => 'card', 'cvc' => $data['cvc'], 'exp_year' => $data['expiration_year'], 'exp_month' => $data['expiration_month'], 'name' => $data['name'], 'address_line1' => $data['address']]; } try { $result = \Stripe\Charge::create($chargeData); return $result->id; } catch (\Stripe\Error\Base $e) { $this->handleStripeError($e); } }
public function pay($runValidation = true) { if ($runValidation && !$this->validate()) { return false; } if ($this->_order->status !== Order::STATUS_UNPAID) { return false; } require_once Yii::getAlias('@vendor') . "/pingplusplus/pingpp-php/init.php"; \Pingpp\Pingpp::setApiKey(Yii::$app->params['pingpp.apiKey']); try { $extra = []; switch ($this->channel) { case self::CHANNEL_ALIPAY_WAP: $extra = ['success_url' => Yii::$app->request->hostInfo . '/#/order/detail/' . $this->_order->id, 'cancel_url' => Yii::$app->request->hostInfo . '/#/order/pay/' . $this->_order->id]; break; case self::CHANNEL_WX_PUB: Yii::$app->session->open(); $extra = ['open_id' => Yii::$app->session['wechatOpenid']]; break; case self::CHANNEL_ALIPAY_PC_DIRECT: $extra = ['success_url' => Yii::$app->request->hostInfo . '/#/order/detail/' . $this->_order->id]; break; default: throw new InvalidValueException('支付渠道错误!'); } $ch = \Pingpp\Charge::create(['subject' => '笑e购订单', 'body' => '笑e购(xiaoego.com)订单,订单号:' . $this->_order->order_sn, 'amount' => bcmul($this->_order->real_fee, 100), 'order_no' => $this->_order->order_sn, 'currency' => 'cny', 'extra' => $extra, 'channel' => $this->channel, 'client_ip' => Yii::$app->request->userIP, 'time_expire' => $this->_order->timeout + 1800, 'app' => ['id' => Yii::$app->params['pingpp.appId']], 'description' => mb_strlen($this->_order->description, 'UTF-8') <= 255 ? $this->_order->description : substr($this->_order->description, 0, 253) . '……']); return $ch; } catch (\Exception $e) { throw $e; } }
function Extract($j){ $bigj = strval($j); $qjr = bcadd(bcmul($this->q, $bigj), $this->r); $sjt = bcadd(bcmul($this->s, $bigj), $this->t); $d = bcdiv($qjr, $sjt); return floor($d); }
function encode_username($username) { $username = strtolower($username); $clean = ''; for ($i = 0; $i < strlen($username); $i++) { $c = ord($username[$i]); if ($c >= 97 && $c <= 122) { $clean .= chr($c); } else { if ($c >= 48 && $c <= 57) { $clean .= chr($c); } else { $clean .= ' '; } } } $clean = trim($clean); if (strlen($clean) > 12) { $clean = substr($clean, 0, 12); } $hash = '0'; for ($i = 0; $i < strlen($clean); $i++) { $c = ord($clean[$i]); $hash = bcmul($hash, 37); if ($c >= 97 && $c <= 122) { $hash = bcadd($hash, 1 + $c - 97); } else { if ($c >= 48 && $c <= 57) { $hash = bcadd($hash, 27 + $c - 48); } } } return $hash; }
/** _ \_/ |\ | /¯¯\ \ / /\ |¯¯) |_¯ \ / /¯¯\ | | |´¯|¯` | /¯¯\ |\ |5 ¯ /¯\ | \| \__/ \/ /--\ |¯¯\ |__ \/ \__/ |__ \_/ | | \__/ | \|Core. * @author: Copyright (C) 2011 by Brayan Narvaez (Prinick) developer of xNova Revolution * @link: http://www.xnovarevolution.con.ar * @package 2Moons * @author Slaver <*****@*****.**> * @copyright 2009 Lucky <*****@*****.**> (XGProyecto) * @copyright 2011 Slaver <*****@*****.**> (Fork/2Moons) * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License * @version 1.3 (2011-01-21) * @link http://code.google.com/p/2moons/ * Please do not remove the credits */ function ShowFleetTraderPage() { global $USER, $PLANET, $LNG, $CONF, $pricelist, $resource; $PlanetRess = new ResourceUpdate(); $PlanetRess->CalcResource(); $CONF['trade_allowed_ships'] = explode(',', $CONF['trade_allowed_ships']); $ID = request_var('id', 0); if (!empty($ID) && in_array($ID, $CONF['trade_allowed_ships'])) { $Count = max(min(request_var('count', '0'), $PLANET[$resource[$ID]]), 0); $PLANET['metal'] = bcadd($PLANET['metal'], bcmul($Count, bcmul($pricelist[$ID]['metal'], (double) (1 - $CONF['trade_charge'])))); $PLANET['crystal'] = bcadd($PLANET['crystal'], bcmul($Count, bcmul($pricelist[$ID]['crystal'], (double) (1 - $CONF['trade_charge'])))); $PLANET['deuterium'] = bcadd($PLANET['deuterium'], bcmul($Count, bcmul($pricelist[$ID]['deuterium'], (double) (1 - $CONF['trade_charge'])))); $PLANET['norio'] = bcadd($PLANET['norio'], bcmul($Count, bcmul($pricelist[$ID]['norio'], (double) (1 - $CONF['trade_charge'])))); $USER['darkmatter'] = bcadd($USER['darkmatter'], bcmul($Count, bcmul($pricelist[$ID]['darkmatter'], (double) (1 - $CONF['trade_charge'])))); $PlanetRess->Builded[$ID] = bcadd(bcmul('-1', $Count), $PlanetRess->Builded[$ID]); } $PlanetRess->SavePlanetToDB(); $template = new template(); $template->loadscript('fleettrader.js'); $template->execscript('updateVars();'); $Cost = array(); foreach ($CONF['trade_allowed_ships'] as $ID) { $Cost[$ID] = array($PLANET[$resource[$ID]], $pricelist[$ID]['metal'], $pricelist[$ID]['crystal'], $pricelist[$ID]['deuterium'], $pricelist[$ID]['darkmatter'], $pricelist[$ID]['norio']); } $template->assign_vars(array('tech' => $LNG['tech'], 'ft_head' => $LNG['ft_head'], 'ft_count' => $LNG['ft_count'], 'ft_max' => $LNG['ft_max'], 'ft_total' => $LNG['ft_total'], 'ft_charge' => $LNG['ft_charge'], 'ft_absenden' => $LNG['ft_absenden'], 'trade_allowed_ships' => $CONF['trade_allowed_ships'], 'CostInfos' => json_encode($Cost), 'Charge' => $CONF['trade_charge'])); $template->show("fleettrader_overview.tpl"); }
/** * Converts the currency. * * @param string $currencyFrom Currency convert from. * @param string $currencyTo Currency convert to. * @param string $amount Amount. * * @return string|false */ public function convert($currencyFrom, $currencyTo, $amount) { if (!floatval($amount) || !($rate = (new \CurrencyWebservice())->getExchangeRate($currencyFrom, $currencyTo))) { return false; } return bcmul($amount, $rate, 2); }
/** * @see http://php.net/manual/en/function.base-convert.php#106546 * * @param $numberInput * @param $fromBaseInput * @param $toBaseInput * * @return int|string */ protected static function convertBase($numberInput, $fromBaseInput, $toBaseInput) { if ($fromBaseInput == $toBaseInput) { return $numberInput; } $fromBase = str_split($fromBaseInput, 1); $toBase = str_split($toBaseInput, 1); $number = str_split($numberInput, 1); $fromLen = strlen($fromBaseInput); $toLen = strlen($toBaseInput); $numberLen = strlen($numberInput); $retval = ''; if ($toBaseInput == self::FORMAT_NUMBER) { $retval = 0; for ($i = 1; $i <= $numberLen; $i++) { $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i))); } return $retval; } if ($fromBaseInput != self::FORMAT_NUMBER) { $base10 = self::convertBase($numberInput, $fromBaseInput, self::FORMAT_NUMBER); } else { $base10 = $numberInput; } if ($base10 < strlen($toBaseInput)) { return $toBase[$base10]; } while ($base10 != '0') { $retval = $toBase[bcmod($base10, $toLen)] . $retval; $base10 = bcdiv($base10, $toLen, 0); } return $retval; }
/** * 生成UUID 单机使用 * @access public * @return string */ public static function uuid() { list($usec, $sec) = explode(" ", microtime(false)); $usec = (string) ($usec * 10000000); $timestamp = bcadd(bcadd(bcmul($sec, "10000000"), (string) $usec), "621355968000000000"); $ticks = bcdiv($timestamp, 10000); $maxUint = 4294967295; $high = bcdiv($ticks, $maxUint) + 0; $low = bcmod($ticks, $maxUint) - $high; $highBit = pack("N*", $high); $lowBit = pack("N*", $low); $guid = str_pad(dechex(ord($highBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($highBit[3])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[0])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[1])), 2, "0", STR_PAD_LEFT) . "-" . str_pad(dechex(ord($lowBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[3])), 2, "0", STR_PAD_LEFT) . "-"; $chars = "abcdef0123456789"; for ($i = 0; $i < 4; $i++) { $guid .= $chars[mt_rand(0, 15)]; } $guid .= "-"; for ($i = 0; $i < 4; $i++) { $guid .= $chars[mt_rand(0, 15)]; } $guid .= "-"; for ($i = 0; $i < 12; $i++) { $guid .= $chars[mt_rand(0, 15)]; } return $guid; }
protected static function decodeAddress($data) { $charsetHex = '0123456789ABCDEF'; $charsetB58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; $raw = "0"; for ($i = 0; $i < strlen($data); $i++) { $current = (string) strpos($charsetB58, $data[$i]); $raw = (string) bcmul($raw, "58", 0); $raw = (string) bcadd($raw, $current, 0); } $hex = ""; while (bccomp($raw, 0) == 1) { $dv = (string) bcdiv($raw, "16", 0); $rem = (int) bcmod($raw, "16"); $raw = $dv; $hex = $hex . $charsetHex[$rem]; } $withPadding = strrev($hex); for ($i = 0; $i < strlen($data) && $data[$i] == "1"; $i++) { $withPadding = "00" . $withPadding; } if (strlen($withPadding) % 2 != 0) { $withPadding = "0" . $withPadding; } return $withPadding; }
function is_prime($n, $k) { if ($n == 2) { return true; } if ($n < 2 || $n % 2 == 0) { return false; } $d = $n - 1; $s = 0; while ($d % 2 == 0) { $d /= 2; $s++; } for ($i = 0; $i < $k; $i++) { $a = rand(2, $n - 1); $x = bcpowmod($a, $d, $n); if ($x == 1 || $x == $n - 1) { continue; } for ($j = 1; $j < $s; $j++) { $x = bcmod(bcmul($x, $x), $n); if ($x == 1) { return false; } if ($x == $n - 1) { continue 2; } } return false; } return true; }
function revalue($data, &$errors = array()) { if (empty($data['transaction_date'])) { $data['transaction_date'] = date(DATE_FORMAT); } $glperiod = GLPeriod::getPeriod(fix_date($data['transaction_date'])); if (!$glperiod || count($glperiod) == 0) { $errors[] = 'No period exists for this date'; return false; } $data['value'] = bcsub($this->glbalance(), $data['new_balance']); $data['glperiods_id'] = $glperiod['id']; $data['source'] = 'C'; $data['type'] = 'V'; $data['glaccount_id'] = $this->currency_detail->writeoff_glaccount_id; $data['glcentre_id'] = $this->currency_detail->glcentre_id; GLTransaction::setTwinCurrency($data); $gl_trans[] = GLTransaction::Factory($data, $errors); $data['value'] = bcmul($data['value'], -1); $data['glaccount_id'] = $this->glaccount_id; $data['glcentre_id'] = $this->glcentre_id; GLTransaction::setTwinCurrency($data); $gl_trans[] = GLTransaction::Factory($data, $errors); $db = DB::Instance(); $db->StartTrans(); if (count($errors) == 0 && GLTransaction::saveTransactions($gl_trans, $errors)) { return $db->CompleteTrans(); } $errors[] = 'Failed to save GL Transaction'; $db->FailTrans(); $db->CompleteTrans(); return false; }
function frame($row, $column, $levelinfo, $options) { $scaledtilesize = array(bcdiv(bcsub($options["framemax"][0], $options["framemin"][0]), $levelinfo["columns"]), bcdiv(bcsub($options["framemax"][1], $options["framemin"][1]), $levelinfo["rows"])); $ret["min"] = array(bcadd(bcmul($scaledtilesize[0], $column), $options["framemin"][0]), bcadd(bcmul($scaledtilesize[1], $row), $options["framemin"][1])); $ret["max"] = array(bcadd($ret["min"][0], $scaledtilesize[0]), bcadd($ret["min"][1], $scaledtilesize[1])); return $ret; }
/** * Connect a new transaction journal to any related piggy banks. * * @param TransactionStored $event * * @return bool */ public function handle(TransactionStored $event) : bool { /** @var PiggyBankRepositoryInterface $repository */ $repository = app(PiggyBankRepositoryInterface::class); $transaction = $event->transaction; $piggyBank = $repository->find($transaction['piggy_bank_id']); // valid piggy: if (is_null($piggyBank->id)) { return true; } $amount = strval($transaction['amount']); // piggy bank account something with amount: if ($transaction['source_account_id'] == $piggyBank->account_id) { // if the source of this transaction is the same as the piggy bank, // the money is being removed from the piggy bank. So the // amount must be negative: $amount = bcmul($amount, '-1'); } $repetition = $piggyBank->currentRelevantRep(); // add or remove the money from the piggy bank: $newAmount = bcadd(strval($repetition->currentamount), $amount); $repetition->currentamount = $newAmount; $repetition->save(); // now generate a piggy bank event: PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'date' => $transaction['date'], 'amount' => $newAmount]); return true; }
public function mul($decimal) { if (!$decimal instanceof Decimal) { $decimal = new Decimal($decimal); } return new Decimal(bcmul($this->amount, $decimal->getAmount(), self::$scale)); }
protected function next($expectedtag = null) { $this->tlv($expectedtag); if ($this->constructed) { return; } else { $value = substr($this->buffer, $this->i, $this->len); if ($this->class == 0 || $this->class == 0x80) { if ($this->tag == 2 || $this->tag == 10) { # ints and enums $int = 0; foreach (str_split($value) as $byte) { $int = bcmul($int, '256', 0); $int = bcadd($int, ord($byte), 0); } $this->value = $int; } elseif ($this->tag == 1) { # boolean $this->value = ord($value) != 0; } elseif ($this->tag == 3) { # bit string $this->value = $value; } elseif ($this->tag == 5) { # null $this->value = null; } else { $this->value = $value; } } $this->i += $this->len; return $this->value; } }
function decode_base58($btcaddress) { // Compute big base58 number: $chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; $n = "0"; for ($i = 0; $i < strlen($btcaddress); $i++) { $p1 = strpos($chars, $btcaddress[$i]); if ($p1 === false) { return false; } $n = bcmul($n, "58"); $n = bcadd($n, (string) $p1); } // Peel off bytes to get checksum / hash / version: $checksum = ""; for ($i = 0; $i < 4; $i++) { $byte = bcmod($n, "256"); $checksum = chr((int) $byte) . $checksum; $n = bcdiv($n, "256"); } $hash = ""; for ($i = 0; $i < 20; $i++) { $byte = bcmod($n, "256"); $hash = chr((int) $byte) . $hash; $n = bcdiv($n, "256"); } $version = (int) $n; // Make sure checksum is correct: $check = hash('sha256', hash('sha256', chr($version) . $hash, true), true); if (substr($check, 0, 4) != $checksum) { return false; } return array($version, $hash, $checksum); }
function convBase($numberInput, $fromBaseInput, $toBaseInput) { if ($fromBaseInput == $toBaseInput) { return $numberInput; } $fromBase = str_split($fromBaseInput, 1); $toBase = str_split($toBaseInput, 1); $number = str_split($numberInput, 1); $fromLen = strlen($fromBaseInput); $toLen = strlen($toBaseInput); $numberLen = strlen($numberInput); $retval = ''; $base10 = ''; if ($toBaseInput == '0123456789') { $retval = 0; for ($i = 1; $i <= $numberLen; $i++) { $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i))); } return $retval; } if ($fromBaseInput != '0123456789') { $base10 = convBase($numberInput, $fromBaseInput, '0123456789'); } else { $base10 = $numberInput; } if ($base10 < strlen($toBaseInput)) { return $toBase[$base10]; } while ($base10 != '0') { $retval = $toBase[bcmod($base10, $toLen)] . $retval; $base10 = bcdiv($base10, $toLen, 0); } return $retval; }
function powmod($base, $exponent, $modulus) { if (function_exists('gmp_powm')) { // fast return gmp_strval(gmp_powm($base, $exponent, $modulus)); } if (function_exists('bi_powmod')) { // not tested return bi_sto_str(bi_powmod($base, $exponent, $modulus)); } if (function_exists('bcpowmod')) { // slow return bcpowmod($base, $exponent, $modulus); } // emulation, slow $square = bcmod($base, $modulus); $result = 1; while (bccomp($exponent, 0) > 0) { if (bcmod($exponent, 2)) { $result = bcmod(bcmul($result, $square), $modulus); } $square = bcmod(bcmul($square, $square), $modulus); $exponent = bcdiv($exponent, 2); } return $result; }