Example usage for java.math BigInteger add

List of usage examples for java.math BigInteger add

Introduction

In this page you can find the example usage for java.math BigInteger add.

Prototype

BigInteger add(long val) 

Source Link

Document

Package private methods used by BigDecimal code to add a BigInteger with a long.

Usage

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * Creates space for an additional amount of nodes at the specified position in the specified node.
 *
 * @param con        an open and valid connection
 * @param seq        reference to the sequencer
 * @param mode       tree mode//from   w  w  w.ja  v a  2s  .  c o  m
 * @param nodeId     the node to work on
 * @param position   the position within the child nodes (0 based)
 * @param additional the amount of additional nodes to make space for
 * @return the used spacing
 * @throws FxApplicationException on errors
 */
public BigInteger makeSpace(Connection con, SequencerEngine seq, FxTreeMode mode, long nodeId, int position,
        final int additional) throws FxApplicationException {
    FxTreeNodeInfoSpreaded nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, nodeId);
    BigInteger boundaries[] = getBoundaries(con, nodeInfo, position);

    int totalChildCount = nodeInfo.getTotalChildCount() + additional;
    boolean hasSpace = nodeInfo.hasSpaceFor(totalChildCount, 2);
    /*if( hasSpace )
    return nodeInfo.getSpacing(totalChildCount);*/

    // Determine node to work on
    while (!hasSpace) {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, nodeInfo.getParentId());
        totalChildCount += nodeInfo.getTotalChildCount() + 1;
        hasSpace = nodeInfo.hasSpaceFor(totalChildCount, 2);
        if (!hasSpace && nodeInfo.isRoot()) {
            throw new FxUpdateException("ex.tree.makeSpace.failed");
        }
    }

    // Allocate/Reorganize space
    BigInteger spacing = nodeInfo.getSpacing(totalChildCount);
    int spaceCount = (additional * 2) + 1;
    BigInteger insertSpace = spacing.multiply(BigInteger.valueOf(spaceCount));
    insertSpace = insertSpace.add(BigInteger.valueOf(additional * 2));

    reorganizeSpace(con, seq, mode, mode, nodeInfo.getId(), false, spacing, null, nodeInfo, position,
            insertSpace, boundaries, 0, null, false, false, false);
    return spacing;
}

From source file:org.openspaces.admin.internal.pu.DefaultProcessingUnit.java

@Override
public boolean waitFor(QuiesceState desiredState, long timeout, TimeUnit timeUnit) {
    if (!isManaged()) {
        throw new AdminException("No managing GSM to execute quiesce");
    }//from  ww  w .j a v a  2  s. c o m
    long interval = 1000;
    long expiration;
    // checking long overflow to set the expiration time properly
    BigInteger sum = BigInteger.valueOf(0);
    sum = sum.add(BigInteger.valueOf(System.currentTimeMillis()))
            .add(BigInteger.valueOf(timeUnit.toMillis(timeout)));
    if (sum.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
        expiration = Long.MAX_VALUE;
    else
        expiration = sum.longValue();
    for (;;) {
        QuiesceDetails currentDetails = getQuiesceDetails();
        if (instancesReachedQuiesceState(desiredState, currentDetails)) {
            return true;
        }
        try {
            Thread.sleep(interval);
            if (System.currentTimeMillis() >= expiration) {
                return false;
            }
        } catch (InterruptedException e) {
            return false;
        }
    }
}

From source file:org.apache.accumulo.pig.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 *///from w w w . j a  va2 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:com.coinprism.model.APIClient.java

/**
 * Gets the list of recent transactions for a given address.
 *
 * @param address the address for which to query the recent transactions
 * @return a list of transactions// w ww .jav  a 2s  .c  o  m
 */
public List<SingleAssetTransaction> getTransactions(String address)
        throws IOException, JSONException, ParseException, APIException {
    String json = executeHttpGet(this.baseUrl + "/v1/addresses/" + address + "/transactions");

    JSONArray transactions = new JSONArray(json);

    ArrayList<SingleAssetTransaction> assetBalances = new ArrayList<SingleAssetTransaction>();

    for (int i = 0; i < transactions.length(); i++) {
        JSONObject transactionObject = (JSONObject) transactions.get(i);
        String transactionId = transactionObject.getString("hash");

        Date date = null;
        if (!transactionObject.isNull("block_time"))
            date = parseDate(transactionObject.getString("block_time"));

        HashMap<String, BigInteger> quantities = new HashMap<String, BigInteger>();
        BigInteger satoshiDelta = BigInteger.ZERO;

        JSONArray inputs = transactionObject.getJSONArray("inputs");
        for (int j = 0; j < inputs.length(); j++) {
            JSONObject input = (JSONObject) inputs.get(j);
            if (isAddress(input, address)) {
                if (!input.isNull("asset_id"))
                    addQuantity(quantities, input.getString("asset_id"),
                            new BigInteger(input.getString("asset_quantity")).negate());

                satoshiDelta = satoshiDelta.subtract(BigInteger.valueOf(input.getLong("value")));
            }
        }

        JSONArray outputs = transactionObject.getJSONArray("outputs");
        for (int j = 0; j < outputs.length(); j++) {
            JSONObject output = (JSONObject) outputs.get(j);
            if (isAddress(output, address)) {
                if (!output.isNull("asset_id"))
                    addQuantity(quantities, output.getString("asset_id"),
                            new BigInteger(output.getString("asset_quantity")));

                satoshiDelta = satoshiDelta.add(BigInteger.valueOf(output.getLong("value")));
            }
        }

        if (!satoshiDelta.equals(BigInteger.ZERO))
            assetBalances.add(new SingleAssetTransaction(transactionId, date, null, satoshiDelta));

        for (String key : quantities.keySet()) {
            assetBalances.add(new SingleAssetTransaction(transactionId, date, getAssetDefinition(key),
                    quantities.get(key)));
        }
    }

    return assetBalances;
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepThree(final int i) throws Exception {
    BigInteger n = this.pubKey.getModulus();
    BigInteger r;//  ww  w. j a  v a  2 s.co  m
    BigInteger upperBound;
    BigInteger lowerBound;
    BigInteger max;
    BigInteger min;
    BigInteger[] tmp;
    ArrayList<Interval> ms = new ArrayList<>(15);

    for (Interval interval : this.m) {
        upperBound = step3ComputeUpperBound(this.si, n, interval.upper);
        lowerBound = step3ComputeLowerBound(this.si, n, interval.lower);

        r = lowerBound;
        // lowerBound <= r <= upperBound
        while (r.compareTo(upperBound) < 1) {
            // ceil((2*B+r*n)/si)
            max = (BigInteger.valueOf(2).multiply(this.bigB)).add(r.multiply(n));
            tmp = max.divideAndRemainder(this.si);
            if (BigInteger.ZERO.compareTo(tmp[1]) != 0) {
                max = tmp[0].add(BigInteger.ONE);
            } else {
                max = tmp[0];
            }

            // floor((3*B-1+r*n)/si
            min = BigInteger.valueOf(3).multiply(this.bigB);
            min = min.subtract(BigInteger.ONE);
            min = min.add(r.multiply(n));
            min = min.divide(this.si);

            // build new interval
            if (interval.lower.compareTo(max) > 0) {
                max = interval.lower;
            }
            if (interval.upper.compareTo(min) < 0) {
                min = interval.upper;
            }
            if (max.compareTo(min) <= 0) {
                ms.add(new Interval(max, min));
            }
            // one further....
            r = r.add(BigInteger.ONE);
        }
    }

    loggerInstance.log(getClass(), " # of intervals for M" + i + ": " + ms.size(), Logger.LogLevel.INFO);

    if (ms.size() == 0) {
        throw new Exception("Zero intervals left, validity oracle seems to be wrong!");
    }

    this.m = ms.toArray(new Interval[ms.size()]);
}

From source file:org.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    readC();/*from  www  .  j  a  va2 s .c  om*/
    if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) {
        final SecureRandom random = new SecureRandom();
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return;
        }
        final BigInteger k = new BigInteger("3");
        final byte[] Bb = readB(32);
        final BigInteger g = new BigInteger(readB(readC()));
        final byte[] Nb = readB(readC());
        final byte[] saltb = readB(32);
        /* byte[] unk3 = */readB(16);
        readC();
        ArrayUtils.reverse(Bb);
        final BigInteger B = new BigInteger(1, Bb);
        ArrayUtils.reverse(Bb);
        ArrayUtils.reverse(Nb);
        final BigInteger N = new BigInteger(1, Nb);
        ArrayUtils.reverse(Nb);
        final BigInteger a = new BigInteger(1, random.generateSeed(19));

        final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":")
                .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8")));
        sha.update(saltb);
        sha.update(passhash);

        final byte[] xhash = sha.digest();
        ArrayUtils.reverse(xhash);
        final BigInteger x = new BigInteger(1, xhash);
        logger.debug("x:" + x.toString(16).toUpperCase());
        final BigInteger v = g.modPow(x, N);
        logger.debug("v:" + v.toString(16).toUpperCase());
        final BigInteger A = g.modPow(a, N);
        logger.debug("A:" + A.toString(16).toUpperCase());
        logger.debug("B:" + B.toString(16).toUpperCase());
        this.ahash = A.toByteArray();
        ArrayUtils.reverse(this.ahash);
        sha.update(this.ahash);
        sha.update(Bb);
        final byte[] hashu = sha.digest();
        ArrayUtils.reverse(hashu);
        final BigInteger u = new BigInteger(1, hashu);
        logger.debug("u:" + u.toString(16).toUpperCase());
        final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N);

        final byte[] full_S = S.toByteArray();
        ArrayUtils.reverse(full_S);
        logger.debug("t:" + StringUtils.toHexString(full_S));
        final byte[] s1_hash = new byte[16];
        final byte[] s2_hash = new byte[16];
        for (int i = 0; i < 16; i++) {
            s1_hash[i] = full_S[i * 2];
            s2_hash[i] = full_S[(i * 2) + 1];
        }
        final byte[] t1 = sha.digest(s1_hash);
        final byte[] t2 = sha.digest(s2_hash);
        final byte[] vK = new byte[40];
        for (int i = 0; i < 20; i++) {
            vK[i * 2] = t1[i];
            vK[(i * 2) + 1] = t2[i];
        }

        byte[] hash = new byte[20];
        logger.debug("N:" + N.toString(16).toUpperCase());
        hash = sha.digest(Nb);

        logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase());

        byte[] gH = new byte[20];
        sha.update(g.toByteArray());
        gH = sha.digest();
        for (int i = 0; i < 20; ++i) {
            hash[i] ^= gH[i];
        }

        byte[] t4 = new byte[20];
        t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8")));

        sha.update(hash);
        logger.debug("hash:" + StringUtils.toHexString(hash));
        sha.update(t4);
        logger.debug("t4:" + StringUtils.toHexString(t4));
        sha.update(saltb);
        logger.debug("saltb:" + StringUtils.toHexString(saltb));
        sha.update(this.ahash);
        logger.debug("ahash:" + StringUtils.toHexString(this.ahash));
        sha.update(Bb);
        logger.debug("Bb:" + StringUtils.toHexString(Bb));
        sha.update(vK);
        logger.debug("vK:" + StringUtils.toHexString(vK));
        this.m1 = sha.digest();

        sha.update(this.ahash);
        sha.update(this.m1);
        sha.update(vK);
        logger.debug("m1 value" + StringUtils.toHexString(this.m1));
        @SuppressWarnings("unused")
        final byte[] m2 = sha.digest();

        final ChannelPipeline pipeline = getClient().getChannel().getPipeline();
        ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK);

    } else {
        getChannel().getPipeline().remove("handler");
        getChannel().getPipeline().remove("eventlog");
        getChannel().getPipeline().remove("executor");
        getChannel().close();
        getChannel().getFactory().releaseExternalResources();
    }
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

private void stepTwoC() throws Exception {
    byte[] send;// www.ja  v a2s  . co  m
    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:test.unit.be.fedict.trust.service.PersistenceTest.java

@Test
public void testFindRevokedCertificate() throws Exception {
    // setup//from   w  w  w  . ja  v a  2  s .co m
    String issuerName = "CN=Test CA";
    BigInteger serialNumber = new BigInteger("21267647932558966653497436382356969621");
    BigInteger crlNumber = new BigInteger("123465789");
    RevokedCertificateEntity revokedCertificateEntity = new RevokedCertificateEntity(issuerName, serialNumber,
            new Date(), crlNumber);
    this.entityManager.persist(revokedCertificateEntity);

    refresh();

    // operate
    Query query = this.entityManager.createNamedQuery(RevokedCertificateEntity.QUERY_WHERE_ISSUER_SERIAL);
    query.setParameter("issuer", issuerName);
    query.setParameter("serialNumber", serialNumber.toString());
    RevokedCertificateEntity resultRevokedCertificate = (RevokedCertificateEntity) query.getSingleResult();

    // verify
    assertNotNull(resultRevokedCertificate);
    assertEquals(resultRevokedCertificate.getPk().getIssuer(), issuerName);
    assertEquals(resultRevokedCertificate.getPk().getSerialNumber(), serialNumber.toString());
    assertEquals(resultRevokedCertificate.getCrlNumber(), crlNumber);

    refresh();

    Query deleteQuery = this.entityManager
            .createNamedQuery(RevokedCertificateEntity.DELETE_WHERE_ISSUER_OLDER_CRL_NUMBER);
    deleteQuery.setParameter("issuer", issuerName);
    deleteQuery.setParameter("crlNumber", crlNumber);
    int zeroDeleteResult = deleteQuery.executeUpdate();
    assertEquals(0, zeroDeleteResult);

    refresh();

    deleteQuery.setParameter("crlNumber", crlNumber.add(new BigInteger("1")));
    int deleteResult = deleteQuery.executeUpdate();
    assertEquals(1, deleteResult);
}

From source file:cn.iie.haiep.hbase.value.Bytes.java

/**
 * Iterate over keys within the passed inclusive range.
 */// ww  w.  j  a  va  2s  .com
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:piuk.MyBlockChain.java

@SuppressWarnings("unchecked")
public void onMessage(WebSocketMessage wmessage) {

    System.out.println("OnMessage()");

    try {//  ww  w.j  a  v a  2 s  .  c o  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();
    }
}