List of usage examples for java.math BigInteger compareTo
public int compareTo(BigInteger val)
From source file:de.decoit.visa.net.IPNetwork.java
/** * Increment the next free address pointer by 1. If the pointer leaves the * address range of this network an exception will be thrown. * * @throws IllegalStateException if the pointer leaves the address range of * this network/*from www . j av a 2 s.com*/ */ private void incrNextAddressMask() { BigInteger tmpMask = incrAddressMask(nextAddressMask, BigInteger.ONE); if (tmpMask.compareTo(lastAddressMask) > 0) { throw new IllegalStateException("New address not in address range of this network"); } nextAddressMask = tmpMask; }
From source file:net.bither.rawprivatekey.RawPrivateKeyDiceFragment.java
private boolean checkValue(byte[] data) { BigInteger value = new BigInteger(1, data).mod(ECKey.CURVE.getN()); if (value.compareTo(BigInteger.ZERO) == 0) { return false; }// w ww.j a va 2 s .c o m return true; }
From source file:hydrograph.ui.validators.impl.AdditionalParamDBValidationRule.java
/** * The Function will compare bigInteger values * @param value1/*from w ww .j a v a 2 s . com*/ * @param value2 * @return */ private boolean compareBigIntegerValue(String value1, String value2) { if (StringUtils.isNotBlank(value1) && StringUtils.isNotBlank(value2) && validateNumericField(value1) && validateNumericField(value2)) { BigInteger int1 = BigInteger.valueOf(Long.parseLong(value1)); BigInteger int2 = BigInteger.valueOf(Long.parseLong(value2)); if (int1.compareTo(int2) == -1) { return false; } } return true; }
From source file:org.ethereum.validator.ProofOfWorkRule.java
@Override public boolean isValid(Block block) { BlockHeader header = block.getHeader(); co.rsk.bitcoinj.core.NetworkParameters bitcoinNetworkParameters = SystemProperties.CONFIG .getBlockchainConfig().getCommonConstants().getBridgeConstants().getBtcParams(); byte[] bitcoinMergedMiningCoinbaseTransactionCompressed = header .getBitcoinMergedMiningCoinbaseTransaction(); co.rsk.bitcoinj.core.BtcBlock bitcoinMergedMiningBlock = bitcoinNetworkParameters.getDefaultSerializer() .makeBlock(header.getBitcoinMergedMiningHeader()); co.rsk.bitcoinj.core.PartialMerkleTree bitcoinMergedMiningMerkleBranch = new co.rsk.bitcoinj.core.PartialMerkleTree( bitcoinNetworkParameters, header.getBitcoinMergedMiningMerkleProof(), 0); BigInteger target = DifficultyUtils.difficultyToTarget(header.getDifficultyBI()); BigInteger bitcoinMergedMiningBlockHashBI = bitcoinMergedMiningBlock.getHash().toBigInteger(); if (bitcoinMergedMiningBlockHashBI.compareTo(target) > 0) { logger.error("Hash {} is higher than target {}", bitcoinMergedMiningBlockHashBI.toString(16), target.toString(16));// w ww .j a va 2s .co m return false; } byte[] bitcoinMergedMiningCoinbaseTransactionMidstate = new byte[RskMiningConstants.MIDSTATE_SIZE]; System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, 0, bitcoinMergedMiningCoinbaseTransactionMidstate, 8, RskMiningConstants.MIDSTATE_SIZE_TRIMMED); byte[] bitcoinMergedMiningCoinbaseTransactionTail = new byte[bitcoinMergedMiningCoinbaseTransactionCompressed.length - RskMiningConstants.MIDSTATE_SIZE_TRIMMED]; System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, RskMiningConstants.MIDSTATE_SIZE_TRIMMED, bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length); byte[] expectedCoinbaseMessageBytes = org.spongycastle.util.Arrays.concatenate(RskMiningConstants.RSK_TAG, header.getHashForMergedMining()); List<Byte> bitcoinMergedMiningCoinbaseTransactionTailAsList = java.util.Arrays .asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionTail)); List<Byte> expectedCoinbaseMessageBytesAsList = java.util.Arrays .asList(ArrayUtils.toObject(expectedCoinbaseMessageBytes)); int rskTagPosition = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, expectedCoinbaseMessageBytesAsList); if (rskTagPosition == -1) { logger.error( "bitcoin coinbase transaction tail message does not contain expected RSKBLOCK:RskBlockHeaderHash. Expected: {} . Actual: {} .", Arrays.toString(expectedCoinbaseMessageBytes), Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail)); return false; } /* * We check that the there is no other block before the rsk tag, to avoid a possible malleability attack: * If we have a mid state with 10 blocks, and the rsk tag, we can also have * another mid state with 9 blocks, 64bytes + the rsk tag, giving us two blocks with different hashes but the same spv proof. * */ if (rskTagPosition >= 64) { logger.error("bitcoin coinbase transaction tag position is bigger than expected 64. Actual: {}.", Integer.toString(rskTagPosition)); return false; } List<Byte> rskTagAsList = java.util.Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG)); if (rskTagPosition != Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, rskTagAsList)) { logger.error("The valid RSK tag is not the last RSK tag. Tail: {}.", Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail)); return false; } int remainingByteCount = bitcoinMergedMiningCoinbaseTransactionTail.length - rskTagPosition - RskMiningConstants.RSK_TAG.length - RskMiningConstants.BLOCK_HEADER_HASH_SIZE; if (remainingByteCount > RskMiningConstants.MAX_BYTES_AFTER_MERGED_MINING_HASH) { logger.error("More than 128 bytes after ROOOTSTOCK tag"); return false; } SHA256Digest digest = new SHA256Digest(bitcoinMergedMiningCoinbaseTransactionMidstate); digest.update(bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length); byte[] bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash = new byte[32]; digest.doFinal(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash, 0); co.rsk.bitcoinj.core.Sha256Hash bitcoinMergedMiningCoinbaseTransactionHash = co.rsk.bitcoinj.core.Sha256Hash .wrapReversed( co.rsk.bitcoinj.core.Sha256Hash.hash(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash)); List<co.rsk.bitcoinj.core.Sha256Hash> txHashesInTheMerkleBranch = new ArrayList<>(); co.rsk.bitcoinj.core.Sha256Hash merkleRoot = bitcoinMergedMiningMerkleBranch .getTxnHashAndMerkleRoot(txHashesInTheMerkleBranch); if (!merkleRoot.equals(bitcoinMergedMiningBlock.getMerkleRoot())) { logger.error("bitcoin merkle root of bitcoin block does not match the merkle root of merkle branch"); return false; } if (!txHashesInTheMerkleBranch.contains(bitcoinMergedMiningCoinbaseTransactionHash)) { logger.error("bitcoin coinbase transaction {} not included in merkle branch", bitcoinMergedMiningCoinbaseTransactionHash); return false; } return true; }
From source file:net.ripe.ipresource.IpRange.java
public List<IpRange> splitToPrefixes() { BigInteger rangeEnd = getEnd().getValue(); BigInteger currentRangeStart = getStart().getValue(); int startingPrefixLength = getType().getBitSize(); List<IpRange> prefixes = new LinkedList<IpRange>(); while (currentRangeStart.compareTo(rangeEnd) <= 0) { int maximumPrefixLength = getMaximumLengthOfPrefixStartingAtIpAddressValue(currentRangeStart, startingPrefixLength);/*from w w w . jav a 2 s .co m*/ BigInteger maximumSizeOfPrefix = rangeEnd.subtract(currentRangeStart).add(BigInteger.ONE); BigInteger currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength); while ((currentSizeOfPrefix.compareTo(maximumSizeOfPrefix) > 0) && (maximumPrefixLength > 0)) { maximumPrefixLength--; currentSizeOfPrefix = BigInteger.valueOf(2).pow(maximumPrefixLength); } BigInteger currentRangeEnd = currentRangeStart .add(BigInteger.valueOf(2).pow(maximumPrefixLength).subtract(BigInteger.ONE)); IpRange prefix = (IpRange) IpResourceRange.assemble(currentRangeStart, currentRangeEnd, getType()); prefixes.add(prefix); currentRangeStart = currentRangeEnd.add(BigInteger.ONE); } return prefixes; }
From source file:libra.preprocess.common.kmerhistogram.KmerRangePartitioner.java
public KmerRangePartition[] getEqualAreaPartitions() { KmerRangePartition[] partitions = new KmerRangePartition[this.numPartitions]; // calc 4^kmerSize BigInteger kmerend = BigInteger.valueOf(4).pow(this.kmerSize); BigDecimal bdkmerend = new BigDecimal(kmerend); // moves between x (0~1) y (0~1) // sum of area (0.5) double kmerArea = 0.5; double sliceArea = kmerArea / this.numPartitions; // we think triangle is horizontally flipped so calc get easier. double x1 = 0; List<BigInteger> widths = new ArrayList<BigInteger>(); BigInteger widthSum = BigInteger.ZERO; for (int i = 0; i < this.numPartitions; i++) { // x2*x2 = 2*sliceArea + x1*x1 double temp = (2 * sliceArea) + (x1 * x1); double x2 = Math.sqrt(temp); BigDecimal bdx1 = BigDecimal.valueOf(x1); BigDecimal bdx2 = BigDecimal.valueOf(x2); // if i increases, bdw will be decreased BigDecimal bdw = bdx2.subtract(bdx1); BigInteger bw = bdw.multiply(bdkmerend).toBigInteger(); if (bw.compareTo(BigInteger.ZERO) <= 0) { bw = BigInteger.ONE;// w ww. j a va2 s . c om } if (widthSum.add(bw).compareTo(kmerend) > 0) { bw = kmerend.subtract(widthSum); } if (i == this.numPartitions - 1) { // last case if (widthSum.add(bw).compareTo(kmerend) < 0) { bw = kmerend.subtract(widthSum); } } // save it widths.add(bw); widthSum = widthSum.add(bw); x1 = x2; } BigInteger cur_begin = BigInteger.ZERO; for (int i = 0; i < this.numPartitions; i++) { BigInteger slice_width = widths.get(this.numPartitions - 1 - i); BigInteger slice_begin = cur_begin; if (slice_begin.add(slice_width).compareTo(kmerend) > 0) { slice_width = kmerend.subtract(slice_begin); } BigInteger slice_end = cur_begin.add(slice_width).subtract(BigInteger.ONE); KmerRangePartition slice = new KmerRangePartition(this.kmerSize, this.numPartitions, i, slice_width, slice_begin, slice_end); partitions[i] = slice; cur_begin = cur_begin.add(slice_width); } return partitions; }
From source file:org.apache.hama.util.Bytes.java
/** * Split passed range. Expensive operation relatively. Uses BigInteger math. * //from ww w.ja va 2 s.co m * @param a Beginning of range * @param b End of range * @param num Number of times to split range. Pass 1 if you want to split the * range in two; i.e. one split. * @return Array of dividing values */ public static byte[][] split(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 }; BigInteger startBI = new BigInteger(add(prependHeader, aPadded)); BigInteger stopBI = new BigInteger(add(prependHeader, bPadded)); BigInteger diffBI = stopBI.subtract(startBI); BigInteger splitsBI = BigInteger.valueOf(num + 1); if (diffBI.compareTo(splitsBI) < 0) { return null; } BigInteger intervalBI; try { intervalBI = diffBI.divide(splitsBI); } catch (Exception e) { LOG.error("Exception caught during division", e); return null; } byte[][] result = new byte[num + 2][]; result[0] = a; for (int i = 1; i <= num; i++) { 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); result[i] = padded; } result[num + 1] = b; return result; }
From source file:com.bitsofproof.supernode.test.APITest.java
private void mineBlock(Block b) { for (int nonce = Integer.MIN_VALUE; nonce <= Integer.MAX_VALUE; ++nonce) { b.setNonce(nonce);/*from w w w . java 2 s . c om*/ b.computeHash(); BigInteger hashAsInteger = new Hash(b.getHash()).toBigInteger(); if (hashAsInteger.compareTo(Difficulty.getTarget(b.getDifficultyTarget())) <= 0) { break; } } }
From source file:org.multibit.utils.CSMiscUtils.java
public static boolean canSafelySpendWhileRespectingMigrationFee(BitcoinController bitcoinController, Wallet wallet, BigInteger amountSatoshis) { BigInteger migrationFee = calcMigrationFeeSatoshis(bitcoinController, wallet); if (migrationFee == null) return false; BigInteger availableBalance = wallet.getBalance(Wallet.BalanceType.AVAILABLE); BigInteger spendingLimit = availableBalance.subtract(migrationFee); // System.out.println(">>>> Available = "+availableBalance); // System.out.println(">>>> Migration fee = "+migrationFee); // System.out.println(">>>> Spending limit= "+spendingLimit); // System.out.println(">>>> Spend amount = "+amountSatoshis); return (amountSatoshis.compareTo(spendingLimit) <= 0); }
From source file:org.openremote.controller.protocol.http.HttpGetCommand.java
private int resolveResultAsInteger(String rawResult) throws ConversionException { try {/* www . j av a 2 s . com*/ BigInteger min = new BigInteger(Integer.toString(Integer.MIN_VALUE)); BigInteger max = new BigInteger(Integer.toString(Integer.MAX_VALUE)); BigInteger result = new BigInteger(rawResult); if (result.compareTo(min) < 0) { return Integer.MIN_VALUE; } else if (result.compareTo(max) > 0) { return Integer.MAX_VALUE; } else { return result.intValue(); } } catch (NumberFormatException e) { throw new ConversionException("Cannot parse device return value to Java integer: " + e.getMessage(), e); } }