List of usage examples for java.math BigInteger valueOf
private static BigInteger valueOf(int val[])
From source file:com.wms.utils.DataUtil.java
public static BigInteger ipv6ToNumber(String addr) { int startIndex = addr.indexOf("::"); if (startIndex != -1) { String firstStr = addr.substring(0, startIndex); String secondStr = addr.substring(startIndex + 2, addr.length()); BigInteger first = ipv6ToNumber(firstStr); int x = countChar(addr, ':'); int y = countChar(secondStr, ':'); //first = first.shiftLeft(16 * (7 - x)).add(ipv6ToNumber(secondStr)); first = first.shiftLeft(16 * (7 - x + y)); first = first.add(ipv6ToNumber(secondStr)); return first; }/*from w w w . ja va 2s . co m*/ String[] strArr = addr.split(":"); BigInteger retValue = BigInteger.valueOf(0); for (int i = 0; i < strArr.length; i++) { BigInteger bi = new BigInteger(strArr[i], 16); retValue = retValue.shiftLeft(16).add(bi); } return retValue; }
From source file:co.rsk.peg.BridgeSerializationUtilsTest.java
@Test public void serializePendingFederation() throws Exception { PowerMockito.mockStatic(RLP.class); mock_RLP_encodeList();// w w w .j a v a 2s. co m mock_RLP_encodeElement(); byte[][] publicKeyBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(), BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), }; PendingFederation pendingFederation = new PendingFederation(Arrays.asList(new BtcECKey[] { BtcECKey.fromPublicOnly(publicKeyBytes[0]), BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]), BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]), BtcECKey.fromPublicOnly(publicKeyBytes[5]), })); byte[] result = BridgeSerializationUtils.serializePendingFederation(pendingFederation); StringBuilder expectedBuilder = new StringBuilder(); pendingFederation.getPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> { expectedBuilder.append("dd"); expectedBuilder.append(Hex.toHexString(key.getPubKey())); }); byte[] expected = Hex.decode(expectedBuilder.toString()); Assert.assertTrue(Arrays.equals(expected, result)); }
From source file:org.mitre.jwt.JwtTest.java
/** * Creates a certificate./*from w w w .j av a 2 s . c o m*/ * * @param commonName * @param daysNotValidBefore * @param daysNotValidAfter * @return */ public static X509V3CertificateGenerator createCertificate(String commonName, int daysNotValidBefore, int daysNotValidAfter) { // BC sez X509V3CertificateGenerator is deprecated and the docs say to // use another, but it seemingly isn't included jar... X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * daysNotValidBefore))); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * daysNotValidAfter))); v3CertGen.setSubjectDN(new X509Principal("CN=" + commonName + ", OU=None, O=None L=None, C=None")); return v3CertGen; }
From source file:demo.config.PropertyConverter.java
/** * Convert the specified object into a BigInteger. * //from ww w . java 2s . c om * @param value * the value to convert * @return the converted value * @throws ConversionException * thrown if the value cannot be converted to a BigInteger */ public static BigInteger toBigInteger(Object value) throws ConversionException { Number n = toNumber(value, BigInteger.class); if (n instanceof BigInteger) { return (BigInteger) n; } else { return BigInteger.valueOf(n.longValue()); } }
From source file:co.rsk.peg.BridgeSupport.java
/** * In case of a lock tx: Transfers some SBTCs to the sender of the btc tx and keeps track of the new UTXOs available for spending. * In case of a release tx: Keeps track of the change UTXOs, now available for spending. * @param btcTx The bitcoin transaction/*from w ww.j a v a 2s .c o m*/ * @param height The height of the bitcoin block that contains the tx * @param pmt Partial Merklee Tree that proves the tx is included in the btc block * @throws BlockStoreException * @throws IOException */ public void registerBtcTransaction(BtcTransaction btcTx, int height, PartialMerkleTree pmt) throws BlockStoreException, IOException { Context.propagate(btcContext); // Check the tx was not already processed if (provider.getBtcTxHashesAlreadyProcessed().contains(btcTx.getHash())) { logger.warn("Supplied tx was already processed"); return; } // Check the tx is in the partial merkle tree List<Sha256Hash> hashesInPmt = new ArrayList<>(); Sha256Hash merkleRoot = pmt.getTxnHashAndMerkleRoot(hashesInPmt); if (!hashesInPmt.contains(btcTx.getHash())) { logger.warn("Supplied tx is not in the supplied partial merkle tree"); panicProcessor.panic("btclock", "Supplied tx is not in the supplied partial merkle tree"); return; } if (height < 0) { logger.warn("Height is " + height + " but should be greater than 0"); panicProcessor.panic("btclock", "Height is " + height + " but should be greater than 0"); return; } // Check there are at least N blocks on top of the supplied height int headHeight = btcBlockChain.getBestChainHeight(); if ((headHeight - height + 1) < bridgeConstants.getBtc2RskMinimumAcceptableConfirmations()) { logger.warn("At least " + bridgeConstants.getBtc2RskMinimumAcceptableConfirmations() + " confirmations are required, but there are only " + (headHeight - height) + " confirmations"); return; } // Check the the merkle root equals merkle root of btc block at specified height in the btc best chain BtcBlock blockHeader = BridgeUtils.getStoredBlockAtHeight(btcBlockStore, height).getHeader(); if (!blockHeader.getMerkleRoot().equals(merkleRoot)) { logger.warn("Supplied merkle root " + merkleRoot + "does not match block's merkle root " + blockHeader.getMerkleRoot()); panicProcessor.panic("btclock", "Supplied merkle root " + merkleRoot + "does not match block's merkle root " + blockHeader.getMerkleRoot()); return; } // Checks the transaction contents for sanity btcTx.verify(); if (btcTx.getInputs().isEmpty()) { logger.warn("Tx has no inputs " + btcTx); panicProcessor.panic("btclock", "Tx has no inputs " + btcTx); return; } // Specific code for lock/release/none txs if (BridgeUtils.isLockTx(btcTx, provider.getWallet(), bridgeConstants)) { logger.debug("This is a lock tx {}", btcTx); Script scriptSig = btcTx.getInput(0).getScriptSig(); if (scriptSig.getChunks().size() != 2) { logger.warn("First input does not spend a Pay-to-PubkeyHash " + btcTx.getInput(0)); panicProcessor.panic("btclock", "First input does not spend a Pay-to-PubkeyHash " + btcTx.getInput(0)); return; } // Tx is a lock tx, transfer SBTC to the sender of the BTC // The RSK account to update is the one that matches the pubkey "spent" on the first bitcoin tx input byte[] data = scriptSig.getChunks().get(1).data; org.ethereum.crypto.ECKey key = org.ethereum.crypto.ECKey.fromPublicOnly(data); byte[] sender = key.getAddress(); Coin amount = btcTx.getValueSentToMe(provider.getWallet()); transfer(rskRepository, Hex.decode(PrecompiledContracts.BRIDGE_ADDR), sender, Denomination.satoshisToWeis(BigInteger.valueOf(amount.getValue()))); } else if (BridgeUtils.isReleaseTx(btcTx, bridgeConstants)) { logger.debug("This is a release tx {}", btcTx); // do-nothing // We could call removeUsedUTXOs(btcTx) here, but we decided to not do that. // Used utxos should had been removed when we created the release tx. // Invoking removeUsedUTXOs() here would make "some" sense in theses scenarios: // a) In testnet, devnet or local: we restart the RSK blockchain whithout changing the federation address. We don't want to have utxos that were already spent. // Open problem: TxA spends TxB. registerBtcTransaction() for TxB is called, it spends a utxo the bridge is not yet aware of, // so nothing is removed. Then registerBtcTransaction() for TxA and the "already spent" utxo is added as it was not spent. // When is not guaranteed to be called in the chronological order, so a Federator can inform // b) In prod: Federator created a tx manually or the federation was compromised and some utxos were spent. Better not try to spend them. // Open problem: For performance removeUsedUTXOs() just removes 1 utxo } else { logger.warn("This is not a lock nor a release tx {}", btcTx); panicProcessor.panic("btclock", "This is not a lock nor a release tx " + btcTx); return; } Sha256Hash btcTxHash = btcTx.getHash(); // Mark tx as processed provider.getBtcTxHashesAlreadyProcessed().add(btcTxHash); saveNewUTXOs(btcTx); logger.info("BTC Tx {} processed in RSK", btcTxHash); }
From source file:Peer.java
/** * Construct a peers finger table using getSuccessor. */// www. jav a 2s . c o m public void constructFingerTable(int mbits) { lg.log(Level.FINEST, "constructFingerTable entry"); // clear the current finger table ft.clear(); try { // For each mbit ... for (int i = 1; i <= mbits; i++) { // make a new finger entry FingerEntry fe = new FingerEntry(); // Calculate (nodeid+2^(i-1))%max_key Key fingerid = new Key().add(nodeid).add(new Key(BigInteger.valueOf((int) Math.pow(2, i - 1)))) .mod(new Key(BigInteger.valueOf((int) Math.pow(2, mbits)))); // Adding a new finger entry fe.setId(fingerid); lg.log(Level.FINER, "Peer " + nodeid + " Initiating getSuccessor on key " + fingerid); fe.setNodeId(getSuccessor(fingerid)); ft.addFingerEntry(fe); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } lg.log(Level.FINEST, "constructFingerTable exit"); }
From source file:com.cognitect.transit.TransitMPTest.java
public void testReadRatio() throws IOException { final String[] ratioRep = { "~n1", "~n2" }; Map thing = new HashMap() { {/*from w w w. jav a 2s.c om*/ put("~#ratio", ratioRep); } }; Ratio r = readerOf(thing).read(); assertEquals(BigInteger.valueOf(1), r.getNumerator()); assertEquals(BigInteger.valueOf(2), r.getDenominator()); assertEquals(0.5d, r.getValue().doubleValue(), 0.01d); }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
public BigInteger getHistoryId(Gmail service, String userId, Credential credential) throws IOException { BigInteger historyId = null;//from www . j a v a 2 s.c o m if (getStartHistoyId() != null) { historyId = getStartHistoyId(); } else { HttpResponse response = service.users().getProfile("me").buildHttpRequest().execute(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent())); StringBuffer res = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { res.append(line); //logger.warning(line); } reader.close(); // JSONObject jsonObj = new JSONObject(res); Gson gson = new Gson(); GmailProfileData gmailProfileData = gson.fromJson(res.toString(), GmailProfileData.class); logger.warning(" historyId : " + gmailProfileData.getHistoryId()); historyId = BigInteger.valueOf(Long.parseLong(gmailProfileData.getHistoryId())); // historyId = BigInteger.valueOf(Long.parseLong("14085")); } finally { response.disconnect(); } } return historyId; // return BigInteger.valueOf(Long.parseLong("14085")); }
From source file:com.amazonaws.services.kinesis.log4j.helpers.AmazonKinesisPutRecordsHelper.java
public static int calculateShardBucket(String partitionKey, int totalNumOfShards) { MessageDigest m = null;/* w w w. j a v a 2 s.c om*/ int shardBucket = 1; try { m = MessageDigest.getInstance("MD5"); m.reset(); m.update(partitionKey.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); shardBucket = bigInt.mod(BigInteger.valueOf(totalNumOfShards)).intValue() + 1; } catch (NoSuchAlgorithmException e) { //ignore } return shardBucket; }
From source file:it.cnr.icar.eric.server.query.federation.FederatedQueryProcessor.java
private AdhocQueryResponse getUnifiedResponse() throws RegistryException { AdhocQueryResponse response = null;/*from w w w. ja v a2 s .c o m*/ try { response = bu.queryFac.createAdhocQueryResponse(); RegistryObjectListType ebRegistryObjectListType = bu.rimFac.createRegistryObjectListType(); response.setRegistryObjectList(ebRegistryObjectListType); int maxTotalResultCount = -1; RegistryErrorList ebRegistryErrorList = null; Iterator<AdhocQueryResponse> i = responses.iterator(); while (i.hasNext()) { AdhocQueryResponse ebAdhocQueryResponse = i.next(); int totalResultCount = ebAdhocQueryResponse.getTotalResultCount().intValue(); if (totalResultCount > maxTotalResultCount) { maxTotalResultCount = totalResultCount; } if ((ebAdhocQueryResponse.getRegistryErrorList() != null) && (ebAdhocQueryResponse.getRegistryErrorList().getRegistryError().size() > 0)) { if (ebRegistryErrorList == null) { ebRegistryErrorList = bu.rsFac.createRegistryErrorList(); response.setRegistryErrorList(ebRegistryErrorList); } response.getRegistryErrorList().getRegistryError() .addAll(ebAdhocQueryResponse.getRegistryErrorList().getRegistryError()); } //Spec Issue: How to handle duplicate id across registries?? //Need to return one. Which one? The latest? Probably the one from current registry. //May require always querying current registry last since code below keeps replacing existing objects //with new ones that have same id. if (ebAdhocQueryResponse.getRegistryObjectList() != null) { IdentifiableComparator comparator = new IdentifiableComparator(); List<JAXBElement<? extends IdentifiableType>> unifiedObjects = response.getRegistryObjectList() .getIdentifiable(); List<JAXBElement<? extends IdentifiableType>> currentObjects = ebAdhocQueryResponse .getRegistryObjectList().getIdentifiable(); Collections.sort(unifiedObjects, comparator); //Remove duplicates. //unifiedObjects.removeAll(currentObjects) will not work as there is no comparator implemented for JAXB objects Iterator<JAXBElement<? extends IdentifiableType>> currentObjectsIter = currentObjects .iterator(); while (currentObjectsIter.hasNext()) { RegistryObjectType currentObject = (RegistryObjectType) currentObjectsIter.next() .getValue(); int index = Collections.binarySearch(unifiedObjects, currentObject, comparator); if (index >= 0) { unifiedObjects.remove(index); log.trace("Removing duplicate object returned by a previous registry: id=" + currentObject.getId() + " name=" + bu.getInternationalStringAsString(currentObject.getName())); } log.trace("Adding object returned by registry: id=" + currentObject.getId() + " name=" + bu.getInternationalStringAsString(currentObject.getName())); } //Add the currentObjects to unified objects unifiedObjects.addAll(currentObjects); } } if ((response.getRegistryErrorList() != null) && (response.getRegistryErrorList().getRegistryError().size() > 0)) { response.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Failure); } else { response.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success); } //Set iterative query related attributes response.setStartIndex(adhocQueryRequest.getStartIndex()); response.setTotalResultCount(BigInteger.valueOf(maxTotalResultCount)); } catch (JAXRException e) { throw new RegistryException(e); } return response; }