public function __construct($cipher, $key, $taglen) { $logging = \Plop\Plop::getInstance(); $this->cipher = mcrypt_module_open($cipher, null, 'ecb', null); mcrypt_generic_init($this->cipher, $key, str_repeat("", 16)); $this->taglen = $taglen; $logging->debug('Pre-computing GCM table'); $H = gmp_init(bin2hex(mcrypt_generic($this->cipher, str_repeat("", 16))), 16); $H = str_pad(gmp_strval($H, 2), 128, '0', STR_PAD_LEFT); $R = gmp_init('E1000000000000000000000000000000', 16); $this->table = array(); for ($i = 0; $i < 16; $i++) { $this->table[$i] = array(); for ($j = 0; $j < 256; $j++) { $V = gmp_init(dechex($j) . str_repeat("00", $i), 16); $Z = gmp_init(0); for ($k = 0; $k < 128; $k++) { // Compute Z_n+1 if ($H[$k]) { $Z = gmp_xor($Z, $V); } // Compute V_n+1 $odd = gmp_testbit($V, 0); $V = gmp_div_q($V, 2); if ($odd) { $V = gmp_xor($V, $R); } } $this->table[$i][$j] = pack('H*', str_pad(gmp_strval($Z, 16), 32, 0, STR_PAD_LEFT)); } } $logging->debug('Done pre-computing GCM table'); }
/** * Pack a long. * * If it is a 32bit PHP we suppose that this log is treated by bcmath * TODO 32bit * * @param int|string $value * * @return string the packed long */ public static function packLong($value) { if (PHP_INT_SIZE > 4) { $value = (int) $value; $binaryString = chr($value >> 56 & 0xff) . chr($value >> 48 & 0xff) . chr($value >> 40 & 0xff) . chr($value >> 32 & 0xff) . chr($value >> 24 & 0xff) . chr($value >> 16 & 0xff) . chr($value >> 8 & 0xff) . chr($value & 0xff); } else { /* * To get the two's complement of a binary number, * the bits are inverted, or "flipped", * by using the bitwise NOT operation; * the value of 1 is then added to the resulting value */ $bitString = ''; $isNegative = $value[0] == '-'; if (function_exists("bcmod")) { //add 1 for the two's complement if ($isNegative) { $value = bcadd($value, '1'); } while ($value !== '0') { $bitString = (string) abs((int) bcmod($value, '2')) . $bitString; $value = bcdiv($value, '2'); } } elseif (function_exists("gmp_mod")) { //add 1 for the two's complement if ($isNegative) { $value = gmp_strval(gmp_add($value, '1')); } while ($value !== '0') { $bitString = gmp_strval(gmp_abs(gmp_mod($value, '2'))) . $bitString; $value = gmp_strval(gmp_div_q($value, '2')); } } else { while ($value != 0) { list($value, $remainder) = self::str2bin((string) $value); $bitString = $remainder . $bitString; } } //Now do the logical not for the two's complement last phase if ($isNegative) { $len = strlen($bitString); for ($x = 0; $x < $len; $x++) { $bitString[$x] = $bitString[$x] == '1' ? '0' : '1'; } } //pad to have 64 bit if ($bitString != '' && $isNegative) { $bitString = str_pad($bitString, 64, '1', STR_PAD_LEFT); } else { $bitString = str_pad($bitString, 64, '0', STR_PAD_LEFT); } $hi = substr($bitString, 0, 32); $lo = substr($bitString, 32, 32); $hiBin = pack('H*', str_pad(base_convert($hi, 2, 16), 8, 0, STR_PAD_LEFT)); $loBin = pack('H*', str_pad(base_convert($lo, 2, 16), 8, 0, STR_PAD_LEFT)); $binaryString = $hiBin . $loBin; } return $binaryString; }
function digit($n1, $n2, $d) { global $u, $v; $u = gmp_div_q($n1, $d); $v = gmp_div_q($n2, $d); if (gmp_cmp($u, $v) == 0) { return $u; } return false; }
/** * {@inheritdoc} */ public function encodeSFixed64($sFixed64) { $value = $this->is32Bit ? gmp_and($sFixed64, '0x0ffffffffffffffff') : gmp_init(sprintf('%u', $sFixed64)); $bytes = ''; for ($i = 0; $i < 8; ++$i) { $bytes .= chr(gmp_intval(gmp_and($value, $this->gmp_xff))); $value = gmp_div_q($value, $this->gmp_x100); } return $bytes; }
public function xrecover($y) { $xx = gmp_mul(gmp_sub(gmp_mul($y, $y), 1), $this->inv(gmp_add(gmp_mul(gmp_mul($this->params['d'], $y), $y), 1))); $x = gmp_powm($xx, gmp_div_q(gmp_add($this->params['q'], 3), 8), $this->params['q']); $t = gmp_mod(gmp_sub(gmp_mul($x, $x), $xx), $this->params['q']); if (gmp_cmp($t, 0)) { $x = gmp_mod(gmp_mul($x, $this->params['I']), $this->params['q']); } if (gmp_cmp(gmp_mod($x, 2), 0)) { $x = gmp_sub($this->params['q'], $x); } return $x; }
/** * Назначение: Основные пользовательские функции */ function number62_encode($number) { if (preg_match('#^[0-9]+$#iu', $number) == 0) { return ""; } $out = ""; $string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; do { $key = gmp_mod($number, 62); $out = $string[$key] . $out; $number = gmp_strval(gmp_div_q($number, 62, GMP_ROUND_ZERO)); } while (gmp_cmp($number, 0) > 0); return $out; }
public function totalPages() { $remainder = gmp_div_r(count($this->items_array), $this->items_x_page); $quotient = gmp_intval(gmp_div_q(count($this->items_array), $this->items_x_page)); if ($quotient > 0) { if ($remainder > 0) { $this->total_pages = $quotient + 1; } else { $this->total_pages = $quotient; } } else { $this->total_pages = 1; } return $this->total_pages; }
function fatorar_raiz_quadrada($numOrig) { $result = ''; $fatoracao = fatoracao_numeros_primos($numOrig); if (is_array($fatoracao) && count($fatoracao) > 0) { $resultFatNumero = 0; $resultFatRaiz = array(); foreach ($fatoracao as $fator => $qtd) { if ($qtd > 1) { $agrupamentoPares = gmp_div_q($qtd, 2); // divide por dois, simples, retorna inteiro $resultPares = $fator * gmp_strval($agrupamentoPares); // os pares são tirados da raiz quadrada, portanto numeros normais no resultado; $resultFatNumero = $resultFatNumero > 0 ? $resultFatNumero * $resultPares : $resultPares; $restoImpar = gmp_div_r($qtd, 2); if ($restoImpar > 0) { $resultFatRaiz[] = "raiz quadrada(" . gmp_strval($fator) . ")"; } } else { $resultFatRaiz[] = "raiz quadrada({$fator})"; } } if ($resultFatNumero > 0) { $result = $resultFatNumero; } if (count($resultFatRaiz) > 0) { $resultFatRaiz = implode(' * ', $resultFatRaiz); if ($result != '') { // caso exista numerico, multiplicar por este $result .= ' * '; } $result .= $resultFatRaiz; } } else { $result = "<b>{$fatoracao}<b><br>"; } return $result; }
$cmp3 = gmp_cmp("1234", "1234"); // equal to echo "{$cmp1} {$cmp2} {$cmp3}" . "\n"; // gmp_com $com = gmp_com("1234"); echo gmp_strval($com) . "\n"; // gmp_div_q $div1 = gmp_div_q("100", "5"); echo gmp_strval($div1) . "\n"; $div2 = gmp_div_q("1", "3"); echo gmp_strval($div2) . "\n"; $div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF); echo gmp_strval($div3) . "\n"; $div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF); echo gmp_strval($div4) . "\n"; $div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF); echo gmp_strval($div5) . "\n"; // gmp_div_qr $a = gmp_init("0x41682179fbf5"); $res = gmp_div_qr($a, "0xDEFE75"); var_dump($res); printf("Result is: q - %s, r - %s" . PHP_EOL, gmp_strval($res[0]), gmp_strval($res[1])); // gmp_div_r $div = gmp_div_r("105", "20"); echo gmp_strval($div) . "\n"; // gmp_div $div1 = gmp_div("100", "5"); echo gmp_strval($div1) . "\n"; // gmp_divexact $div1 = gmp_divexact("10", "2"); echo gmp_strval($div1) . "\n";
public function getPubKeyWithRS($flag, $R, $S, $hash) { $isCompressed = false; if ($flag < 27 || $flag >= 35) { return false; } if ($flag >= 31) { $isCompressed = true; $flag -= 4; } $recid = $flag - 27; //step 1.1 $x = null; $x = gmp_add(gmp_init($R, 16), gmp_mul($this->n, gmp_div_q(gmp_init($recid, 10), gmp_init(2, 10)))); //step 1.3 $y = null; if (1 == $flag % 2) { $gmpY = $this->calculateYWithX(gmp_strval($x, 16), '02'); if (null != $gmpY) { $y = gmp_init($gmpY, 16); } } else { $gmpY = $this->calculateYWithX(gmp_strval($x, 16), '03'); if (null != $gmpY) { $y = gmp_init($gmpY, 16); } } if (null == $y) { return null; } $Rpt = array('x' => $x, 'y' => $y); //step 1.6.1 //calculate r^-1 (S*Rpt - eG) $eG = $this->mulPoint($hash, $this->G); $eG['y'] = gmp_mod(gmp_neg($eG['y']), $this->p); $SR = $this->mulPoint($S, $Rpt); $pubKey = $this->mulPoint(gmp_strval(gmp_invert(gmp_init($R, 16), $this->n), 16), $this->addPoints($SR, $eG)); $pubKey['x'] = gmp_strval($pubKey['x'], 16); $pubKey['y'] = gmp_strval($pubKey['y'], 16); while (strlen($pubKey['x']) < 64) { $pubKey['x'] = '0' . $pubKey['x']; } while (strlen($pubKey['y']) < 64) { $pubKey['y'] = '0' . $pubKey['y']; } $derPubKey = $this->getDerPubKeyWithPubKeyPoints($pubKey, $isCompressed); if ($this->checkSignaturePoints($derPubKey, $R, $S, $hash)) { return $derPubKey; } else { return false; } }
public function Div($left, $right) { return $this->string(gmp_div_q($left, $right)); }
/** * Divides two numbers. * * @param resource $a The first number * @param resource $b The second number * @return resource */ public function div($a, $b) { return gmp_div_q($a, $b); }
/** * Return all prime factors of this number * * The keys (prime factors) will be strings * The values (exponents will be integers * * Adapted from http://www.thatsgeeky.com/2011/03/prime-factoring-with-php/ * * @return array [primeFactor => exponent,...] */ public function primeFactors() { $number = $this->cloneValue(); $divisor = 2; $zero = gmp_init(0); $one = gmp_init(1); $dmax = gmp_sqrt($number); $factors = array(); $sieve = array_fill(1, intval(gmp_strval($dmax)), 1); do { $rFlag = false; while (gmp_cmp(gmp_mod($number, $divisor), $zero) == 0) { $factors[$divisor] = isset($factors[$divisor]) ? $factors[$divisor] + 1 : 1; $number = gmp_div_q($number, $divisor); $rFlag = true; } if ($rFlag) { $dmax = gmp_sqrt($number); } if (gmp_cmp($number, $one) > 0) { for ($i = $divisor; gmp_cmp($i, $dmax) <= 0; $i += $divisor) { $sieve[$i] = 0; } do { $divisor++; } while (gmp_cmp($divisor, $dmax) < 0 && $sieve[$divisor] != 1); if (gmp_cmp($divisor, $dmax) > 0) { $key = gmp_strval($number); $factors[$key] = isset($factors[$key]) ? $factors[$key] + 1 : 1; } } } while (gmp_cmp($number, $one) > 0 && gmp_cmp($divisor, $dmax) <= 0); return $factors; }
public function import() { /*{{{*/ if (extension_loaded('xhprof')) { // xhprof slows things down xhprof_disable(); } if (!extension_loaded('gmp')) { throw new Exception('The blockchain importer requires the PHP GMP module to be installed and enabled'); } echo "\nTodo:\n\n* add Output_Key join table to support multisig, convert data, then re-import all multisig transactions\n* detect if PHP is 64-bit, if not, check if GMP is installed, otherwise us BCMath\n - ACTUALLY, just move to PHPSECLIB: http://phpseclib.sourceforge.net/math/intro.html \n* move RPC calls into separate class\n* move bitcoin specific utils into separate class\n* move conversion from satoshis to floats into view model\n* fix trailing decimal point on whole numbers in block and blockchain views\n\nMaybe:\n\n* move entities to model binder?\n"; sleep(1); // this can take a long time set_time_limit(0); $client = new \Zend\Json\Server\Client($this->bitcoindServerUrl); $client->getHttpClient()->setOptions(array('timeout' => 30)); $blockcount = $client->call('getblockcount'); // Get the last block in the DB $query = $this->objectManager->createQuery('SELECT b FROM Blockchain\\Entity\\Block b WHERE b.id = (SELECT MAX(bm.id) FROM Blockchain\\Entity\\Block bm)'); $result = $query->getResult(); if (count($result) == 1) { $blockEntity = $result[0]; $blockId = $blockEntity->getId(); $blockhash = $blockEntity->getBlockhash(); $blockNumber = $blockEntity->getBlockNumber(); $block = $this->getBlockFromServer($blockhash); // remove last block and all associated transactions in case it wasn't loaded full or there was no "nextblockhash" $connection = $this->objectManager->getConnection(); if ($connection->getDatabasePlatform()->getName() == 'mysql') { // The input and output tables have cyclical foreign keys, so rows can't be deleted $connection->query('SET FOREIGN_KEY_CHECKS=0'); } $this->objectManager->remove($blockEntity); $this->objectManager->flush(); if ($connection->getDatabasePlatform()->getName() == 'mysql') { $connection->query('SET FOREIGN_KEY_CHECKS=1'); } $coinbaseExp = floor($blockNumber / 210000); $gmp_coinbaseValue = gmp_div_q(gmp_init("5000000000"), gmp_pow(gmp_init("2"), $coinbaseExp)); } else { $blockNumber = 0; $blockhash = $client->call('getblockhash', array($blockNumber)); $gmp_coinbaseValue = gmp_init("5000000000"); } $batchSize = 25; $count = 0; // Start importing $lastTime = 0; $currTime = 0; $avgTime = 0; $blockCount = 0; while ($blockhash) { $currTime = microtime(true); if ($lastTime) { $diff = $currTime - $lastTime; // update average time between blocks $avgTime = ($avgTime * ($blockCount - 1) + $diff) / $blockCount; $blocksLeft = $blockcount - $blockNumber; $estimatedCompletion = $blocksLeft * $avgTime; echo sprintf("\n\nEstimated completion: %s (blocks left: %d, average block time: %s seconds\n", self::secondsToString($estimatedCompletion), $blocksLeft, number_format($avgTime, 2)); } if ($blockNumber % 210000 == 0) { // only calculate this when necessary instead of every loop $coinbaseExp = floor($blockNumber / 210000); $gmp_coinbaseValue = gmp_div_q(gmp_init("5000000000"), gmp_pow(gmp_init("2"), $coinbaseExp)); } echo "\nBlock {$blockNumber}, Transactions: "; $gmp_totalBlockValue = gmp_init("0"); $block = $this->getBlockFromServer($blockhash); $blockEntity = new \Blockchain\Entity\Block(); $blockEntity->setBlockNumber($blockNumber); $blockEntity->setBlockhash($block['hash']); $blockEntity->setSize($block['size']); $blockEntity->setHeight($block['height']); $blockEntity->setVersion($block['version']); $blockEntity->setMerkleroot($block['merkleroot']); $blockEntity->setTime(new \DateTime('@' . $block['time'])); $blockEntity->setNonce($block['nonce']); $blockEntity->setBits($block['bits']); $blockEntity->setDifficulty($block['difficulty']); if (isset($block['nextblockhash'])) { $blockEntity->setNextblockhash($block['nextblockhash']); } if (isset($block['previousblockhash'])) { $blockEntity->setPreviousblockhash($block['previousblockhash']); } $this->objectManager->persist($blockEntity); $count++; $gmp_offeredFees = gmp_init("0"); $gmp_takenFees = gmp_init("0"); // First block is unique if ($blockNumber > 0) { $seenTxids = array(); $seenAddresses = array(); $txCount = 0; foreach ($block['tx'] as $txid) { $txCount++; if ($txCount > 1) { echo ', '; } echo $txCount; // the JSON RPC client appears to have a memory leak, so isolate it inside a function $transaction = $this->getRawTransactionFromServer($txid); if (!$transaction) { die('failure retrieving transaction'); } if ($blockNumber == 91842 && $transaction['txid'] == 'd5d27987d2a3dfc724e359870c6644b40e497bdc0589a033220fe15429d88599') { // Special case where a transaction was duplicated in block 91812 and 91842 due to a bug in a mining client // ignore the second instance continue; } if ($blockNumber == 91880 && $transaction['txid'] == 'e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468') { // Special case where a transaction was duplicated in block 91722 and 91880 due to a bug in a mining client // ignore the second instance continue; } $transactionEntity = new \Blockchain\Entity\Transaction(); $transactionEntity->setTxid($transaction['txid']); $transactionEntity->setBlockhash($blockhash); $transactionEntity->setBlock($blockEntity); $transactionEntity->setVersion($transaction['version']); $transactionEntity->setLocktime($transaction['locktime']); $transactionEntity->setSize($transaction['size']); $this->objectManager->persist($transactionEntity); $count++; $gmp_totalInputValue = gmp_init("0"); foreach ($transaction['vin'] as $input) { $inputEntity = new \Blockchain\Entity\Input(); $inputEntity->setTxid($txid); $inputEntity->setSequence($input['sequence']); if (isset($input['coinbase'])) { $inputEntity->setCoinbase($input['coinbase']); $inputEntity->setValue(gmp_strval($gmp_coinbaseValue)); $gmp_totalInputValue = gmp_add($gmp_totalInputValue, $gmp_coinbaseValue); } else { if (isset($seenTxids[$input['txid']])) { // input of one transaction is referencing the output of another transaction in the same block. flush writes. $this->objectManager->flush(); // clear objects to free memory $this->objectManager->clear(); // reload associated entities $blockEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Block')->findOneBy(array('blockhash' => $blockhash)); $transactionEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Transaction')->findOneBy(array('txid' => $txid)); } $inputEntity->setRedeemedTxid($input['txid']); $inputEntity->setScriptSigAsm($input['scriptSig']['asm']); $inputEntity->setScriptSigHex($input['scriptSig']['hex']); $inputEntity->setVout($input['vout']); $redeemedOutputEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Output')->findOneBy(array('txid' => $input['txid'], 'n' => $input['vout'])); if (!$redeemedOutputEntity) { die('could not find output'); } $nonstandard = false; $pubkey = null; $hash160 = null; $address = null; $keyEntity = null; if (preg_match('/(.+) (.+)/', $input['scriptSig']['asm'], $matches)) { // Standard Transaction to Bitcoin address (pay-to-pubkey-hash) // scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // scriptSig: <sig> <pubKey> $signature = $matches[1]; $pubkey = $matches[2]; $hash160 = self::pubkeyToHash160($pubkey); $address = self::hash160ToAddress($hash160); } else { if ($redeemedOutputEntity->getType() == 'nonstandard') { $nonstandard = true; echo "...nonstandard output, scriptsig: " . $input['scriptSig']['asm'] . "..."; $redeemedOutputKeyEntity = $redeemedOutputEntity->getKey(); if ($redeemedOutputKeyEntity) { $pubkey = $redeemedOutputKeyEntity->getPubkey(); $hash160 = $redeemedOutputKeyEntity->getHash160(); $address = $redeemedOutputKeyEntity->getAddress(); } } else { if (preg_match('/([\\S]+)/', $input['scriptSig']['asm'])) { // Standard Generation Transaction (pay-to-pubkey) // scriptPubKey: <pubKey> OP_CHECKSIG // scriptSig: <sig> $redeemedOutputKeyEntity = $redeemedOutputEntity->getKey(); if ($redeemedOutputKeyEntity) { $pubkey = $redeemedOutputKeyEntity->getPubkey(); $hash160 = $redeemedOutputKeyEntity->getHash160(); $address = $redeemedOutputKeyEntity->getAddress(); } else { echo "\n\n" . $input['scriptSig']['asm'] . "\n"; die("\nStandard Generation without key\n"); } } else { die("strange scriptSig: " . $input['scriptSig']['asm'] . "\n"); } } } $keyEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Key')->findOneBy(array('address' => $address)); if (!$keyEntity) { if ($address && !isset($seenAddresses[$address])) { $keyEntity = new \Blockchain\Entity\Key(); $keyEntity->setPubkey($pubkey); $keyEntity->setHash160($hash160); $keyEntity->setAddress($address); $keyEntity->setFirstblockhash($blockhash); $keyEntity->setFirstblock($blockEntity); $seenAddresses[$address] = array('pubkey' => $pubkey); } else { $this->objectManager->flush(); $keyEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Key')->findOneBy(array('address' => $address)); } } if (!$keyEntity && !$nonstandard) { die("problem finding input key: {$address}\n"); } if ($keyEntity) { if ($pubkey && !$keyEntity->getPubkey()) { $keyEntity->setPubkey($pubkey); } $this->objectManager->persist($keyEntity); $inputEntity->setKey($keyEntity); } $inputEntity->setHash160($hash160); $inputEntity->setAddress($address); $gmp_inputValue = gmp_init($redeemedOutputEntity->getValue()); $inputEntity->setValue(gmp_strval($gmp_inputValue)); $inputEntity->setAddress($redeemedOutputEntity->getAddress()); $inputEntity->setRedeemedOutput($redeemedOutputEntity); $redeemedOutputEntity->setRedeemingInput($inputEntity); $this->objectManager->persist($redeemedOutputEntity); $gmp_totalInputValue = gmp_add($gmp_totalInputValue, gmp_init($inputEntity->getValue())); // echo 'txid: '.$txid.', input txid: '.$input['txid'].', vout: '.$input['vout'].", val: ".gmp_strval($gmp_inputValue)."\n"; // Need to figure out how to extract hash160, if it is of any value... // $inputEntity->setHash160(); } $inputEntity->setTransaction($transactionEntity); $this->objectManager->persist($inputEntity); $count++; } $gmp_totalBlockValue = gmp_add($gmp_totalBlockValue, $gmp_totalInputValue); $gmp_totalOutputValue = gmp_init("0"); foreach ($transaction['vout'] as $output) { $outputEntity = new \Blockchain\Entity\Output(); $outputEntity->setTxid($txid); $outputEntity->setN($output['n']); $gmp_outputValue = self::floatBTCToGmpSatoshis($output['value']); $outputEntity->setValue(gmp_strval($gmp_outputValue)); $gmp_totalOutputValue = gmp_add($gmp_totalOutputValue, $gmp_outputValue); $outputEntity->setScriptPubKeyAsm($output['scriptPubKey']['asm']); $outputEntity->setScriptPubKeyHex($output['scriptPubKey']['hex']); $pubkey = null; $hash160 = null; $address = null; if (preg_match('/OP_DUP OP_HASH160 ([\\S]+) OP_EQUALVERIFY OP_CHECKSIG/', $output['scriptPubKey']['asm'], $matches)) { $hash160 = $matches[1]; $address = self::hash160ToAddress($hash160); } else { if (preg_match('/^([\\S]+) OP_CHECKSIG$/', $output['scriptPubKey']['asm'], $matches)) { $pubkey = $matches[1]; $hash160 = self::pubkeyToHash160($pubkey); $address = self::hash160ToAddress($hash160); } } $keyEntity = null; if ($address) { $keyEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Key')->findOneBy(array('address' => $address)); if (!$keyEntity) { if (!isset($seenAddresses[$address])) { $keyEntity = new \Blockchain\Entity\Key(); $keyEntity->setPubkey($pubkey); $keyEntity->setHash160($hash160); $keyEntity->setAddress($address); $keyEntity->setFirstblockhash($blockhash); $keyEntity->setFirstblock($blockEntity); $seenAddresses[$address] = array('pubkey' => $pubkey); } else { $this->objectManager->flush(); $keyEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Key')->findOneBy(array('address' => $address)); } } if ($keyEntity) { if ($pubkey && !$keyEntity->getPubkey()) { $keyEntity->setPubkey($pubkey); } $this->objectManager->persist($keyEntity); $outputEntity->setKey($keyEntity); } if (!$keyEntity && $pubkey && !$seenAddresses[$address]['pubkey']) { die("Situation: address seen multiple times in transaction, and pubkey available\n"); } } if ($address && !$keyEntity) { die("Output key entity not generated: {$address}\n"); } $outputEntity->setHash160($hash160); if (isset($output['scriptPubKey']['reqSigs'])) { $outputEntity->setReqSigs($output['scriptPubKey']['reqSigs']); } $outputEntity->setType($output['scriptPubKey']['type']); if (count($output['scriptPubKey']['addresses']) > 1) { echo "\n\noutput with multiple addresses found:\n"; echo print_r($output, true); echo "\n"; } else { if (isset($output['scriptPubKey']['addresses'][0]) && $address != $output['scriptPubKey']['addresses'][0]) { echo $output['scriptPubKey']['asm'] . "\n"; die("inconsistent output addresses\n parsed: {$address}\n given: {$output['scriptPubKey']['addresses'][0]}\n"); } } $outputEntity->setAddress($output['scriptPubKey']['addresses'][0]); $outputEntity->setHash160($hash160); $outputEntity->setTransaction($transactionEntity); $this->objectManager->persist($outputEntity); $count++; } if (isset($input['coinbase'])) { $gmp_takenFees = gmp_sub($gmp_totalOutputValue, $gmp_coinbaseValue); } if (!isset($input['coinbase'])) { $gmp_fee = gmp_sub($gmp_totalInputValue, $gmp_totalOutputValue); $gmp_offeredFees = gmp_add($gmp_offeredFees, $gmp_fee); } else { $gmp_fee = gmp_init("0"); } $transactionEntity->setFee(gmp_strval($gmp_fee)); $transactionEntity->setTotalIn(gmp_strval($gmp_totalInputValue)); $transactionEntity->setTotalOut(gmp_strval($gmp_totalOutputValue)); $this->objectManager->persist($transactionEntity); $count++; $seenTxids[$txid] = true; if ($count % $batchSize == 0) { $this->objectManager->flush(); $this->objectManager->clear(); $blockEntity = $this->objectManager->getRepository('Blockchain\\Entity\\Block')->findOneBy(array('blockhash' => $blockhash)); } } } if (gmp_cmp($gmp_offeredFees, $gmp_takenFees) > 0) { echo "WARNING: Possible lost coins. Offered Fees: " . gmp_strval($gmp_offeredFees) . ", Taken Fees: " . gmp_strval($gmp_takenFees) . "\n"; } if (gmp_cmp($gmp_takenFees, $gmp_offeredFees) > 0) { die("ERROR. Impossible transaction: Offered Fees: " . gmp_strval($gmp_offeredFees) . ", Taken Fees: " . gmp_strval($gmp_takenFees) . "\n"); } $blockEntity->setOfferedFees(gmp_strval($gmp_offeredFees)); $blockEntity->setTakenFees(gmp_strval($gmp_takenFees)); $blockEntity->setTotalvalue(gmp_strval($gmp_totalBlockValue)); $gmp_lostValue = gmp_sub($gmp_offeredFees, $gmp_takenFees); $blockEntity->setLostvalue(gmp_strval($gmp_lostValue)); $this->objectManager->persist($blockEntity); $count++; if (isset($block['nextblockhash'])) { $nextblockhash = $block['nextblockhash']; } else { $nextblockhash = null; } $this->objectManager->flush(); $this->objectManager->clear(); $blockhash = $nextblockhash; $blockNumber++; $blockCount++; $lastTime = $currTime; } }
/** * Divide two big integers and return integer part result. * Raises exception if the divisor is zero. * * @param string $leftOperand * @param string $rightOperand * @return string|null * @throws Exception\DivisionByZeroException */ public function div($leftOperand, $rightOperand) { if ($rightOperand == 0) { throw new Exception\DivisionByZeroException("Division by zero; divisor = {$rightOperand}"); } $result = gmp_div_q($leftOperand, $rightOperand); return gmp_strval($result); }
/** * * Reduce this number to it's lowest form */ protected function reduce() { $gcd = gmp_gcd($this->value['num']->gmp(), $this->value['den']->gmp()); if (gmp_cmp($gcd, 1) > 0) { $this->value['num']->set(gmp_div_q($this->value['num']->gmp(), $gcd)); $this->value['den']->set(gmp_div_q($this->value['den']->gmp(), $gcd)); } }
public function bitwise_rightShift($shift) { $temp = new Math_BigInteger(); switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: static $two; if (!isset($two)) { $two = gmp_init('2'); } $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift)); break; case MATH_BIGINTEGER_MODE_BCMATH: $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0); break; default: $temp->value = $this->value; $temp->_rshift($shift); } return $this->_normalize($temp); }
/** * This method returns the result of dividing the specified value against this object's * value. * * @access public * @static * @param IInteger\Type $x the left operand * @param IInteger\Type $y the right operand * @return IInteger\Type the result */ public static function divide(IInteger\Type $x, IInteger\Type $y) : IInteger\Type { return IInteger\Type::box(gmp_strval(gmp_div_q($x->unbox(), $y->unbox()))); }
/** * Divide two big integers and return result or NULL if the denominator * is zero. * * @param string $left_operand * @param string $right_operand * @return string|null */ public function divide($left_operand, $right_operand) { $result = gmp_div_q($left_operand, $right_operand); return gmp_strval($result); }
/** * Create a big math division function * @param string $l * @param string $r * @param int $z * @return string * @url http://www.icosaedro.it/bigint Inspired by */ function bmdiv($l, $r, $z = 0) { if (function_exists('bcdiv')) { return $z == 0 ? bcdiv($l, $r) : bcmod($l, $r); } global $profile; if ($profile['use_gmp']) { return gmp_strval($z == 0 ? gmp_div_q($l, $r) : gmp_mod($l, $r)); } $l = strval($l); $r = strval($r); $v = '0'; while (true) { if (bmcomp($l, $r) < 0) { break; } $delta = strlen($l) - strlen($r); if ($delta >= 1) { $zeroes = str_repeat("0", $delta); $r2 = $r . $zeroes; if (strcmp($l, $r2) >= 0) { $v = bmadd($v, "1" . $zeroes); $l = bmsub($l, $r2); } else { $zeroes = str_repeat("0", $delta - 1); $v = bmadd($v, "1" . $zeroes); $l = bmsub($l, $r . $zeroes); } } else { $l = bmsub($l, $r); $v = bmadd($v, "1"); } } return $z == 0 ? $v : $l; }
/** * {@inheritdoc} */ public function divide($amount, $divisor) { $divisor = Number::fromString((string) $divisor); if ($divisor->isDecimal()) { $decimalPlaces = strlen($divisor->getFractionalPart()); if ($divisor->getIntegerPart()) { $divisor = Number::fromString($divisor->getIntegerPart() . $divisor->getFractionalPart()); } else { $divisor = Number::fromString(ltrim($divisor->getFractionalPart(), '0')); } $amount = gmp_strval(gmp_mul(gmp_init($amount), gmp_init('1' . str_pad('', $decimalPlaces, '0')))); } list($integer, $remainder) = gmp_div_qr(gmp_init($amount), gmp_init((string) $divisor)); if (gmp_cmp($remainder, '0') === 0) { return gmp_strval($integer); } $divisionOfRemainder = gmp_strval(gmp_div_q(gmp_mul($remainder, gmp_init('1' . str_pad('', $this->scale, '0'))), gmp_init((string) $divisor), GMP_ROUND_MINUSINF)); return gmp_strval($integer) . '.' . str_pad($divisionOfRemainder, $this->scale, '0', STR_PAD_LEFT); }
port from pidigits.lua-5.lua (Mike Pall, Wim Couwenberg) modified by Craig Russell */ $N = (int) $argv[1]; ob_implicit_flush(1); ob_start(NULL, 4096); $w = gmp_init(0); $k = 1; $n1 = gmp_init(4); $n2 = gmp_init(3); $d = gmp_init(1); $i = 0; while (true) { //digit $u = gmp_div_q($n1, $d); $v = gmp_div_q($n2, $d); if (gmp_cmp($u, $v) == 0) { echo gmp_strval($u); ++$i; if ($i % 10 == 0) { echo "\t:", $i, "\n"; } if ($i == $N) { break; } //extract $u = gmp_mul($d, gmp_mul(-10, $u)); $n1 = gmp_mul($n1, 10); $n1 = gmp_add($n1, $u); $n2 = gmp_mul($n2, 10); $n2 = gmp_add($n2, $u);
public function sFixed64_gmp($value) { static $xff, $x100; if (NULL === $xff) { $xff = gmp_init(0xff); $x100 = gmp_init(0x100); } $value = PHP_INT_SIZE < 8 ? gmp_and($value, '0x0ffffffffffffffff') : gmp_init(sprintf('%u', $value)); $bytes = ''; for ($i = 0; $i < 8; $i++) { $bytes .= chr(gmp_intval(gmp_and($value, $xff))); $value = gmp_div_q($value, $x100); } $this->write($bytes); }
public static function unserialize(\fpoirotte\Pssht\ECC\Curve $curve, $s) { $len = strlen($s); if ($len === 0) { throw new \InvalidArgumentException(); } if ($s[0] === "" && $len === 1) { return new static(null, null); } /// @TODO Support point compression? if ($s[0] !== "") { throw new \InvalidArgumentException(); } $mod = $curve->getModulus(); $mlen = gmp_init(strlen(gmp_strval($mod, 2))); $mlen = gmp_intval(gmp_div_q($mlen, 8, GMP_ROUND_PLUSINF)) * 2; if ($len !== $mlen + 1) { throw new \InvalidArgumentException(); } $x = gmp_init(bin2hex(substr($s, 1, $mlen / 2)), 16); $y = gmp_init(bin2hex(substr($s, 1 + $mlen / 2)), 16); if (gmp_cmp($x, $mod) >= 0 || gmp_cmp($y, $mod) >= 0) { throw new \InvalidArgumentException(); } return new static($x, $y); }
function div($x, $y) { return gmp_div_q($x, $y); }
/** * Divide two big integers and return result or NULL if the denominator * is zero. * @param string $left_operand * @param string $right_operand * @return string|null */ public function divide($left_operand, $right_operand) { return gmp_strval(gmp_div_q($left_operand, $right_operand)); }
function Transformation_Extract($tr, $j) { return gmp_div_q(gmp_add(gmp_mul($tr[0], $j), $tr[1]), gmp_add(gmp_mul($tr[2], $j), $tr[3])); }
function dots($num) { if (strstr($num, ".")) { $ost1 = substr($num, 1 + strpos($num, ".")); $num = substr($num, 0, strpos($num, ".")); } if (substr($num, 0, 1) == "-") { $min = 1; $num = substr($num, 1); } if (strstr($num, ".")) { $num = substr($num, 0, strpos($num, ".")); } $ost = gmp_strval(gmp_div_r(strlen($num), 3)); for ($i = 1; $i <= gmp_strval(gmp_div_q(strlen($num), 3)); $i++) { $str = substr($num, strlen($num) - $i * 3, 3) . "." . $str; } if ($ost > 0) { $str = substr($num, 0, $ost) . "." . $str; } $str = substr($str, 0, strlen($str) - 1); if ($str == "") { $str = 0; } if ($min) { $str = "-" . $str; } if ($ost1) { $str = $str . "," . $ost1; } return $str; }
/** * Logical Right Shift * * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift. * * @param int $shift * @return Math_BigInteger * @access public * @internal The only version that yields any speed increases is the internal version. */ function bitwise_rightShift($shift) { $temp = new Math_BigInteger(); switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: static $two; if (!isset($two)) { $two = gmp_init('2'); } $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift)); break; case MATH_BIGINTEGER_MODE_BCMATH: $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0); break; default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten // and I don't want to do that... $temp->value = $this->value; $temp->_rshift($shift); } return $this->_normalize($temp); }
<?php var_dump(gmp_div_q()); var_dump(gmp_div_q("")); var_dump(gmp_div_q(0, 1)); var_dump(gmp_div_q(1, 0)); var_dump(gmp_div_q(12653, 23482734)); var_dump(gmp_div_q(12653, 23482734, 10)); var_dump(gmp_div_q(1123123, 123)); var_dump(gmp_div_q(1123123, 123, 1)); var_dump(gmp_div_q(1123123, 123, 2)); var_dump(gmp_div_q(1123123, 123, GMP_ROUND_ZERO)); var_dump(gmp_div_q(1123123, 123, GMP_ROUND_PLUSINF)); var_dump(gmp_div_q(1123123, 123, GMP_ROUND_MINUSINF)); $fp = fopen(__FILE__, 'r'); var_dump(gmp_div_q($fp, $fp)); var_dump(gmp_div_q(array(), array())); echo "Done\n";