List of usage examples for java.math BigInteger subtract
public BigInteger subtract(BigInteger val)
From source file:piuk.MyBlockChain.java
@SuppressWarnings("unchecked") public void onMessage(WebSocketMessage wmessage) { System.out.println("OnMessage()"); try {/*www .j a v a2s. co m*/ String message = wmessage.getText(); System.out.println("Websocket() onMessage() " + message); Map<String, Object> top = (Map<String, Object>) JSONValue.parse(message); if (top == null) return; String op = (String) top.get("op"); if (op.equals("block")) { Map<String, Object> x = (Map<String, Object>) top.get("x"); Sha256Hash hash = new Sha256Hash(Hex.decode((String) x.get("hash"))); int blockIndex = ((Number) x.get("blockIndex")).intValue(); int blockHeight = ((Number) x.get("height")).intValue(); long time = ((Number) x.get("time")).longValue(); MyBlock block = new MyBlock(Constants.NETWORK_PARAMETERS); block.hash = hash; block.blockIndex = blockIndex; block.time = time; this.latestBlock = new StoredBlock(block, BigInteger.ZERO, blockHeight); List<MyTransaction> transactions = remoteWallet.getMyTransactions(); List<Number> txIndexes = (List<Number>) x.get("txIndexes"); for (Number txIndex : txIndexes) { for (MyTransaction tx : transactions) { MyTransactionConfidence confidence = (MyTransactionConfidence) tx.getConfidence(); if (tx.txIndex == txIndex.intValue() && confidence.height != blockHeight) { confidence.height = blockHeight; confidence.runListeners(); } } } for (PeerEventListener listener : listeners) { listener.onBlocksDownloaded(null, block, 0); } } else if (op.equals("utx")) { Map<String, Object> x = (Map<String, Object>) top.get("x"); WalletTransaction tx = MyTransaction.fromJSONDict(x); BigInteger result = BigInteger.ZERO; BigInteger previousBalance = remoteWallet.getBitcoinJWallet().final_balance; for (TransactionInput input : tx.getTransaction().getInputs()) { //if the input is from me subtract the value MyTransactionInput myinput = (MyTransactionInput) input; if (remoteWallet.isAddressMine(input.getFromAddress().toString())) { result = result.subtract(myinput.value); remoteWallet .getBitcoinJWallet().final_balance = remoteWallet.getBitcoinJWallet().final_balance .subtract(myinput.value); remoteWallet.getBitcoinJWallet().total_sent = remoteWallet.getBitcoinJWallet().total_sent .add(myinput.value); } } for (TransactionOutput output : tx.getTransaction().getOutputs()) { //if the input is from me subtract the value MyTransactionOutput myoutput = (MyTransactionOutput) output; if (remoteWallet.isAddressMine(myoutput.getToAddress().toString())) { result = result.add(myoutput.getValue()); remoteWallet .getBitcoinJWallet().final_balance = remoteWallet.getBitcoinJWallet().final_balance .add(myoutput.getValue()); remoteWallet .getBitcoinJWallet().total_received = remoteWallet.getBitcoinJWallet().total_sent .add(myoutput.getValue()); } } MyTransaction mytx = (MyTransaction) tx.getTransaction(); mytx.result = result; remoteWallet.getBitcoinJWallet().addWalletTransaction(tx); if (result.compareTo(BigInteger.ZERO) >= 0) { System.out.println("On Received"); remoteWallet.getBitcoinJWallet().invokeOnCoinsReceived(tx.getTransaction(), previousBalance, remoteWallet.getBitcoinJWallet().final_balance); } else { remoteWallet.getBitcoinJWallet().invokeOnCoinsSent(tx.getTransaction(), previousBalance, remoteWallet.getBitcoinJWallet().final_balance); } } else if (op.equals("on_change")) { String newChecksum = (String) top.get("checksum"); String oldChecksum = remoteWallet.getChecksum(); System.out.println("On change " + newChecksum + " " + oldChecksum); if (!newChecksum.equals(oldChecksum)) { try { String newPayload = MyRemoteWallet.getWalletPayload(remoteWallet.getGUID(), remoteWallet.getSharedKey(), oldChecksum); if (newPayload == null) return; remoteWallet.setPayload(newPayload); remoteWallet.getBitcoinJWallet().invokeOnChange(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static boolean isGoodPrime(byte[] prime, int g) { if (!(g >= 2 && g <= 7)) { return false; }/*from ww w.j a va 2 s . c o m*/ if (prime.length != 256 || prime[0] >= 0) { return false; } BigInteger dhBI = new BigInteger(1, prime); if (g == 2) { // p mod 8 = 7 for g = 2; BigInteger res = dhBI.mod(BigInteger.valueOf(8)); if (res.intValue() != 7) { return false; } } else if (g == 3) { // p mod 3 = 2 for g = 3; BigInteger res = dhBI.mod(BigInteger.valueOf(3)); if (res.intValue() != 2) { return false; } } else if (g == 5) { // p mod 5 = 1 or 4 for g = 5; BigInteger res = dhBI.mod(BigInteger.valueOf(5)); int val = res.intValue(); if (val != 1 && val != 4) { return false; } } else if (g == 6) { // p mod 24 = 19 or 23 for g = 6; BigInteger res = dhBI.mod(BigInteger.valueOf(24)); int val = res.intValue(); if (val != 19 && val != 23) { return false; } } else if (g == 7) { // p mod 7 = 3, 5 or 6 for g = 7. BigInteger res = dhBI.mod(BigInteger.valueOf(7)); int val = res.intValue(); if (val != 3 && val != 5 && val != 6) { return false; } } String hex = bytesToHex(prime); if (hex.equals( "C71CAEB9C6B1C9048E6C522F70F13F73980D40238E3E21C14934D037563D930F48198A0AA7C14058229493D22530F4DBFA336F6E0AC925139543AED44CCE7C3720FD51F69458705AC68CD4FE6B6B13ABDC9746512969328454F18FAF8C595F642477FE96BB2A941D5BCD1D4AC8CC49880708FA9B378E3C4F3A9060BEE67CF9A4A4A695811051907E162753B56B0F6B410DBA74D8A84B2A14B3144E0EF1284754FD17ED950D5965B4B9DD46582DB1178D169C6BC465B0D6FF9CA3928FEF5B9AE4E418FC15E83EBEA0F87FA9FF5EED70050DED2849F47BF959D956850CE929851F0D8115F635B105EE2E4E15D04B2454BF6F4FADF034B10403119CD8E3B92FCC5B")) { return true; } BigInteger dhBI2 = dhBI.subtract(BigInteger.valueOf(1)).divide(BigInteger.valueOf(2)); return !(!dhBI.isProbablePrime(30) || !dhBI2.isProbablePrime(30)); }
From source file:PalidromeArray.java
public BigInteger get(BigInteger position) { /**/*from w ww.j ava 2 s. co m*/ * {1,4,6,4,1} would have {1,4,6} in our array * 0: return 1 * 1: return 4 * 2: return 6 * 3: return 4 * 4: return 1 * totalLength = 5 * halfLength = 3 * get(0) returns #0 * get(1) returns #1 * get(2) returns #2 * get(3) returns #1 * get(4) returns #0 * * {1,3,3,1} would have {1,3} in our array * array.length = 2 * 0: return 1 * 1: return 3 * 2: return 3 * 3: return 1 * totalLength = 4 * halfLength = 2 * get(0) returns #0 * get(1) returns #1 * get(2) returns #1 * get(3) returns #0 */ if (position.subtract(halfLength).signum() < 0) return array.get(position); BigInteger mid = halfLength.subtract(BigInteger.ONE); if (isEven) return array.get(mid.subtract(position.subtract(halfLength))); return array.get(mid.subtract(position.subtract(mid))); }
From source file:org.apache.flink.graph.library.clustering.undirected.TriadicCensus.java
@Override public Result getResult() { // vertex metrics BigInteger bigVertexCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfVertices()); BigInteger bigEdgeCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfEdges()); BigInteger bigTripletCount = BigInteger.valueOf(vertexMetrics.getResult().getNumberOfTriplets()); // triangle count BigInteger bigTriangleCount = BigInteger.valueOf(triangleCount.getResult()); BigInteger one = BigInteger.ONE; BigInteger two = BigInteger.valueOf(2); BigInteger three = BigInteger.valueOf(3); BigInteger six = BigInteger.valueOf(6); // counts as ordered in TriadicCensus.Result BigInteger[] counts = new BigInteger[4]; // triads with three connecting edges = closed triplet = triangle counts[3] = bigTriangleCount;/* ww w. ja va 2s . c om*/ // triads with two connecting edges = open triplet; // deduct each triplet having been counted three times per triangle counts[2] = bigTripletCount.subtract(bigTriangleCount.multiply(three)); // triads with one connecting edge; each edge pairs with `vertex count - 2` vertices // then deduct twice for each open triplet and three times for each triangle counts[1] = bigEdgeCount.multiply(bigVertexCount.subtract(two)).subtract(counts[2].multiply(two)) .subtract(counts[3].multiply(three)); // triads with zero connecting edges; // (vertex count choose 3) minus earlier counts counts[0] = bigVertexCount.multiply(bigVertexCount.subtract(one)).multiply(bigVertexCount.subtract(two)) .divide(six).subtract(counts[1]).subtract(counts[2]).subtract(counts[3]); return new Result(counts); }
From source file:com.ery.ertc.estorm.util.Bytes.java
/** * Iterate over keys within the passed range. *//*from www.j a 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; } }; }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {//from w w w .j a va2 s .c o m // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:org.apache.kylin.common.util.Bytes.java
/** * Iterate over keys within the passed range. *//*w w w . j a va 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 + 1L); 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:devcoin.wallet.ui.SendCoinsFragment.java
private void validateAmounts(final boolean popups) { isValidAmounts = false;/*w w w. j a va 2 s .co m*/ final BigInteger amount = amountCalculatorLink.getAmount(); if (amount == null) { // empty amount if (popups) popupMessage(amountCalculatorLink.activeView(), getString(R.string.send_coins_fragment_amount_empty)); } else if (amount.signum() > 0) { final BigInteger estimated = wallet.getBalance(BalanceType.ESTIMATED); final BigInteger available = wallet.getBalance(BalanceType.AVAILABLE); final BigInteger pending = estimated.subtract(available); // TODO subscribe to wallet changes final BigInteger availableAfterAmount = available.subtract(amount); final boolean enoughFundsForAmount = availableAfterAmount.signum() >= 0; if (enoughFundsForAmount) { // everything fine isValidAmounts = true; } else { // not enough funds for amount if (popups) popupAvailable(amountCalculatorLink.activeView(), available, pending); } } else { // invalid amount if (popups) popupMessage(amountCalculatorLink.activeView(), getString(R.string.send_coins_fragment_amount_error)); } updateView(); }
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];//from ww w.j a v a 2s . c om if (sval.compareTo(cmpVal) == 1) { sigs[1] = curveN.subtract(sval); } return sigs; }
From source file:Ternary.java
public Ternary(BigInteger toConvert) { this();//from w ww. j a v a 2 s.c o m int position = 0; BigInteger remaining = toConvert; BigInteger rounded, left; while (!remaining.equals(BigInteger.ZERO)) { rounded = ((new BigDecimal(remaining)).divide(bdThree, 0, BigDecimal.ROUND_HALF_UP)).toBigInteger(); left = remaining.subtract(rounded.multiply(biThree)); if (left.equals(BigInteger.ONE)) setTrit(position++, Trit.POSITIVE); else if (left.equals(BigInteger.ZERO)) setTrit(position++, Trit.NEUTRAL); else setTrit(position++, Trit.NEGATIVE); remaining = rounded; } }