net.bither.bitherj.utils.Sha256Hash Java Examples

The following examples show how to use net.bither.bitherj.utils.Sha256Hash. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Peer.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void sendGetBlocksDataNextPiece(List<Sha256Hash> withTxHashes) {
    List<Sha256Hash> blockHashesPiece = new ArrayList<Sha256Hash>(invBlockHashes.subList(0,
            Math.min(invBlockHashes.size(), GET_BLOCK_DATA_PIECE_SIZE)));
    invBlockHashes.removeAll(blockHashesPiece);

    if (PeerManager.instance().getDownloadingPeer() == null || getDownloadData()) {
        sendGetDataMessageWithTxHashesAndBlockHashes(withTxHashes, blockHashesPiece);
    } else if (withTxHashes.size() > 0) {
        sendGetDataMessageWithTxHashesAndBlockHashes(withTxHashes, new
                ArrayList<Sha256Hash>());
    }

    if (blockHashesPiece.size() > 0) {
        //remember blockHashes in case we need to refetch them with an updated bloom filter
        currentBlockHashes.addAll(blockHashesPiece);
        if (currentBlockHashes.size() > MAX_GETDATA_HASHES) {
            Iterator iterator = currentBlockHashes.iterator();
            while (iterator.hasNext() && currentBlockHashes.size() > MAX_GETDATA_HASHES / 2) {
                iterator.remove();
            }
        }
        if (this.synchronising) {
            this.syncBlockHashes.addAll(blockHashesPiece);
        }
    }
}
 
Example #2
Source File: PeerManager.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public Tx requestedTransaction(final Peer byPeer, final byte[] txHash) {
    if (!isRunning()) {
        return null;
    }
    final Tx tx = publishedTx.get(new Sha256Hash(txHash));
    if (tx != null) {
        bloomFilter = null;
        executor.submit(new Runnable() {
            @Override
            public void run() {
                if (txRelays.get(new Sha256Hash(txHash)) == null) {
                    txRelays.put(new Sha256Hash(txHash), new HashSet<Peer>());
                }
                long count = txRelays.get(new Sha256Hash(txHash)).size();
                txRelays.get(new Sha256Hash(txHash)).add(byPeer);
                if (txRelays.get(new Sha256Hash(txHash)).size() > count) {
                    tx.sawByPeer();
                }
            }
        });
    }
    return tx;
}
 
Example #3
Source File: PeerManager.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void syncStopped() {
    synchronizing = false;
    syncStartHeight = 0;

    for (Peer p : connectedPeers) { // after syncing, load filters and get mempools from the
        // other peers
        if (p != downloadingPeer) {
            p.sendFilterLoadMessage(bloomFilterForPeer(p));
        }
        for (Tx tx : publishedTx.values()) {
            if (tx.getSource() > 0 && tx.getSource() <= MaxPeerCount) {
                p.sendInvMessageWithTxHash(new Sha256Hash(tx.getTxHash()));
            }
        }
        p.sendMemPoolMessage();
    }
    cancelTimeoutTimer();
    sendSyncProgress();
}
 
Example #4
Source File: PeerManager.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void setBlockHeightForTxs(final int height, final List<byte[]> txHashes) {
    if (txHashes == null || txHashes.size() == 0) {
        return;
    }
    if (height != BitherjSettings.TX_UNCONFIRMED) {
        // update all tx in db
        log.info("update {} txs confirmation", txHashes.size());
        AbstractDb.txProvider.confirmTx(height, txHashes);
        // update all address 's tx and balance
        for (Address address : AddressManager.getInstance().getAllAddresses()) {
            address.setBlockHeight(txHashes, height);
        }

        // remove confirmed tx from publish list and relay counts
        for (byte[] hash : txHashes) {
            publishedTx.remove(new Sha256Hash(hash));
            txRelays.remove(new Sha256Hash(hash));
        }
    }
}
 
Example #5
Source File: Peer.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public Peer(InetAddress address) {
    super(new InetSocketAddress(address, BitherjSettings.port));
    this.peerAddress = address;
    peerPort = BitherjSettings.port;
    state = State.Disconnected;
    peerServices = 1;
    currentTxHashes = new HashSet<Sha256Hash>();
    currentBlockHashes = new LinkedHashSet<Sha256Hash>();
    knownTxHashes = new HashSet<Sha256Hash>();
    requestedBlockHashes = new HashSet<Sha256Hash>();
    needToRequestDependencyDict = new HashMap<Sha256Hash, HashSet<Tx>>();
    invBlockHashes = new ArrayList<Sha256Hash>();
    incrementalBlockHeight = 0;
    unrelatedTxRelayCount = 0;
    nonce = new Random().nextLong();
    peerTimestamp = (int) (new Date().getTime() / 1000 - 24 * 60 * 60 * (3 + new Random()
            .nextFloat() * 4));
    synchronising = false;
    syncBlocks = new ArrayList<Block>();
    syncBlockHashes = new ArrayList<Sha256Hash>();
}
 
Example #6
Source File: Peer.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void processNotFoundMessage(NotFoundMessage m) {
    // This is received when we previously did a getdata but the peer couldn't find what we
    // requested in it's
    // memory pool. Typically, because we are downloading dependencies of a relevant
    // transaction and reached
    // the bottom of the dependency tree (where the unconfirmed transactions connect to
    // transactions that are
    // in the chain).
    //
    // We go through and cancel the pending getdata futures for the items we were told
    // weren't found.
    log.info("peer[{}:{}] receive {} notfound item ", this.peerAddress.getHostAddress(),
            this.peerPort, m.getItems().size());
    for (InventoryItem item : m.getItems()) {
        if (item.type == InventoryItem.Type.Transaction && item.hash != null && item.hash
                .length > 0) {
            checkDependencyWithNotFoundMsg(new Sha256Hash(item.hash));
        }
    }
}
 
Example #7
Source File: AddressManager.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private boolean isSendFromMe(Tx tx, Map<Sha256Hash, Tx> txHashList, Address address) {
    for (In in : tx.getIns()) {
        Sha256Hash prevTxHahs = new Sha256Hash(in.getPrevTxHash());
        if (txHashList.containsKey(prevTxHahs)) {
            Tx preTx = txHashList.get(prevTxHahs);
            for (Out out : preTx.getOuts()) {
                if (out.getOutSn() == in.getPrevOutSn()) {
                    if (Utils.compareString(out.getOutAddress(), address.getAddress())) {
                        return true;
                    }

                }
            }
        }

    }
    return false;
}
 
Example #8
Source File: AbstractTxProvider.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void addOutForTxDetail(IDb db, String address, final HashMap<Sha256Hash, Tx> txDict) {
    String sql = "select b.* from addresses_txs a, outs b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash,b.out_sn";
    this.execQueryLoop(db, sql, new String[]{address}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            Out out = applyCursorOut(c);
            Tx tx = txDict.get(new Sha256Hash(out.getTxHash()));
            if (tx != null) {
                tx.getOuts().add(out);
            }
            return null;
        }
    });
}
 
Example #9
Source File: AbstractTxProvider.java    From bitherj with Apache License 2.0 6 votes vote down vote up
private void addInForTxDetail(IDb db, String address, final HashMap<Sha256Hash, Tx> txDict) {
    String sql = "select b.* from addresses_txs a, ins b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash ,b.in_sn";
    this.execQueryLoop(db, sql, new String[]{address}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            In inItem = applyCursorIn(c);
            Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash()));
            if (tx != null) {
                tx.getIns().add(inItem);
            }
            return null;
        }
    });
}
 
Example #10
Source File: AbstractTxProvider.java    From bitherj with Apache License 2.0 6 votes vote down vote up
@Override
public List<Tx> getTxAndDetailByAddress(String address) {
    final List<Tx> txItemList = new ArrayList<Tx>();
    final HashMap<Sha256Hash, Tx> txDict = new HashMap<Sha256Hash, Tx>();
    String sql = "select b.* from addresses_txs a, txs b" +
            " where a.tx_hash=b.tx_hash and a.address=? order by ifnull(b.block_no,4294967295) desc";
    IDb db = this.getReadDb();
    this.execQueryLoop(db, sql, new String[]{address}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            Tx txItem = applyCursor(c);
            txItem.setIns(new ArrayList<In>());
            txItem.setOuts(new ArrayList<Out>());
            txItemList.add(txItem);
            txDict.put(new Sha256Hash(txItem.getTxHash()), txItem);
            return null;
        }
    });
    addInForTxDetail(db, address, txDict);
    addOutForTxDetail(db, address, txDict);

    return txItemList;
}
 
Example #11
Source File: Peer.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public void sendInvMessageWithTxHash(Sha256Hash txHash) {
    if (state != State.Connected) {
        return;
    }
    InventoryMessage m = new InventoryMessage();
    Tx tx = AbstractDb.txProvider.getTxDetailByTxHash(txHash.getBytes());
    if (tx == null) {
        tx = AbstractDb.txProvider.getTxDetailByTxHash(txHash.getBytes());
    }
    if (tx == null) {
        return;
    }
    m.addTransaction(tx);
    log.info("Peer {} send inv with tx {}", getPeerAddress().getHostAddress(),
            Utils.hashToString(txHash.getBytes()));
    sendMessage(m);
}
 
Example #12
Source File: Bip38Util.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the checksum in the last 4 bytes of the decoded data to verify the
 * rest are correct. The checksum is removed from the returned data.
 */
public static byte[] decodeChecked(String input) {
    byte tmp[] = decode(input);
    if (tmp == null || tmp.length < 4) {
        return null;
    }
    byte[] bytes = copyOfRange(tmp, 0, tmp.length - 4);
    byte[] checksum = copyOfRange(tmp, tmp.length - 4, tmp.length);

    Sha256Hash sha256Hash = doubleSha256(bytes);
    byte[] hash = sha256Hash.firstFourBytes();
    if (!Arrays.equals(checksum, hash)) {
        return null;
    }

    return bytes;
}
 
Example #13
Source File: Peer.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public void setSynchronising(boolean synchronising) {
    if (synchronising && !this.synchronising) {
        syncStartBlockNo = BlockChain.getInstance().getLastBlock().getBlockNo();
        syncStartPeerBlockNo = this.getDisplayLastBlockHeight();
        synchronisingBlockCount = 0;
        syncBlocks = new ArrayList<Block>();
        syncBlockHashes = new ArrayList<Sha256Hash>();

        this.synchronising = synchronising;
    } else if (!synchronising && this.synchronising) {
        incrementalBlockHeight = BlockChain.getInstance().getLastBlock().getBlockNo() - (int) this.getVersionLastBlockHeight();
        synchronisingBlockCount = 0;

        this.synchronising = synchronising;
    }
}
 
Example #14
Source File: DialogEnterpriseHDMEnable.java    From bither-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onDismiss(DialogInterface dialog) {
    if (clickedId == R.id.btn_ok) {
        Sha256Hash hash = Sha256Hash.create(et.getText().toString().trim().getBytes());
        if (Arrays.equals(hash.getBytes(), Utils.hexStringToByteArray(CodeHash))) {
            if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.HOT) {
                activity.startActivity(new Intent(activity, EnterpriseHDMKeychainActivity
                        .class));
            } else {
                activity.startActivity(new Intent(activity, EnterpriseHDMSeedActivity.class));
            }
        } else {
            DropdownMessage.showDropdownMessage(activity, R.string
                    .enterprise_hdm_keychain_enable_failed);
        }
    }
}
 
Example #15
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void refetchBlocksFrom(Sha256Hash blockHash) {
    if (!currentBlockHashes.contains(blockHash)) {
        return;
    }
    Iterator<Sha256Hash> iterator = currentBlockHashes.iterator();
    while (iterator.hasNext()) {
        Sha256Hash hash = iterator.next();
        iterator.remove();
        if (blockHash.equals(hash)) {
            break;
        }
    }
    log.info("Peer {} refetch {} blocks from {}", getPeerAddress().getHostAddress(), currentBlockHashes.size(), Utils.hashToString(blockHash.getBytes()));
    sendGetDataMessageWithTxHashesAndBlockHashes(null, new ArrayList<Sha256Hash>(currentBlockHashes));
}
 
Example #16
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void sendGetHeadersMessage(List<byte[]> locators, byte[] hashStop) {
    if (state != State.Connected) {
        return;
    }
    GetHeadersMessage m = new GetHeadersMessage(locators, hashStop == null ? Sha256Hash
            .ZERO_HASH.getBytes() : hashStop);
    log.info("Peer {} send get header message", getPeerAddress().getHostAddress());
    sendMessage(m);
}
 
Example #17
Source File: TxProvider.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private void addInForTxDetail(String address, HashMap<Sha256Hash, Tx> txDict) throws AddressFormatException, SQLException {
    String sql = "select b.* from addresses_txs a, ins b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash ,b.in_sn";
    PreparedStatement statement = this.mDb.getPreparedStatement(sql, new String[]{address});
    ResultSet c = statement.executeQuery();
    while (c.next()) {
        In inItem = TxHelper.applyCursorIn(c);
        Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash()));
        if (tx != null) {
            tx.getIns().add(inItem);
        }
    }
    c.close();
    statement.close();
}
 
Example #18
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void sendGetHeadersMessage(List<Sha256Hash> locators, Sha256Hash hashStop) {
    ArrayList<byte[]> ls = new ArrayList<byte[]>();
    for (Sha256Hash i : locators) {
        ls.add(i.getBytes());
    }
    sendGetHeadersMessage(ls, hashStop == null ? null : hashStop.getBytes());
}
 
Example #19
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void sendGetBlocksMessage(List<byte[]> locators, byte[] hashStop) {
    if (state != State.Connected) {
        return;
    }
    GetBlocksMessage m = new GetBlocksMessage(locators, hashStop == null ? Sha256Hash
            .ZERO_HASH.getBytes() : hashStop);
    log.info("Peer {} send get blocks message", getPeerAddress().getHostAddress());
    sendMessage(m);
}
 
Example #20
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void sendGetBlocksMessage(List<Sha256Hash> locators, Sha256Hash hashStop) {
    ArrayList<byte[]> ls = new ArrayList<byte[]>();
    for (Sha256Hash i : locators) {
        ls.add(i.getBytes());
    }
    sendGetBlocksMessage(ls, hashStop == null ? null : hashStop.getBytes());
}
 
Example #21
Source File: Peer.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private void clearInvalidTxFromDependencyDict(Tx tx) {
    for (HashSet<Tx> set : needToRequestDependencyDict.values()) {
        if (set.contains(tx)) {
            set.remove(tx);
        }
    }
    HashSet<Tx> subTxs = needToRequestDependencyDict.get(new Sha256Hash(tx.getTxHash()));
    if (subTxs != null) {
        needToRequestDependencyDict.remove(new Sha256Hash(tx.getTxHash()));
        for (Tx eachTx : subTxs) {
            clearInvalidTxFromDependencyDict(eachTx);
        }
    }
}
 
Example #22
Source File: UEntropyCollector.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] nextBytes(int length) {
    byte[] bytes = null;
    if (!shouldCollectData()) {
        throw new IllegalStateException("UEntropyCollector is not running");
    }
    try {
        for (int i = 0;
             i < ENTROPY_XOR_MULTIPLIER;
             i++) {
            byte[] itemBytes = new byte[length];
            while (in.available() < itemBytes.length) {
                if (!shouldCollectData()) {
                    throw new IllegalStateException("UEntropyCollector is not running");
                }
            }
            in.read(itemBytes);
            if (i == ENTROPY_XOR_MULTIPLIER - 1) {
                itemBytes = Sha256Hash.create(itemBytes).getBytes();
            }
            if (bytes == null) {
                bytes = itemBytes;
            } else {
                for (int k = 0;
                     k < bytes.length && k < itemBytes.length;
                     k++) {
                    bytes[k] = (byte) (bytes[k] ^ itemBytes[k]);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return new byte[length];
    }
    return bytes;
}
 
Example #23
Source File: TxProvider.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private void addInForTxDetail(String address, HashMap<Sha256Hash, Tx> txDict) throws AddressFormatException, SQLException {
    String sql = "select b.* from addresses_txs a, ins b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash ,b.in_sn";
    PreparedStatement statement = this.mDb.getPreparedStatement(sql, new String[]{address});
    ResultSet c = statement.executeQuery();
    while (c.next()) {
        In inItem = TxHelper.applyCursorIn(c);
        Tx tx = txDict.get(new Sha256Hash(inItem.getTxHash()));
        if (tx != null) {
            tx.getIns().add(inItem);
        }
    }
    c.close();
    statement.close();
}
 
Example #24
Source File: PeerManager.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private void schedulePublishTxTimeoutTimer(long delay, final byte[] txHash) {
    cancelPublishTxTimeoutTimer(txHash);
    if (publishTxTimeoutTimers == null) {
        publishTxTimeoutTimers = new HashMap<Sha256Hash, Timer>();
    }

    Timer publishTxTimeoutTimer = new Timer();
    publishTxTimeoutTimers.put(new Sha256Hash(txHash), publishTxTimeoutTimer);
    publishTxTimeoutTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            publishTxTimeout(txHash);
        }
    }, delay);
}
 
Example #25
Source File: PeerManager.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private void cancelPublishTxTimeoutTimer(byte[] txHash) {
    Sha256Hash hash = new Sha256Hash(txHash);
    if (publishTxTimeoutTimers != null && publishTxTimeoutTimers.containsKey(hash)) {
        Timer publishTxTimeoutTimer = publishTxTimeoutTimers.get(hash);
        publishTxTimeoutTimers.remove(hash);
        publishTxTimeoutTimer.cancel();
        publishTxTimeoutTimer = null;
    }
}
 
Example #26
Source File: TxProvider.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private void addOutForTxDetail(String address, HashMap<Sha256Hash, Tx> txDict) throws AddressFormatException, SQLException {
    String sql = "select b.* from addresses_txs a, outs b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash,b.out_sn";
    PreparedStatement statement = this.mDb.getPreparedStatement(sql, new String[]{address});
    ResultSet c = statement.executeQuery();
    while (c.next()) {
        Out out = TxHelper.applyCursorOut(c);
        Tx tx = txDict.get(new Sha256Hash(out.getTxHash()));
        if (tx != null) {
            tx.getOuts().add(out);
        }
    }
    c.close();
    statement.close();
}
 
Example #27
Source File: UEntropyCollector.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] nextBytes(int length) {
    byte[] bytes = null;
    if (!shouldCollectData()) {
        throw new IllegalStateException("UEntropyCollector is not running");
    }
    try {
        for (int i = 0;
             i < ENTROPY_XOR_MULTIPLIER;
             i++) {
            byte[] itemBytes = new byte[length];
            while (in.available() < itemBytes.length) {
                if (!shouldCollectData()) {
                    throw new IllegalStateException("UEntropyCollector is not running");
                }
            }
            in.read(itemBytes);
            if (i == ENTROPY_XOR_MULTIPLIER - 1) {
                itemBytes = Sha256Hash.create(itemBytes).getBytes();
            }
            if (bytes == null) {
                bytes = itemBytes;
            } else {
                for (int k = 0;
                     k < bytes.length && k < itemBytes.length;
                     k++) {
                    bytes[k] = (byte) (bytes[k] ^ itemBytes[k]);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return new byte[length];
    }
    return bytes;
}
 
Example #28
Source File: TxProvider.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private void addOutForTxDetail(String address, HashMap<Sha256Hash, Tx> txDict) throws AddressFormatException, SQLException {
    String sql = "select b.* from addresses_txs a, outs b where a.tx_hash=b.tx_hash and a.address=? "
            + "order by b.tx_hash,b.out_sn";
    PreparedStatement statement = this.mDb.getPreparedStatement(sql, new String[]{address});
    ResultSet c = statement.executeQuery();
    while (c.next()) {
        Out out = TxHelper.applyCursorOut(c);
        Tx tx = txDict.get(new Sha256Hash(out.getTxHash()));
        if (tx != null) {
            tx.getOuts().add(out);
        }
    }
    c.close();
    statement.close();
}
 
Example #29
Source File: PeerManager.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private void initPublishedTx() {
    for (Tx tx : AbstractDb.txProvider.getPublishedTxs()) {
        if (tx.getBlockNo() == Tx.TX_UNCONFIRMED) {
            publishedTx.put(new Sha256Hash(tx.getTxHash()), tx);
        }
    }

}
 
Example #30
Source File: PeerManager.java    From bitherj with Apache License 2.0 5 votes vote down vote up
private PeerManager() {
        running = new AtomicBoolean(false);
        connected = new AtomicBoolean(false);
        connectedPeers = new HashSet<Peer>();
        abandonPeers = new HashSet<Peer>();
        txRelays = new HashMap<Sha256Hash, HashSet<Peer>>();
        publishedTx = new HashMap<Sha256Hash, Tx>();
        tweak = new Random().nextLong();
//        earliestKeyTime = new Date().getTime() / 1000;//TODO how to set this field
        executor = new PeerManagerExecutorService();
        initPublishedTx();
    }