/** * Conver 64-bit SteamID to 32-bit SteamID * * @param string|int $userId * * @return string * @throws Exception */ public static function to32Bit($userId) { if (!function_exists('gmp_add')) { throw new Exception("GMP Library not installed. Cannot convert SteamIDs."); } return gmp_strval(gmp_sub($userId, gmp_mul(bindec(self::STEAM_ID_UPPER_BITS), "4294967296"))); }
/** * Constructor * * @param number $flags Flags * @param int $width The number of flags. If width is larger than number of * bits in $flags, zeroes are prepended to flag field. */ public function __construct($flags, $width) { if (!$width) { $this->_flags = ""; } else { // calculate number of unused bits in last octet $last_octet_bits = $width % 8; $unused_bits = $last_octet_bits ? 8 - $last_octet_bits : 0; $num = gmp_init($flags); // mask bits outside bitfield width $mask = gmp_sub(gmp_init(1) << $width, 1); $num &= $mask; // shift towards MSB if needed $data = gmp_export($num << $unused_bits, 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); $octets = unpack("C*", $data); $bits = count($octets) * 8; // pad with zeroes while ($bits < $width) { array_unshift($octets, 0); $bits += 8; } $this->_flags = pack("C*", ...$octets); } $this->_width = $width; }
function GetAuthID($i64friendID) { $tmpfriendID = $i64friendID; $iServer = "1"; if (extension_loaded('bcmath') == 1) { //decode communityid with bcmath if (bcmod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = bcsub($tmpfriendID, $iServer); if (bccomp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = bcsub($tmpfriendID, "76561197960265728"); } $tmpfriendID = bcdiv($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . $tmpfriendID; } else { if (extension_loaded('gmp') == 1) { //decode communityid with gmp if (gmp_mod($i64friendID, "2") == "0") { $iServer = "0"; } $tmpfriendID = gmp_sub($tmpfriendID, $iServer); if (gmp_cmp("76561197960265728", $tmpfriendID) == -1) { $tmpfriendID = gmp_sub($tmpfriendID, "76561197960265728"); } $tmpfriendID = gmp_div($tmpfriendID, "2"); return "STEAM_0:" . $iServer . ":" . gmp_strval($tmpfriendID); } } return false; }
function sumT($n) { if (gmp_intval($n) == 1) { return gmp_init(1); } return gmp_add(gmp_sub(gmp_pow($n, 2), gmp_pow(gmp_init(gmp_intval($n) - 1), 2)), sumT(gmp_init(gmp_intval($n) - 1))); //return gmp_mod(gmp_add(gmp_sub(gmp_mod(gmp_pow($n, 2), '1000000007'), gmp_mod(gmp_pow(gmp_init(gmp_intval($n)-1), 2), '1000000007')), sumT(gmp_init(gmp_intval($n)-1))), '1000000007'); }
public function edwards($P, $Q) { $x1 = $P[0]; $y1 = $P[1]; $x2 = $Q[0]; $y2 = $Q[1]; $t = gmp_mul($this->params['d'], gmp_mul(gmp_mul($x1, $x2), gmp_mul($y1, $y2))); $x3 = gmp_mul(gmp_add(gmp_mul($x1, $y2), gmp_mul($x2, $y1)), $this->inv(gmp_add(1, $t))); $y3 = gmp_mul(gmp_add(gmp_mul($y1, $y2), gmp_mul($x1, $x2)), $this->inv(gmp_sub(1, $t))); return array(gmp_mod($x3, $this->params['q']), gmp_mod($y3, $this->params['q'])); }
/** * Return delta to last IP address * * @return IPv6 */ public function getDelta() { if ($this->delta === null) { if ($this->prefix == 0) { $this->delta = new $this->ip_class(constant("{$this->ip_class}::MAX_INT")); } else { $this->delta = new $this->ip_class(gmp_sub(gmp_shiftl(1, constant("{$this->ip_class}::NB_BITS") - $this->prefix), 1)); } } return $this->delta; }
private function computeBaseNDigits($number, $targetBase) { $digits = array(); $length = $this->computeBaseNLength($number, $targetBase); for ($i = 0; $i < $length; $i++) { $pow = gmp_pow($targetBase, $length - $i - 1); $div = gmp_div($number, $pow, GMP_ROUND_ZERO); $number = gmp_sub($number, gmp_mul($div, $pow)); $digits[] = $div; } return array_map('gmp_strval', $digits); }
public function verifies($hash, Signature $signature) { if (extension_loaded('gmp') && USE_EXT == 'GMP') { $G = $this->generator; $n = $this->generator->getOrder(); $point = $this->point; $r = $signature->getR(); $s = $signature->getS(); if (gmp_cmp($r, 1) < 0 || gmp_cmp($r, gmp_sub($n, 1)) > 0) { return false; } if (gmp_cmp($s, 1) < 0 || gmp_cmp($s, gmp_sub($n, 1)) > 0) { return false; } $c = NumberTheory::inverse_mod($s, $n); $u1 = gmp_Utils::gmp_mod2(gmp_mul($hash, $c), $n); $u2 = gmp_Utils::gmp_mod2(gmp_mul($r, $c), $n); $xy = Point::add(Point::mul($u1, $G), Point::mul($u2, $point)); $v = gmp_Utils::gmp_mod2($xy->getX(), $n); if (gmp_cmp($v, $r) == 0) { return true; } else { return false; } } else { if (extension_loaded('bcmath') && USE_EXT == 'BCMATH') { $G = $this->generator; $n = $this->generator->getOrder(); $point = $this->point; $r = $signature->getR(); $s = $signature->getS(); if (bccomp($r, 1) == -1 || bccomp($r, bcsub($n, 1)) == 1) { return false; } if (bccomp($s, 1) == -1 || bccomp($s, bcsub($n, 1)) == 1) { return false; } $c = NumberTheory::inverse_mod($s, $n); $u1 = bcmod(bcmul($hash, $c), $n); $u2 = bcmod(bcmul($r, $c), $n); $xy = Point::add(Point::mul($u1, $G), Point::mul($u2, $point)); $v = bcmod($xy->getX(), $n); if (bccomp($v, $r) == 0) { return true; } else { return false; } } else { throw new ErrorException("Please install BCMATH or GMP"); } } }
public function kirim_chat() { $this->load->view("fungsiRSA"); /* -- keterangan Masing Masing Fungsi yang dipake dari Library gmp -- gmp_div_qr = Bagi; gmp_add = Tambah; gmp_mul = Kali; gmp_sub = Kurang; gmp_gcd = Menghitung Nilai phi; gmp_strval = Convert Nomer ke String; */ // Inisialisasi P = 113 & Q = 157 (Masing Masing adalah Bilangan Prima) <--- Lebih Besar Lebih Bagus // Menghitung N = P*Q $n = gmp_mul(113, 157); $valn = gmp_strval($n); // Menghitung Nilai M =(p-1)*(q-1) $m = gmp_mul(gmp_sub(113, 1), gmp_sub(157, 1)); // Mencari E (Kunci Public --> (e,n)) // Inisialisasi E = 5 // Membuktikan E = FPB (Faktor Persekutuan Terbesar) dari E dan M = 1 for ($e = 5; $e < 1000; $e++) { // Mencoba dengan Perulangan 1000 Kali $fpb = gmp_gcd($e, $m); if (gmp_strval($fpb) == '1') { // Jika Benar E adalah FPB dari E dan M = 1 <-- Hentikan Proses break; } } // Menghitung D (Kunci Private --> (d,n)) // D = (($m * $i) + 1) / e = $key[1] <-- Perulangan Do While $i = 1; do { $key = gmp_div_qr(gmp_add(gmp_mul($m, $i), 1), $e); $i++; if ($i == 1000) { // Dengan Perulangan 1000 Kali break; } } while (gmp_strval($key[1]) != '0'); // Hasil D = $key[0] $d = $key[0]; $vald = gmp_strval($d); $user = $this->input->post("user"); $pesan = $this->input->post("pesan"); $userid = $this->input->post("iduser"); $hasilenkripsi = enkripsi($pesan, $n, $e); $insert = "insert into chat (user,pesan,id_user) VALUES ('{$user}','{$hasilenkripsi}','{$userid}')"; $this->db->query($insert); redirect("home/ambil_pesan"); }
public function contains($x, $y) { $eq_zero = null; if (extension_loaded('gmp') && USE_EXT == 'GMP') { $eq_zero = gmp_cmp(gmp_Utils::gmp_mod2(gmp_sub(gmp_pow($y, 2), gmp_add(gmp_add(gmp_pow($x, 3), gmp_mul($this->a, $x)), $this->b)), $this->prime), 0); if ($eq_zero == 0) { return true; } else { return false; } } else { throw new ErrorException("Please install GMP"); } }
public static function sub($x, $y) { switch (self::getMode()) { case self::modeGmp: return gmp_strval(gmp_sub($x, $y)); break; case self::modeBcmath: return bcsub($x, $y); break; case self::modeNative: return $x - $y; break; } }
public function GOST_verifies($hash, Signature $signature) { if (extension_loaded('gmp') && USE_EXT == 'GMP') { $G = $this->generator; //P $n = $this->generator->getOrder(); //q $point = $this->point; //Q $r = $signature->getR(); $s = $signature->getS(); if (gmp_cmp($r, 1) < 0 || gmp_cmp($r, gmp_sub($n, 1)) > 0) { return false; } if (gmp_cmp($s, 1) < 0 || gmp_cmp($s, gmp_sub($n, 1)) > 0) { return false; } //step 3 GOST $e = gmp_Utils::gmp_mod2($hash, $n); if (gmp_cmp($e, '0') === 0) { $e = gmp_init('1'); } // step 4 GOST $v = gmp_strval(gmp_invert($e, $n)); // step 5 GOST $z1 = gmp_Utils::gmp_mod2(gmp_mul($s, $v), $n); $z2 = gmp_Utils::gmp_mod2(gmp_mul(gmp_neg($r), $v), $n); // step 6 GOST $C = Point::add(Point::mul($z1, $G), Point::mul($z2, $point)); $R = gmp_Utils::gmp_mod2($C->getX(), $n); if (0) { echo "n - " . $n . "\n"; echo "h - " . $hash . "\n"; echo "e - " . gmp_Utils::gmp_dechex($e) . "\n"; echo "v - " . gmp_Utils::gmp_dechex($v) . "\n"; echo "r - " . $r . "\n"; echo "s - " . $s . "\n"; echo "z1 - " . gmp_Utils::gmp_dechex($z1) . "\nz2 - " . gmp_Utils::gmp_dechex($z2) . "\n"; echo "Q - " . $point . "\nG - " . $G . "\n"; echo "C - " . $C . "\nR - " . $R . "\n"; } if (gmp_cmp($R, $r) == 0) { return true; } else { return false; } } else { throw new ErrorException("Please install GMP"); } }
public function __construct(\Cachet\Cache $cache, \Cachet\Locker $locker) { $this->locker = $locker; $this->cache = $cache; if (extension_loaded('bcmath')) { $this->addCallback = 'bcadd'; $this->subCallback = 'bcsub'; } elseif (extension_loaded('gmp')) { $this->addCallback = function ($a, $b) { return gmp_strval(gmp_add($a, $b)); }; $this->subCallback = function ($a, $b) { return gmp_strval(gmp_sub($a, $b)); }; } else { throw new \RuntimeException("Neither bcmath nor gmp extensions present"); } }
/** * @large */ public function testSingleBit() { $this->assertTrue(BitWiseGmp::isSingleBit(1)); $this->assertTrue(BitWiseGmp::isSingleBit("1")); $this->assertTrue(BitWiseGmp::isSingleBit(2)); $this->assertTrue(BitWiseGmp::isSingleBit("2")); $this->assertTrue(BitWiseGmp::isSingleBit(4)); $fails = [3, 5, 6, 7, 9, 10, 11, 13, 14, 15]; foreach ($fails as $checkBit) { $this->assertFalse(BitWiseGmp::isSingleBit($checkBit)); } $checkBit = 4; for ($i = 0; $i < 10000; $i++) { $checkBit = gmp_mul($checkBit, 2); $this->assertTrue(BitWiseGmp::isSingleBit($checkBit)); $this->assertFalse(BitWiseGmp::isSingleBit(gmp_sub($checkBit, 3))); } }
function summa($type) { $total_in = gmp_init('0'); $query = "\n SELECT SUM(amount) AS sum\n FROM purses\n WHERE type='{$type}'\n "; $result = do_query($query); $row = get_row($result); $v = gmp_init($row['sum']); $total_in = gmp_add($total_in, $v); $query = "\n SELECT SUM(amount) AS sum\n FROM orderbook\n WHERE type='{$type}' AND status='OPEN'\n "; $result = do_query($query); $row = get_row($result); if (isset($row['sum'])) { $v = gmp_init($row['sum']); $total_in = gmp_add($total_in, $v); } $query = "\n SELECT SUM(amount) AS sum\n FROM requests\n WHERE curr_type='{$type}' AND req_type='WITHDR' AND status='VERIFY'\n "; $result = do_query($query); $row = get_row($result); if (isset($row['sum'])) { $v = gmp_init($row['sum']); $total_in = gmp_add($total_in, $v); } $total_in = gmp_strval($total_in); $total_out = gmp_init('0'); $query = "\n SELECT SUM(amount) AS sum\n FROM requests\n WHERE curr_type='{$type}' AND req_type='DEPOS' AND status='FINAL'\n "; $result = do_query($query); $row = get_row($result); if (isset($row['sum'])) { $v = gmp_init($row['sum']); $total_out = gmp_add($total_out, $v); } $query = "\n SELECT SUM(amount) AS sum\n FROM requests\n WHERE curr_type='{$type}' AND req_type='WITHDR' AND status='FINAL'\n "; $result = do_query($query); $row = get_row($result); if (isset($row['sum'])) { $v = gmp_init($row['sum']); $total_out = gmp_sub($total_out, $v); } $total_out = gmp_strval($total_out); echo "{$type} = {$total_in}\t {$total_out}\n"; if (gmp_cmp($total_in, $total_out) != 0) { echo "*********** MISMATCH ****************\n"; } }
function recoverPubKey($r, $s, $e, $recoveryFlags, $G) { $isYEven = ($recoveryFlags & 1) != 0; $isSecondKey = ($recoveryFlags & 2) != 0; $curve = $G->getCurve(); $signature = new Signature($r, $s); // Precalculate (p + 1) / 4 where p is the field order static $p_over_four; // XXX just assuming only one curve/prime will be used if (!$p_over_four) { $p_over_four = gmp_div(gmp_add($curve->getPrime(), 1), 4); } // 1.1 Compute x if (!$isSecondKey) { $x = $r; } else { $x = gmp_add($r, $G->getOrder()); } // 1.3 Convert x to point $alpha = gmp_mod(gmp_add(gmp_add(gmp_pow($x, 3), gmp_mul($curve->getA(), $x)), $curve->getB()), $curve->getPrime()); $beta = NumberTheory::modular_exp($alpha, $p_over_four, $curve->getPrime()); // If beta is even, but y isn't or vice versa, then convert it, // otherwise we're done and y == beta. if (isBignumEven($beta) == $isYEven) { $y = gmp_sub($curve->getPrime(), $beta); } else { $y = $beta; } // 1.4 Check that nR is at infinity (implicitly done in construtor) $R = new Point($curve, $x, $y, $G->getOrder()); $point_negate = function ($p) { return new Point($p->curve, $p->x, gmp_neg($p->y), $p->order); }; // 1.6.1 Compute a candidate public key Q = r^-1 (sR - eG) $rInv = NumberTheory::inverse_mod($r, $G->getOrder()); $eGNeg = $point_negate(Point::mul($e, $G)); $Q = Point::mul($rInv, Point::add(Point::mul($s, $R), $eGNeg)); // 1.6.2 Test Q as a public key $Qk = new PublicKey($G, $Q); if ($Qk->verifies($e, $signature)) { return $Qk; } return false; }
function show_mini_orderbook_table_cell($id, $curr, $price, $have, $want, $fiat_depth, $btc_depth) { // $have and $want is what the 'worst priced' existing order has and wants, and is used here to set the price // $fiat_depth and $btc_depth are combined amounts available which we want to match, and may include orders at better prices // $curr is the currency type they want if ($curr == 'BTC') { // we are selling BTC $depth = $btc_depth; $p = clean_sql_numstr(bcdiv($have, $want, 8)); } else { // we are buying BTC $depth = $fiat_depth; $p = clean_sql_numstr(bcdiv($want, $have, 8)); } list($w, $r) = gmp_div_qr(gmp_mul($depth, $have), $want); $w = gmp_strval(gmp_cmp($r, 0) ? gmp_sub($w, 1) : $w); $h = gmp_strval($depth); active_table_cell_trade($id, 'l', internal_to_numstr($btc_depth, BTC_PRECISION), "?page=trade&in={$curr}&have={$h}&want={$w}&rate={$p}", 'right'); active_table_cell_trade($id, 'r', internal_to_numstr($fiat_depth, FIAT_PRECISION), "?page=trade&in={$curr}&have={$h}&want={$w}&rate={$p}", 'right'); }
function CantorExpand($n, $x) { //參數說明 // $n - 排列的位數 // $x - 第幾個 (必須要是字串) //1. $x 先減1 $x = gmp_sub($x, "1"); $str = ""; for ($i = 1; $i <= $n; $i++) { //2. 先算($n-$i)階乘 $fac = gmp_strval(gmp_fact($n - $i)); //3. 再算 $x / ($n-$i) 的商跟餘數 $res = gmp_div_qr($x, $fac); $quotient = gmp_strval($res[0]); $remainder = gmp_strval($res[1]); //4. 比這個位數小的數目總共有 $quotient 個,所以開始找出這個位數 $str .= findMax($quotient); //5. 把餘數設為 $x,下次要使用 $x = $remainder; } return $str; }
/** * @param string $left_operand * @param string $right_operand * @return string */ public function subtract($left_operand, $right_operand) { $result = gmp_sub($left_operand, $right_operand); return gmp_strval($result); }
/** * Subtracts two BigIntegers. * * Here's an example: * <code> * <?php * include 'Math/BigInteger.php'; * * $a = new Math_BigInteger('10'); * $b = new Math_BigInteger('20'); * * $c = $a->subtract($b); * * echo $c->toString(); // outputs -10 * ?> * </code> * * @param Math_BigInteger $y * @return Math_BigInteger * @access public * @internal Performs base-2**52 subtraction */ function subtract($y) { switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: $temp = new Math_BigInteger(); $temp->value = gmp_sub($this->value, $y->value); return $this->_normalize($temp); case MATH_BIGINTEGER_MODE_BCMATH: $temp = new Math_BigInteger(); $temp->value = bcsub($this->value, $y->value, 0); return $this->_normalize($temp); } $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative); $result = new Math_BigInteger(); $result->value = $temp[MATH_BIGINTEGER_VALUE]; $result->is_negative = $temp[MATH_BIGINTEGER_SIGN]; return $this->_normalize($result); }
/** * This function compresses all ranges * * input is array of ip addresses * output compresses address range * * @access public * @param array $addresses * @return void */ public function compress_address_ranges($addresses, $state = 4) { # loop through IP addresses for ($c = 0; $c < sizeof($addresses); $c++) { # ignore already comressed range if ($addresses[$c]->class != "compressed-range") { # gap between this and previous if (gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c - 1]->ip_addr)) != 1) { # remove index flag unset($fIndex); # save IP address $addresses_formatted[$c] = $addresses[$c]; $addresses_formatted[$c]->class = "ip"; # no gap this -> next if (gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c + 1]->ip_addr)) == -1 && $addresses[$c]->state == $state) { //is state the same? if ($addresses[$c]->state == $addresses[$c + 1]->state) { $fIndex = $c; $addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr; $addresses_formatted[$c]->class = "compressed-range"; } } } else { # is state same as previous? if ($addresses[$c]->state == $addresses[$c - 1]->state && $addresses[$c]->state == $state) { $addresses_formatted[$fIndex]->stopIP = $addresses[$c]->ip_addr; //adds dhcp state $addresses_formatted[$fIndex]->numHosts = gmp_strval(gmp_add(@gmp_sub($addresses[$c]->ip_addr, $addresses_formatted[$fIndex]->ip_addr), 1)); //add number of hosts } else { # remove index flag unset($fIndex); # save IP address $addresses_formatted[$c] = $addresses[$c]; $addresses_formatted[$c]->class = "ip"; # check if state is same as next to start range if ($addresses[$c]->state == @$addresses[$c + 1]->state && gmp_strval(@gmp_sub($addresses[$c]->ip_addr, $addresses[$c + 1]->ip_addr)) == -1 && $addresses[$c]->state == $state) { $fIndex = $c; $addresses_formatted[$fIndex]->startIP = $addresses[$c]->ip_addr; $addresses_formatted[$c]->class = "compressed-range"; } } } } else { # save already compressed $addresses_formatted[$c] = $addresses[$c]; } } # overrwrite ipaddresses and rekey $addresses = @array_values($addresses_formatted); # return return $addresses; }
/** * Subtracts two BigIntegers. * * Here's an example: * <code> * <?php * $a = new \phpseclib\Math\BigInteger('10'); * $b = new \phpseclib\Math\BigInteger('20'); * * $c = $a->subtract($b); * * echo $c->toString(); // outputs -10 * ?> * </code> * * @param \phpseclib\Math\BigInteger $y * @return \phpseclib\Math\BigInteger * @access public * @internal Performs base-2**52 subtraction */ function subtract($y) { switch (MATH_BIGINTEGER_MODE) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_sub($this->value, $y->value); return $this->_normalize($temp); case self::MODE_BCMATH: $temp = new static(); $temp->value = bcsub($this->value, $y->value, 0); return $this->_normalize($temp); } $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative); $result = new static(); $result->value = $temp[self::VALUE]; $result->is_negative = $temp[self::SIGN]; return $this->_normalize($result); }
$cnt_tmp = 0; // loop foreach ($Subnets->slaves_full as $ss) { if ($ss->isFull == 1) { $max = $Subnets->get_max_hosts($ss->mask, $Addresses->identify_address($ss->subnet), false); // add to count $cnt_tmp = gmp_strval(gmp_add($cnt_tmp, $max)); } } } // calculate without isFull $details = $Subnets->calculate_subnet_usage_detailed($subnet['subnet'], $subnet['mask'], $addresses_slaves, $subnet['isFull']); // add temp values for slaves, recalculate if (isset($cnt_tmp)) { # calculate free hosts $details['freehosts'] = gmp_strval(gmp_sub($details['maxhosts'], $cnt_tmp)); # calculate use percentage for each type $details['freehosts_percent'] = round($details['freehosts'] * 100 / $details['maxhosts'], 2); // add "used" $details["Used_percent"] = round($cnt_tmp * 100 / $details['maxhosts'], 2); # if marked as full override if ($subnet['isFull'] == 1) { $details['Used_percent'] = $details['Used_percent'] + $details['freehosts_percent']; $details['freehosts_percent'] = 0; } } } else { $details = $Subnets->calculate_subnet_usage_detailed($subnet['subnet'], $subnet['mask'], $addresses, $subnet['isFull']); } ?>
function big_sub($left, $right, $force = null) { debug(array($left, $right)); if (is_null($left)) { $left = 0; } if (is_null($right)) { $right = 0; } if (function_exists("gmp_sub") && (is_null($force) || $force == 'gmp')) { debug(array('gmp_sub', $left, $right)); return gmp_strval(gmp_sub($left, $right)); } elseif (function_exists("bcsub") && (is_null($force) || $force == 'bc')) { debug(array('bcsub', $left, $right)); return bcsub($left, $right); } else { # Or $force == 'something else' debug(array('to_int', $left, $right)); return to_int($left - $right); } }
/** * Reformat incomplete IPv6 address to decimal for search! */ function reformatIPv6forSearch($ip) { //split network and subnet part $ip = explode("/", $ip); //if subnet is not provided we are looking for host! if (sizeof($ip) < 2) { $return['low'] = Transform2decimal($ip[0]); $return['high'] = Transform2decimal($ip[0]); } //if network part ends with :: we must search the complete provided subnet! $lastChars = substr($ip[0], -2); if ($lastChars == "::") { $return['low'] = Transform2decimal($ip[0]); //set highest IP address $subnet = substr($ip[0], 0, -2); $subnet = Transform2decimal($subnet); //calculate all possible hosts in subnet mask $maskHosts = gmp_strval(gmp_sub(gmp_pow(2, 128 - $ip[1]), 1)); $return['high'] = gmp_strval(gmp_add($return['low'], $maskHosts)); } return $return; }
protected function subtraction($A, $B, $radix) { $a = gmp_init($A, $radix); $b = gmp_init($B, $radix); // Prevent negative values if (gmp_cmp($a, $b) < 0) { $a = gmp_add($a, gmp_pow($radix, strlen($A))); } // Block-wise subtraction return $this->fixedLength(gmp_strval(gmp_sub($a, $b), $radix), strlen($A), '0'); }
protected function getAddressData($keyEntity) { /*{{{*/ $query = $this->objectManager->createQuery(' SELECT o FROM Blockchain\\Entity\\Output o LEFT JOIN o.key k WHERE k.address = :address')->setParameter('address', $keyEntity->getAddress()); $results = $query->getResult(); $transactions = array(); $receivedCount = 0; foreach ($results as $outputEntity) { $transactionEntity = $outputEntity->getTransaction(); $blockEntity = $transactionEntity->getBlock(); $output = array('id' => $outputEntity->getId(), 'txid' => $outputEntity->getTxid(), 'txidTruncated' => substr($outputEntity->getTxid(), 0, 25) . '...', 'txType' => 'received', 'blocknumber' => $blockEntity->getBlocknumber(), 'blocktime' => $blockEntity->getTime()->getTimestamp(), 'blocktimeFormatted' => $blockEntity->getTime()->format('Y-m-d H:i:s'), 'amountSatoshis' => $outputEntity->getValue(), 'amount' => self::gmpSatoshisToFloatBTC(gmp_init($outputEntity->getValue())), 'type' => $outputEntity->getType() == 'pubkeyhash' ? 'Address' : ucfirst($outputEntity->getType()), 'fromto' => array()); foreach ($transactionEntity->getInputs() as $inputEntity) { if ($inputEntity->getCoinbase()) { $output['fromto'][] = array('isGeneration' => true); } else { $inputKeyEntity = $inputEntity->getKey(); $output['fromto'][] = array('isGeneration' => false, 'address' => $inputKeyEntity ? $inputKeyEntity->getAddress() : "f'd up"); } } $transactions[] = $output; $receivedCount++; } $query = $this->objectManager->createQuery(' SELECT i FROM Blockchain\\Entity\\Input i LEFT JOIN i.key k WHERE k.address = :address')->setParameter('address', $keyEntity->getAddress()); $results = $query->getResult(); $sentCount = 0; foreach ($results as $inputEntity) { $transactionEntity = $inputEntity->getTransaction(); $blockEntity = $transactionEntity->getBlock(); $input = array('id' => $inputEntity->getId(), 'txid' => $inputEntity->getTxid(), 'txidTruncated' => substr($inputEntity->getTxid(), 0, 25) . '...', 'txType' => 'sent', 'blocknumber' => $blockEntity->getBlocknumber(), 'blocktime' => $blockEntity->getTime()->getTimestamp(), 'blocktimeFormatted' => $blockEntity->getTime()->format('Y-m-d H:i:s'), 'amountSatoshis' => $inputEntity->getValue(), 'amount' => self::gmpSatoshisToFloatBTC(gmp_init($inputEntity->getValue())), 'type' => null, 'fromto' => array()); foreach ($transactionEntity->getOutputs() as $outputEntity) { $input['fromto'][] = array('isGeneration' => false, 'address' => $outputEntity->getKey()->getAddress()); if ($outputEntity->getType() == 'pubkeyhash') { $type = 'Address'; } else { $type = ucfirst($outputEntity->getType()); } if (!$input['type']) { $input['type'] = $type; } else { if ($input['type'] != $type) { $input['type'] = 'Mixed'; } } } $transactions[] = $input; $sentCount++; } usort($transactions, function ($a, $b) { if ($a['blocktime'] == $b['blocktime']) { if ($a['txType'] == $b['txType']) { return $a['id'] - $b['id']; } switch ($a['txType']) { case 'received': return -1; break; case 'sent': return 1; break; default: return 0; break; } } return $a['blocktime'] - $b['blocktime']; }); $balance = gmp_init('0'); $receivedTotalValue = gmp_init('0'); $sentTotalValue = gmp_init('0'); foreach ($transactions as &$transaction) { $amount = gmp_init($transaction['amountSatoshis']); switch ($transaction['txType']) { case 'received': $balance = gmp_add($balance, $amount); $receivedTotalValue = gmp_add($receivedTotalValue, $amount); break; case 'sent': $balance = gmp_sub($balance, $amount); $sentTotalValue = gmp_add($sentTotalValue, $amount); break; default: die($transaction['txType']); break; } $transaction['balance'] = self::gmpSatoshisToFloatBTC($balance); } $addressData = array('address' => $keyEntity->getAddress(), 'firstseen' => $keyEntity->getFirstblock()->getTime()->format('Y-m-d H:i:s'), 'receivedTransactions' => $receivedCount, 'receivedBTC' => self::gmpSatoshisToFloatBTC($receivedTotalValue), 'sentTransactions' => $sentCount, 'sentBTC' => self::gmpSatoshisToFloatBTC($sentTotalValue), 'hash160' => $keyEntity->getHash160(), 'pubkey' => $keyEntity->getPubkey(), 'transactions' => $transactions); return $addressData; }
public static function double(Point $p1) { $p = $p1->curve->prime; $a = $p1->curve->a; $inverse = gmp_invert(gmp_mul(2, $p1->y), $p); $three_x2 = gmp_mul(3, gmp_pow($p1->x, 2)); $l = gmp_mod(gmp_mul(gmp_add($three_x2, $a), $inverse), $p); $x3 = gmp_mod(gmp_sub(gmp_pow($l, 2), gmp_mul(2, $p1->x)), $p); $y3 = gmp_mod(gmp_sub(gmp_mul($l, gmp_sub($p1->x, $x3)), $p1->y), $p); if (gmp_cmp(0, $y3) > 0) { $y3 = gmp_add($p, $y3); } return new Point($p1->curve, $x3, $y3); }
function check_btc_withdraw_limit($uid, $amount) { $withdrawn = btc_withdrawn_today($uid); $limit = numstr_to_internal(MAXIMUM_DAILY_BTC_WITHDRAW); $available = gmp_sub($limit, $withdrawn); if (gmp_cmp($amount, $available) > 0) { throw new Problem(_('Daily limit exceeded'), sprintf(_('You can only withdraw %s per day.'), internal_to_numstr($limit) . ' BTC')); } }
/** * Calculates $num - 1 * * @param gmp resource $num * @return gmp resource * @access public */ function dec($num) { return gmp_sub($num, 1); }