net.bither.bitherj.core.Block Java Examples

The following examples show how to use net.bither.bitherj.core.Block. 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: BlockPanel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
private void refreshBlock() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            List<Block> temp = BlockChain.getInstance().getLimitBlocks(100);
            if (temp != null && temp.size() > 0) {
                blocks.clear();
                blocks.addAll(temp);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        blockTableModel.fireTableDataChanged();
                    }
                });
            }
        }
    }).start();
}
 
Example #2
Source File: BlockTableModel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
@Override
public Object getValueAt(int i, int i2) {
    Block block = this.blockList.get(i);
    switch (i2) {
        case 0:
            return Integer.toString(block.getBlockNo());
        case 1:
            final long timeMs = block.getBlockTime()
                    * DateUtils.SECOND_IN_MILLIS;
            return DateUtils.dateToRelativeTime(new Date(timeMs));

        case 2:
            return WalletUtils.formatHash(
                    Utils.bytesToHexString(Utils.reverseBytes(block.getBlockHash())), 8, 0, ' ');
    }


    return "";
}
 
Example #3
Source File: BlockTableModel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
@Override
public Object getValueAt(int i, int i2) {
    Block block = this.blockList.get(i);
    switch (i2) {
        case 0:
            return Integer.toString(block.getBlockNo());
        case 1:
            final long timeMs = block.getBlockTime()
                    * DateUtils.SECOND_IN_MILLIS;
            return DateUtils.dateToRelativeTime(new Date(timeMs));

        case 2:
            return WalletUtils.formatHash(
                    Utils.bytesToHexString(Utils.reverseBytes(block.getBlockHash())), 8, 0, ' ');
    }


    return "";
}
 
Example #4
Source File: BlockPanel.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
private void refreshBlock() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            List<Block> temp = BlockChain.getInstance().getLimitBlocks(100);
            if (temp != null && temp.size() > 0) {
                blocks.clear();
                blocks.addAll(temp);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        blockTableModel.fireTableDataChanged();
                    }
                });
            }
        }
    }).start();
}
 
Example #5
Source File: DownloadSpvRunnable.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    prepare();
    try {
        Block block = BlockUtil.dowloadSpvBlock();
        if (block != null) {
            success(null);
        } else {
            error(0, null);
        }
    } catch (Exception e) {
        error(0, null);
        e.printStackTrace();
    }

}
 
Example #6
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public void addBlock(Block item) {
    boolean blockExists = blockExists(item.getBlockHash());
    if (!blockExists) {
        String sql = "insert into blocks(block_no,block_hash,block_root,block_ver,block_bits,block_nonce,block_time,block_prev,is_main) values(?,?,?,?,?,?,?,?,?)";
        this.execUpdate(sql, new String[] {
                Integer.toString(item.getBlockNo())
                , Base58.encode(item.getBlockHash())
                , Base58.encode(item.getBlockRoot())
                , Long.toString(item.getBlockVer())
                , Long.toString(item.getBlockBits())
                , Long.toString(item.getBlockNonce())
                , Long.toString(item.getBlockTime())
                , Base58.encode(item.getBlockPrev())
                , item.isMain() ? "1" : "0"
        });
    }
}
 
Example #7
Source File: BlockMessage.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
     * Special case constructor, used for the genesis node, cloneAsHeader and unit tests.
     */
    public BlockMessage() {
        super();
        // Set up a few basic things. We are not complete after this though.
//        version = 1;
//        difficultyTarget = 0x1d07fff8L;
//        time = System.currentTimeMillis() / 1000;
//        prevBlockHash = new byte[32];
//
//        length = 80;
        block = new Block();
        block.setBlockVer(1);
        block.setBlockBits(0x1d07fff8L);
        block.setBlockTime((int) (System.currentTimeMillis() / 1000));
        block.setBlockPrev(new byte[32]);
        length = 80;
    }
 
Example #8
Source File: DownloadSpvRunnable.java    From bither-desktop-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    prepare();
    try {
        Block block = BlockUtil.dowloadSpvBlock();
        if (block != null) {
            success(null);
        } else {
            error(0, null);
        }
    } catch (Exception e) {
        error(0, null);
        e.printStackTrace();
    }

}
 
Example #9
Source File: BlockMessage.java    From bitherj with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a copy of the block, but without any transactions.
 */
public BlockMessage cloneAsHeader() {
    BlockMessage blockMessage = new BlockMessage();
    Block block = new Block();
    block.setBlockNo(this.block.getBlockNo());
    block.setBlockNonce(this.block.getBlockNonce());
    block.setBlockPrev(this.block.getBlockPrev().clone());
    block.setBlockRoot(this.block.getBlockRoot().clone());
    block.setBlockVer(this.block.getBlockVer());
    block.setBlockTime(this.block.getBlockTime());
    block.setBlockBits(this.block.getBlockBits());
    block.setTransactions(null);
    block.setBlockHash(this.block.getBlockHash().clone());
    blockMessage.setBlock(block);
    return blockMessage;
}
 
Example #10
Source File: DownloadSpvRunnable.java    From bither-android with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    obtainMessage(HandlerMessage.MSG_PREPARE);
    try {
        Block block = BlockUtil.dowloadSpvBlock();
        if (block != null) {
            obtainMessage(HandlerMessage.MSG_SUCCESS);
        } else {
            obtainMessage(HandlerMessage.MSG_FAILURE);
        }
    } catch (Exception e) {
        obtainMessage(HandlerMessage.MSG_FAILURE);
        e.printStackTrace();
    }

}
 
Example #11
Source File: BlockUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static Block getStoredBlock(long ver, String prevBlock,
                                   String mrklRoot, int time, long difficultyTarget, long nonce,
                                   int hegiht) {
    Block b = new Block(ver,
            prevBlock, mrklRoot, time,
            difficultyTarget, nonce, hegiht);
    return b;
}
 
Example #12
Source File: FilteredBlockMessage.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public void bitcoinSerializeToStream(OutputStream stream) throws IOException {
    if (block.getTransactions() == null)
        block.bitcoinSerializeToStream(stream);
    else {
        Block emptyBlock = new Block(block.bitcoinSerialize());
        emptyBlock.setTransactions(null);
        emptyBlock.bitcoinSerializeToStream(stream);
    }
    merkleTree.bitcoinSerializeToStream(stream);
}
 
Example #13
Source File: BlockUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static Block formatStoredBlock(JSONObject jsonObject, int hegih)
        throws JSONException {
    long ver = jsonObject.getLong(VER);
    String prevBlock = jsonObject.getString(PREV_BLOCK);
    String mrklRoot = jsonObject.getString(MRKL_ROOT);
    int time = jsonObject.getInt(TIME);
    long difficultyTarget = jsonObject.getLong(BITS);
    long nonce = jsonObject.getLong(NONCE);

    return BlockUtil.getStoredBlock(ver, prevBlock, mrklRoot, time,
            difficultyTarget, nonce, hegih);

}
 
Example #14
Source File: BlockUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static Block formatStoredBlock(JSONObject jsonObject)
        throws JSONException {
    long ver = jsonObject.getLong(VER);
    int height = jsonObject.getInt(BLOCK_NO);
    String prevBlock = jsonObject.getString(PREV_BLOCK);
    String mrklRoot = jsonObject.getString(MRKL_ROOT);
    int time = jsonObject.getInt(TIME);
    long difficultyTarget = jsonObject.getLong(BITS);
    long nonce = jsonObject.getLong(NONCE);

    return BlockUtil.getStoredBlock(ver, prevBlock, mrklRoot, time,
            difficultyTarget, nonce, height);
}
 
Example #15
Source File: BlockUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static Block formatStoreBlockFromBlockChainInfo(JSONObject jsonObject)
    throws JSONException{
    long ver = jsonObject.getLong(VER);
    int height = jsonObject.getInt(HEIGHT);
    String prevBlock = jsonObject.getString(PREV_BLOCK);
    String mrklRoot = jsonObject.getString(MRKL_ROOT);
    int time = jsonObject.getInt(TIME);
    long difficultyTarget = jsonObject.getLong(BITS);
    long nonce = jsonObject.getLong(NONCE);

    return BlockUtil.getStoredBlock(ver, prevBlock, mrklRoot, time,
            difficultyTarget, nonce, height);

}
 
Example #16
Source File: FilteredBlockMessage.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Override
protected void parse() throws ProtocolException {
    byte[] headerBytes = new byte[BlockMessage.HEADER_SIZE];
    System.arraycopy(bytes, 0, headerBytes, 0, BlockMessage.HEADER_SIZE);
    block = new Block(headerBytes);
    merkleTree = new PartialMerkleTree(bytes, BlockMessage.HEADER_SIZE);
    length = BlockMessage.HEADER_SIZE + merkleTree.getMessageSize();
    block.setTxHashes(this.getTransactionHashes());
}
 
Example #17
Source File: BlockUtil.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public  static Block getLatestBlockHeight(JSONObject jsonObject)
        throws Exception {
    int latestHeight = jsonObject.getInt("height");
    int height = 0;
    if (latestHeight % 2016 !=0){
        height = latestHeight - (latestHeight%2016);
    }else {
        height = latestHeight;
    }
    BlockChainDownloadSpvApi blockChainDownloadSpvApi = new BlockChainDownloadSpvApi(height);
    blockChainDownloadSpvApi.handleHttpGet();
    Block block = null;
    block = blockChainDownloadSpvApi.getResult();
    return block;
}
 
Example #18
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public List<Block> getAllBlocks() {
    final List<Block> blockItems = new ArrayList<Block>();
    String sql = "select * from blocks order by block_no desc";

    this.execQueryLoop(sql, null, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(ICursor c) {
            blockItems.add(applyCursor(c));
            return null;
        }
    });
    return blockItems;
}
 
Example #19
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Override
public List<Block> getLimitBlocks(int limit) {
    final List<Block> blockItems = new ArrayList<Block>();
    String sql = "select * from blocks order by block_no desc limit ?";
    this.execQueryLoop(sql, new String[]{Integer.toString(limit)}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            blockItems.add(applyCursor(c));
            return null;
        }
    });
    return blockItems;
}
 
Example #20
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public List<Block> getBlocksFrom(int blockNo) {
    final List<Block> blockItems = new ArrayList<Block>();
    String sql = "select * from blocks where block_no>? order by block_no desc";
    this.execQueryLoop(sql, new String[]{Integer.toString(blockNo)}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            blockItems.add(applyCursor(c));
            return null;
        }
    });
    return blockItems;
}
 
Example #21
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Block getLastBlock() {
    final Block[] item = {null};
    String sql = "select * from blocks where is_main=1 order by block_no desc limit 1";

    this.execQueryOneRecord(sql, null, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            item[0] = applyCursor(c);
            return null;
        }
    });
    return item[0];
}
 
Example #22
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Block getLastOrphanBlock() {
    final Block[] item = {null};
    String sql = "select * from blocks where is_main=0 order by block_no desc limit 1";
    this.execQueryOneRecord(sql, null, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            item[0] = applyCursor(c);
            return null;
        }
    });
    return item[0];
}
 
Example #23
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Block getBlock(byte[] blockHash) {
    final Block[] item = {null};
    String sql = "select * from blocks where block_hash=?";
    this.execQueryOneRecord(sql, new String[]{Base58.encode(blockHash)}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            item[0] = applyCursor(c);
            return null;
        }
    });
    return item[0];
}
 
Example #24
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Block getOrphanBlockByPrevHash(byte[] prevHash) {
    final Block[] item = {null};
    String sql = "select * from blocks where block_prev=? and is_main=0";
    this.execQueryOneRecord(sql, new String[]{Base58.encode(prevHash)}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            item[0] = applyCursor(c);
            return null;
        }
    });
    return item[0];
}
 
Example #25
Source File: AbstractBlockProvider.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public Block getMainChainBlock(byte[] blockHash) {
    final Block[] item = {null};
    String sql = "select * from blocks where block_hash=? and is_main=1";
    this.execQueryOneRecord(sql, new String[]{Base58.encode(blockHash)}, new Function<ICursor, Void>() {
        @Nullable
        @Override
        public Void apply(@Nullable ICursor c) {
            item[0] = applyCursor(c);
            return null;
        }
    });
    return item[0];
}
 
Example #26
Source File: BlockProvider.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
public void addBlock(Block item) {
    boolean blockExists = blockExists(item.getBlockHash());
    if (!blockExists) {

        this.mDb.executeUpdate(insertBlockSql, new String[]{Integer.toString(item.getBlockNo()),
                Base58.encode(item.getBlockHash()), Base58.encode(item.getBlockRoot()), Long.toString(item.getBlockVer())
                , Long.toString(item.getBlockBits()), Long.toString(item.getBlockNonce()), Integer.toString(item.getBlockTime()), Base58.encode(item.getBlockPrev()), Integer.toString(item.isMain() ? 1 : 0)});
    }
    LogUtil.printlnOut("addBlock");

}
 
Example #27
Source File: BlockListFragment.java    From bither-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onLoadFinished(final Loader<List<Block>> loader,
                           final List<Block> blocks) {
    adapter.replace(blocks);

    final Loader<Set<Tx>> transactionLoader = loaderManager
            .getLoader(ID_TRANSACTION_LOADER);
    if (transactionLoader != null && transactionLoader.isStarted())
        transactionLoader.forceLoad();
}
 
Example #28
Source File: HeadersMessage.java    From bitherj with Apache License 2.0 5 votes vote down vote up
@Override
public void bitcoinSerializeToStream(OutputStream stream) throws IOException {
    stream.write(new VarInt(blockHeaders.size()).encode());
    for (Block header : blockHeaders) {
        if (header.getTransactions() == null)
            header.bitcoinSerializeToStream(stream);
        else
            header.cloneAsHeader().bitcoinSerializeToStream(stream);
        stream.write(0);
    }
}
 
Example #29
Source File: BlockchainService.java    From bither-android with Apache License 2.0 5 votes vote down vote up
private synchronized void startPeer() {
    try {
        if (peerCanNotRun) {
            return;
        }
        if (UpgradeUtil.needUpgrade()) {
            return;
        }
        if (!AppSharedPreference.getInstance().getDownloadSpvFinish()) {
            Block block = BlockUtil.dowloadSpvBlock();
            if (block == null) {
                return;
            }
        }
        if (AppSharedPreference.getInstance().getAppMode() != BitherjSettings.AppMode.COLD) {
            if (!AppSharedPreference.getInstance().getBitherjDoneSyncFromSpv()) {
                if (!PeerManager.instance().isConnected()) {
                    PeerManager.instance().start();
                    if (!spvFinishedReceivered) {
                        final IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(NotificationAndroidImpl.ACTION_SYNC_FROM_SPV_FINISHED);
                        spvFinishedReceiver = new SPVFinishedReceiver();
                        registerReceiver(spvFinishedReceiver, intentFilter);
                        spvFinishedReceivered = true;
                    }
                }
            } else {
                if (!AddressManager.getInstance().addressIsSyncComplete()) {
                    TransactionsUtil.getMyTxFromBither();
                }
                startPeerManager();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example #30
Source File: BlockMessage.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a block initialized with all the given fields.
 * //     * @param params Which network the block is for.
 *
 * @param version          This should usually be set to 1 or 2, depending on if the height is in the coinbase input.
 * @param prevBlockHash    Reference to previous block in the chain or {@link net.bither.bitherj.utils.Sha256Hash#ZERO_HASH} if genesis.
 * @param merkleRoot       The root of the merkle tree formed by the transactions.
 * @param time             UNIX time when the block was mined.
 * @param difficultyTarget Number which this block hashes lower than.
 * @param nonce            Arbitrary number to make the block hash lower than the target.
 * @param transactions     List of transactions including the coinbase.
 */
public BlockMessage(long version, byte[] prevBlockHash, byte[] merkleRoot, long time,
                    long difficultyTarget, long nonce, List<Tx> transactions) {
    super();
    block = new Block();
    block.setBlockVer(version);
    block.setBlockBits(difficultyTarget);
    block.setBlockTime((int) time);
    block.setBlockPrev(prevBlockHash);
    block.setBlockRoot(merkleRoot);
    block.setBlockNonce(nonce);
    block.setTransactions(transactions);
}