List of usage examples for java.math BigInteger divide
public BigInteger divide(BigInteger val)
From source file:it.nibbles.javacoin.block.BlockChainImpl.java
/** * Calculate the difficulty for the next block after the one supplied. *///from w ww . jav a2 s . co m public DifficultyTarget getNextDifficultyTarget(BlockChainLink link, Block newBlock) { // If we're calculating for the genesis block return // fixed difficulty if (link == null) return bitcoinFactory.maxDifficultyTarget(); // Look whether it's time to change the difficulty setting // (only change every TARGET_RECALC blocks). If not, return the // setting of this block, because the next one has to have the same // target. if ((link.getHeight() + 1) % TARGET_RECALC != 0) { // Special rules for testnet (for testnet2 only after 15 Feb 2012) Block currBlock = link.getBlock(); if (bitcoinFactory.isTestnet3() || (bitcoinFactory.isTestnet2() && currBlock.getCreationTime() > 1329180000000L)) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (newBlock.getCreationTime() > link.getBlock().getCreationTime() + 2 * TARGET_SPACING) return bitcoinFactory.maxDifficultyTarget(); else { // Return the last non-special-min-difficulty-rules-block // We could use a custom method here to load only block headers instead of full blocks // but this lack of performance is only for the testnet so we don't care while (link != null && (link.getHeight() % TARGET_RECALC) != 0 && link.getBlock() .getCompressedTarget() == bitcoinFactory.maxDifficultyTarget().getCompressedTarget()) link = linkStorage.getLinkBlockHeader(link.getBlock().getPreviousBlockHash()); if (link != null) return new DifficultyTarget(link.getBlock().getCompressedTarget()); else return bitcoinFactory.maxDifficultyTarget(); } } logger.debug("previous height {}, not change in target", link.getHeight()); return new DifficultyTarget(link.getBlock().getCompressedTarget()); } // We have to change the target. First collect the last TARGET_RECALC // blocks (including the given block) Block startBlock = link.getBlock(); for (int i = 0; (i < TARGET_RECALC - 1) && (startBlock != null); i++) startBlock = getBlockHeader(startBlock.getPreviousBlockHash()); // This shouldn't happen, we reached genesis if (startBlock == null) return bitcoinFactory.maxDifficultyTarget(); // Calculate the time the TARGET_RECALC blocks took long calculatedTimespan = link.getBlock().getCreationTime() - startBlock.getCreationTime(); if (calculatedTimespan < TARGET_TIMESPAN / 4) calculatedTimespan = TARGET_TIMESPAN / 4; if (calculatedTimespan > TARGET_TIMESPAN * 4) calculatedTimespan = TARGET_TIMESPAN * 4; // Calculate new target, but allow no more than maximum target DifficultyTarget difficultyTarget = new DifficultyTarget(link.getBlock().getCompressedTarget()); BigInteger target = difficultyTarget.getTarget(); target = target.multiply(BigInteger.valueOf(calculatedTimespan)); target = target.divide(BigInteger.valueOf(TARGET_TIMESPAN)); // Return the new difficulty setting DifficultyTarget resultTarget = new DifficultyTarget(target); DifficultyTarget maxTarget = bitcoinFactory.maxDifficultyTarget(); if (resultTarget.compareTo(maxTarget) > 0) return maxTarget; else resultTarget = new DifficultyTarget(resultTarget.getCompressedTarget()); // Normalize logger.debug("previous height {}, recalculated target is: {}", link.getHeight(), resultTarget); return resultTarget; }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private BigInteger step3ComputeLowerBound(final BigInteger s, final BigInteger modulus, final BigInteger lowerIntervalBound) { BigInteger lowerBound = lowerIntervalBound.multiply(s); lowerBound = lowerBound.subtract(BigInteger.valueOf(3).multiply(this.bigB)); lowerBound = lowerBound.add(BigInteger.ONE); lowerBound = lowerBound.divide(modulus); return lowerBound; }
From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java
private void stepTwoC() throws Exception { byte[] send;/* w w w . java2 s . com*/ IHttpRequestResponse response; byte[] request; BigInteger n = this.pubKey.getModulus(); loggerInstance.log(getClass(), "Step 2c: Searching with one interval left", Logger.LogLevel.INFO); // initial ri computation - ri = 2(b*(si-1)-2*B)/n BigInteger ri = this.si.multiply(this.m[0].upper); ri = ri.subtract(BigInteger.valueOf(2).multiply(this.bigB)); ri = ri.multiply(BigInteger.valueOf(2)); ri = ri.divide(n); // initial si computation BigInteger upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower); BigInteger lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper); // to counter .add operation in do while this.si = lowerBound.subtract(BigInteger.ONE); do { // Check if user has cancelled the worker if (isCancelled()) { loggerInstance.log(getClass(), "Decryption Attack Executor Worker cancelled by user", Logger.LogLevel.INFO); return; } this.si = this.si.add(BigInteger.ONE); // lowerBound <= si < upperBound if (this.si.compareTo(upperBound) > 0) { // new values ri = ri.add(BigInteger.ONE); upperBound = step2cComputeUpperBound(ri, n, this.m[0].lower); lowerBound = step2cComputeLowerBound(ri, n, this.m[0].upper); this.si = lowerBound; } send = prepareMsg(this.c0, this.si); request = this.requestResponse.getRequest(); String[] components = Decoder.getComponents(this.parameter.getJoseValue()); components[1] = Decoder.base64UrlEncode(send); String newComponentsConcatenated = Decoder.concatComponents(components); request = JoseParameter.updateRequest(request, this.parameter, helpers, newComponentsConcatenated); response = callbacks.makeHttpRequest(this.httpService, request); updateAmountRequest(); } while (oracle.getResult(response.getResponse()) != BleichenbacherPkcs1Oracle.Result.VALID); loggerInstance.log(getClass(), "Matching response: " + helpers.bytesToString(response.getResponse()), Logger.LogLevel.DEBUG); }
From source file:org.vafer.jdeb.ControlBuilder.java
/** * Creates a package control file from the specified file and adds the * <tt>Date</tt>, <tt>Distribution</tt> and <tt>Urgency</tt> fields if missing. * The <tt>Installed-Size</tt> field is also initialized to the actual size of * the package. The <tt>Maintainer</tt> field is overridden by the <tt>DEBEMAIL</tt> * and <tt>DEBFULLNAME</tt> environment variables if defined. * /* ww w . j a va 2s . c o m*/ * @param file the control file * @param pDataSize the size of the installed package */ public BinaryPackageControlFile createPackageControlFile(File file, BigInteger pDataSize) throws IOException, ParseException { FilteredFile controlFile = new FilteredFile(new FileInputStream(file), resolver); BinaryPackageControlFile packageControlFile = new BinaryPackageControlFile(controlFile.toString()); if (packageControlFile.get("Distribution") == null) { packageControlFile.set("Distribution", "unknown"); } if (packageControlFile.get("Urgency") == null) { packageControlFile.set("Urgency", "low"); } packageControlFile.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString()); // override the Version if the DEBVERSION environment variable is defined final String debVersion = System.getenv("DEBVERSION"); if (debVersion != null) { packageControlFile.set("Version", debVersion); console.info("Using version'" + debVersion + "' from the environment variables."); } // override the Maintainer field if the DEBFULLNAME and DEBEMAIL environment variables are defined final String debFullName = System.getenv("DEBFULLNAME"); final String debEmail = System.getenv("DEBEMAIL"); if (debFullName != null && debEmail != null) { final String maintainer = debFullName + " <" + debEmail + ">"; packageControlFile.set("Maintainer", maintainer); console.info("Using maintainer '" + maintainer + "' from the environment variables."); } return packageControlFile; }
From source file:co.rsk.remasc.Remasc.java
/** * Implements the actual Remasc distribution logic *///from w ww . j av a 2s . c o m void processMinersFees() { if (!(executionTx instanceof RemascTransaction)) { //Detect // 1) tx to remasc that is not the latest tx in a block // 2) invocation to remasc from another contract (ie call opcode) throw new RemascInvalidInvocationException("Invoked Remasc outside last tx of the block"); } this.addNewSiblings(); long blockNbr = executionBlock.getNumber(); long processingBlockNumber = blockNbr - remascConstants.getMaturity(); if (processingBlockNumber < 1) { logger.debug("First block has not reached maturity yet, current block is {}", blockNbr); return; } BlockHeader processingBlockHeader = blockStore .getBlockByHashAndDepth(executionBlock.getParentHash(), remascConstants.getMaturity() - 1) .getHeader(); // Adds current block fees to accumulated rewardBalance BigInteger processingBlockReward = BigInteger.valueOf(processingBlockHeader.getPaidFees()); BigInteger rewardBalance = provider.getRewardBalance(); rewardBalance = rewardBalance.add(processingBlockReward); provider.setRewardBalance(rewardBalance); if (processingBlockNumber - remascConstants.getSyntheticSpan() < 0) { logger.debug("First block has not reached maturity+syntheticSpan yet, current block is {}", executionBlock.getNumber()); return; } // Takes from rewardBalance this block's height reward. BigInteger fullBlockReward = rewardBalance.divide(BigInteger.valueOf(remascConstants.getSyntheticSpan())); rewardBalance = rewardBalance.subtract(fullBlockReward); provider.setRewardBalance(rewardBalance); // Pay RSK labs cut BigInteger payToRskLabs = fullBlockReward.divide(BigInteger.valueOf(remascConstants.getRskLabsDivisor())); transfer(remascConstants.getRskLabsAddress(), payToRskLabs); fullBlockReward = fullBlockReward.subtract(payToRskLabs); List<Sibling> siblings = provider.getSiblings().get(processingBlockNumber); if (CollectionUtils.isNotEmpty(siblings)) { // Block has siblings, reward distribution is more complex boolean previousBrokenSelectionRule = provider.getBrokenSelectionRule(); this.payWithSiblings(processingBlockHeader, fullBlockReward, siblings, previousBrokenSelectionRule); boolean brokenSelectionRule = this.isBrokenSelectionRule(processingBlockHeader, siblings); provider.setBrokenSelectionRule(brokenSelectionRule); } else { if (provider.getBrokenSelectionRule()) { // broken selection rule, apply punishment, ie burn part of the reward. BigInteger punishment = fullBlockReward .divide(BigInteger.valueOf(remascConstants.getPunishmentDivisor())); fullBlockReward = fullBlockReward.subtract(punishment); provider.setBurnedBalance(provider.getBurnedBalance().add(punishment)); } transfer(processingBlockHeader.getCoinbase(), fullBlockReward); provider.setBrokenSelectionRule(Boolean.FALSE); } this.removeUsedSiblings(processingBlockHeader); }
From source file:org.trnltk.numeral.DigitsToTextConverter.java
private String convertNaturalNumberToWords(BigInteger naturalNumber) { Validate.isTrue(naturalNumber.compareTo(ZERO) >= 0); Validate.isTrue(naturalNumber.compareTo(MAX_NATURAL_NUMBER_SUPPORTED) <= 0, "Given number " + naturalNumber + " is larger than maximum supported natural number " + MAX_NATURAL_NUMBER_SUPPORTED); StringBuilder result = new StringBuilder(); if (naturalNumber.compareTo(BigInteger.TEN) < 0) { result.append(NUMERAL_SYMBOL_NAMES.get(naturalNumber.intValue())); } else if (naturalNumber.compareTo(ONE_HUNDRED) < 0) { final BigInteger tensDigit = naturalNumber.divide(TEN); final BigInteger onesDigit = naturalNumber.mod(TEN); final String strTensDigit = TENS_MULTIPLES_NAMES.get(tensDigit.intValue()); final String strOnesDigit = onesDigit.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(onesDigit) : StringUtils.EMPTY;/*from w w w .j av a 2 s. c o m*/ result.append(strTensDigit).append(" ").append(strOnesDigit); } else if (naturalNumber.compareTo(ONE_THOUSAND) < 0) { final BigInteger hundredsDigit = naturalNumber.divide(ONE_HUNDRED); final BigInteger rest = naturalNumber.mod(ONE_HUNDRED); final String strHundredsDigit; if (hundredsDigit.equals(ZERO)) { strHundredsDigit = StringUtils.EMPTY; } else if (hundredsDigit.equals(ONE)) { strHundredsDigit = StringUtils.EMPTY; } else { strHundredsDigit = convertNaturalNumberToWords(hundredsDigit); } final String restStr = rest.compareTo(ZERO) > 0 ? convertNaturalNumberToWords(rest) : StringUtils.EMPTY; result.append(strHundredsDigit).append(" ").append(HUNDRED_NAME).append(" ").append(restStr); } else { int mostSignificantGroupBase = this.findMostSignificantGroupBase(naturalNumber); for (int i = mostSignificantGroupBase / 3; i > 0; i--) { int groupNumber = this.getNthGroupNumber(naturalNumber, i); //noinspection StatementWithEmptyBody if (groupNumber == 0) { // don't write 'sifir milyon' } else if (groupNumber == 1 && i == 1) { // don't write 'bir bin', but write 'bir milyon'(below) result.append(" ").append(THOUSAND_NAME); } else { final String strGroupNumber = this.convertNaturalNumberToWords(BigInteger.valueOf(groupNumber)); result.append(" ").append(strGroupNumber).append(" ").append(THOUSAND_POWER_NAMES.get(i)); } result = new StringBuilder(result.toString().trim()); } final BigInteger lastGroupNumber = naturalNumber.mod(ONE_THOUSAND); if (lastGroupNumber.compareTo(ZERO) > 0) result.append(" ").append(convertNaturalNumberToWords(lastGroupNumber)); } return result.toString().trim(); }
From source file:cn.iie.haiep.hbase.value.Bytes.java
/** * Iterate over keys within the passed inclusive range. *///w w w.java 2 s. c o m public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); final BigInteger diffBI = stopBI.subtract(startBI); final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
private BigInteger[] preventMalleability(BigInteger[] sigs, BigInteger curveN) { BigInteger cmpVal = curveN.divide(BigInteger.valueOf(2L)); BigInteger sval = sigs[1];//w w w.ja v a 2 s .co m if (sval.compareTo(cmpVal) == 1) { sigs[1] = curveN.subtract(sval); } return sigs; }
From source file:com.fratello.longevity.smooth.object.SpecialFile.java
private boolean testFilterProperty_Size(SpecialFile other) { String byteType = this.filter.getMetricSize(); BigInteger sourceSize = new BigInteger(String.valueOf(this.SIZE)); BigInteger targetSize = new BigInteger(String.valueOf(other.SIZE)); String num = ""; switch (byteType) { default:/*from ww w. java 2 s.c o m*/ case "BYTE": num = "1"; break; case "KILOBYTE": num = "1024"; break; case "MEGABYTE": num = "1048576"; break; case "GIGABYTE": num = "1073741824"; break; } sourceSize.multiply(new BigInteger(String.valueOf(num))); targetSize.multiply(new BigInteger(String.valueOf(num))); boolean sourceSizeIsBiggest = sourceSize.compareTo(targetSize) > 0; double requiredPercent = this.filter.getSizePercentMatchDouble(); if (sourceSizeIsBiggest) { double matchPercent = targetSize.divide(sourceSize).doubleValue(); if (!(matchPercent >= requiredPercent)) return false; } else { double matchPercent = sourceSize.divide(targetSize).doubleValue(); if (!(matchPercent >= requiredPercent)) return false; } return true; }
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. *//*from ww w . ja v a 2 s . co m*/ public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, boolean inclusive, final int num) { byte[] aPadded; byte[] bPadded; if (a.length < b.length) { aPadded = padTail(a, b.length - a.length); bPadded = b; } else if (b.length < a.length) { aPadded = a; bPadded = padTail(b, a.length - b.length); } else { aPadded = a; bPadded = b; } if (compareTo(aPadded, bPadded) >= 0) { throw new IllegalArgumentException("b <= a"); } if (num <= 0) { throw new IllegalArgumentException("num cannot be < 0"); } byte[] prependHeader = { 1, 0 }; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); final BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); if (inclusive) { diffBI = diffBI.add(BigInteger.ONE); } final BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } final BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } final Iterator<byte[]> iterator = new Iterator<byte[]>() { private int i = -1; @Override public boolean hasNext() { return i < num + 1; } @Override public byte[] next() { i++; if (i == 0) return a; if (i == num + 1) return b; BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i))); byte[] padded = curBI.toByteArray(); if (padded[1] == 0) padded = tail(padded, padded.length - 2); else padded = tail(padded, padded.length - 1); return padded; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return new Iterable<byte[]>() { @Override public Iterator<byte[]> iterator() { return iterator; } }; }