org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock Java Examples

The following examples show how to use org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock. 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: MockBlockTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void getBlockNumber() throws IOException {

    BcosBlock block = objectMapper.readValue(rawResponse, BcosBlock.class);
    block.setRawResponse(rawResponse);

    Web3j web3j = Web3j.build(web3jService);
    when(web3jService.send(any(Request.class), eq(BcosBlock.class))).thenReturn(block);

    BcosBlock mockBlocks =
            web3j.getBlockByNumber(DefaultBlockParameter.valueOf(new BigInteger("1")), true)
                    .send();
    BcosBlock.Block mockBlock = mockBlocks.getBlock();
    assertEquals(mockBlock.getNonce(), new BigInteger("0"));
    assertTrue(mockBlock.getNumber().intValue() == 1);
}
 
Example #2
Source File: Web3ApiService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * getBlockByNumber.
 *
 * @param blockNumber blockNumber
 */
public BcosBlock.Block getBlockByNumber(int groupId, BigInteger blockNumber) {
    if (blockNumberCheck(groupId, blockNumber)) {
        throw new FrontException(ConstantCode.BLOCK_NUMBER_ERROR);
    }
    BcosBlock.Block block;
    try {
        block = getWeb3j(groupId)
                .getBlockByNumber(DefaultBlockParameter.valueOf(blockNumber), true)
                .send()
                .getBlock();
    } catch (IOException e) {
        log.info("get blocknumber failed" + e.getMessage());
        log.error("getBlAockByNumber fail. blockNumber:{} , groupID: {}", blockNumber, groupId);
        throw new FrontException(ConstantCode.NODE_REQUEST_FAILED);
    }
    return block;
}
 
Example #3
Source File: Web3ApiService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * getBlockTransCntByNumber.
 *
 * @param blockNumber blockNumber
 */
public int getBlockTransCntByNumber(int groupId, BigInteger blockNumber) {
    int transCnt;
    try {
        if (blockNumberCheck(groupId, blockNumber)) {
            throw new FrontException("ConstantCode.NODE_REQUEST_FAILED");
        }
        BcosBlock.Block block = getWeb3j(groupId)
                .getBlockByNumber(DefaultBlockParameter.valueOf(blockNumber), true)
                .send()
                .getBlock();
        transCnt = block.getTransactions().size();
    } catch (IOException e) {
        log.error("getBlockTransCntByNumber fail. blockNumber:{} ", blockNumber);
        throw new FrontException(ConstantCode.NODE_REQUEST_FAILED);
    }
    return transCnt;
}
 
Example #4
Source File: Web3SDK2Wrapper.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private static void getTbBlockList(List<TbBlock> tbBlocks, BcosBlock.Block block) throws BrokerException {
    if (block == null) {
        log.error("query block failed, block is null.");
        throw new BrokerException(ErrorCode.WEB3SDK_RPC_ERROR);
    }

    String blockTimestamp = DataTypeUtils.getTimestamp(block.getTimestamp().longValue());

    int transactions = 0;
    if (!block.getTransactions().isEmpty()) {
        transactions = block.getTransactions().size();
    }
    int sealerIndex = Integer.parseInt(block.getSealer().substring(2), 16);
    TbBlock tbBlock = new TbBlock(block.getHash(), block.getNumber(), blockTimestamp,
            transactions, sealerIndex);
    tbBlock.setSealer(block.getSealer());
    tbBlocks.add(tbBlock);
}
 
Example #5
Source File: Web3ApiController.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "getBlockByHash", notes = "Get block information based on block hash")
@ApiImplicitParam(name = "blockHash", value = "blockHash", required = true, dataType = "String",
        paramType = "path")
@GetMapping("/blockByHash/{blockHash}")
public BcosBlock.Block getBlockByHash(@PathVariable int groupId,
        @PathVariable String blockHash) {
    return web3ApiService.getBlockByHash(groupId, blockHash);
}
 
Example #6
Source File: CnsService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
boolean isSynced() throws Exception {
    SyncStatus ethSyncing = web3j.getSyncStatus().send();
    if (ethSyncing.isSyncing()) {
        return false;
    } else {
        BcosBlock block =
                web3j.getBlockByNumber(DefaultBlockParameterName.LATEST, false).send();
        long timestamp = block.getBlock().getTimestamp().longValueExact() * 1000;

        return System.currentTimeMillis() - syncThreshold < timestamp;
    }
}
 
Example #7
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        boolean fullTransactionObjects,
        Flowable<BcosBlock> onCompleteFlowable) {
    return null;
}
 
Example #8
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        DefaultBlockParameter endBlock,
        boolean fullTransactionObjects,
        boolean ascending) {
    return null;
}
 
Example #9
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        DefaultBlockParameter endBlock,
        boolean fullTransactionObjects) {
    return null;
}
 
Example #10
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, BcosBlock> getBlockByNumber(
        DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects) {
    return new Request<>(
            "getBlockByNumber",
            Arrays.asList(
                    groupId, defaultBlockParameter.getValue(), returnFullTransactionObjects),
            web3jService,
            BcosBlock.class);
}
 
Example #11
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Request<?, BcosBlock> getBlockByHash(
        String blockHash, boolean returnFullTransactionObjects) {
    return new Request<>(
            "getBlockByHash",
            Arrays.asList(groupId, blockHash, returnFullTransactionObjects),
            web3jService,
            BcosBlock.class);
}
 
Example #12
Source File: Web3ApiController.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "getBlockByNumber", notes = "Get block information based on block height")
@ApiImplicitParam(name = "blockNumber", value = "blockNumber", required = true,
        dataType = "BigInteger", paramType = "path")
@GetMapping("/blockByNumber/{blockNumber}")
public BcosBlock.Block getBlockByNumber(@PathVariable int groupId,
        @PathVariable BigInteger blockNumber) {
    return web3ApiService.getBlockByNumber(groupId, blockNumber);
}
 
Example #13
Source File: Web3ApiService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * getBlockByHash.
 *
 * @param blockHash blockHash
 */
public BcosBlock.Block getBlockByHash(int groupId, String blockHash) {
    BcosBlock.Block block;
    try {

        block = getWeb3j(groupId).getBlockByHash(blockHash, true)
                .send()
                .getBlock();
    } catch (IOException e) {
        log.error("getBlockByHash fail. blockHash:{} ", blockHash);
        throw new FrontException(ConstantCode.NODE_REQUEST_FAILED);
    }
    return block;
}
 
Example #14
Source File: Web3SDK2Wrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static List<TbBlock> getTbBlock(Web3j web3j, List<Long> blockNums, int timeout) throws ExecutionException, InterruptedException {

        List<CompletableFuture<TbBlock>> futureList = new ArrayList<>();
        for (Long blockNumber : blockNums) {
            CompletableFuture<TbBlock> future = CompletableFuture.supplyAsync(() -> {
                BcosBlock bcosBlock;
                try {
                    bcosBlock = web3j.getBlockByNumber(new DefaultBlockParameterNumber(blockNumber), true)
                            .sendAsync().get(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    log.error("query block by blockNumber failed. e:", e);
                    return null;
                }
                BcosBlock.Block block = bcosBlock.getBlock();
                if (block == null) {
                    return null;
                }

                String blockTimestamp = DataTypeUtils.getTimestamp(block.getTimestamp().longValue());
                int transactions = 0;
                if (!block.getTransactions().isEmpty()) {
                    transactions = block.getTransactions().size();
                }
                int sealerIndex = Integer.parseInt(block.getSealer().substring(2), 16);
                TbBlock tbBlock = new TbBlock(block.getHash(), block.getNumber(), blockTimestamp, transactions, sealerIndex);
                tbBlock.setSealer(block.getSealer());
                return tbBlock;
            });

            futureList.add(future);
        }

        return CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]))
                .thenApply(v -> futureList.stream().map(CompletableFuture::join).collect(Collectors.toList())).get();
    }
 
Example #15
Source File: Web3SDK2Wrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static void generateTbTransHashListPage(Integer pageIndex, Integer pageSize, ListPage<TbTransHash> tbTransHashListPage, List<TbTransHash> tbTransHashes, BcosBlock bcosBlock) throws BrokerException {
    BcosBlock.Block block = bcosBlock.getBlock();
    if (block == null || CollectionUtils.isEmpty(block.getTransactions())) {
        log.error("query transaction from block failed. transaction in block is empty");
        throw new BrokerException(ErrorCode.WEB3SDK_RPC_ERROR);
    }

    Integer transCount = block.getTransactions().size();

    if (pageIndex < 1 || (pageIndex - 1) * pageSize > transCount) {
        log.error("pageIndex error.");
        throw new BrokerException("pageIndex error.");
    }
    Integer transSize = (transCount <= pageIndex * pageSize) ? (transCount - ((pageIndex - 1) * pageSize)) : pageSize;
    Integer transIndexStart = (pageIndex - 1) * pageSize;

    List<Transaction> transactionHashList = block.getTransactions().stream()
            .map(transactionResult -> (Transaction) transactionResult.get()).collect(Collectors.toList()).subList(transIndexStart, transSize + transIndexStart);
    transactionHashList.forEach(tx -> {
        TbTransHash tbTransHash = new TbTransHash(tx.getHash(), tx.getFrom(), tx.getTo(),
                tx.getBlockNumber(), DataTypeUtils.getTimestamp(bcosBlock.getBlock().getTimestamp().longValue()));
        tbTransHashes.add(tbTransHash);
    });
    tbTransHashListPage.setPageSize(transSize);
    tbTransHashListPage.setTotal(transCount);
    tbTransHashListPage.setPageData(tbTransHashes);
}
 
Example #16
Source File: Web3jApITest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void getBlockByNumber() throws Exception {
  BcosBlock bcosBlock =
      web3j.getBlockByNumber(DefaultBlockParameter.valueOf(blockNumber), true).send();
  assertNotNull(bcosBlock.getBlock());
}
 
Example #17
Source File: Web3jApITest.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void getBlockByHash() throws Exception {
  BcosBlock bcosBlock = web3j.getBlockByHash(blockHash, true).send();
  assertNotNull(bcosBlock.getBlock());
}
 
Example #18
Source File: Ethereum.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
Request<?, BcosBlock> getBlockByNumber(
DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects);
 
Example #19
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public Flowable<BcosBlock> replayPastAndFutureBlocksFlowable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects) {
    return null;
}
 
Example #20
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public Flowable<BcosBlock> blockFlowable(boolean fullTransactionObjects) {
    return null;
}
 
Example #21
Source File: JsonRpc2_0Web3j.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects) {
    return null;
}
 
Example #22
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Create an {@link Flowable} instance that emits newly created blocks on the blockchain.
 *
 * @param fullTransactionObjects if true, provides transactions embedded in blocks, otherwise
 *     transaction hashes
 * @return a {@link Flowable} instance that emits all new blocks as they are added to the
 *     blockchain
 */
Flowable<BcosBlock> blockFlowable(boolean fullTransactionObjects);
 
Example #23
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Create a {@link Flowable} instance that emits all transactions from the blockchain starting
 * with a provided block number. Once it has replayed up to the most current block, the provided
 * Flowable is invoked.
 *
 * <p>To automatically subscribe to new blocks, use {@link
 * #replayPastAndFutureBlocksFlowable(DefaultBlockParameter, boolean)}.
 *
 * @param startBlock the block number we wish to request from
 * @param fullTransactionObjects if we require full {@link Transaction} objects to be provided
 *     in the {@link BcosBlock} responses
 * @param onCompleteFlowable a subsequent Flowable that we wish to run once we are caught up
 *     with the latest block
 * @return a {@link Flowable} instance to emit all requested blocks
 */
Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        boolean fullTransactionObjects,
        Flowable<BcosBlock> onCompleteFlowable);
 
Example #24
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Create an {@link Flowable} instance that emits all blocks from the blockchain contained
 * within the requested range.
 *
 * @param startBlock block number to commence with
 * @param endBlock block number to finish with
 * @param fullTransactionObjects if true, provides transactions embedded in blocks, otherwise
 *     transaction hashes
 * @return a {@link Flowable} instance to emit these blocks
 */
Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        DefaultBlockParameter endBlock,
        boolean fullTransactionObjects);
 
Example #25
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Create an {@link Flowable} instance that emits all blocks from the blockchain contained
 * within the requested range.
 *
 * @param startBlock block number to commence with
 * @param endBlock block number to finish with
 * @param fullTransactionObjects if true, provides transactions embedded in blocks, otherwise
 *     transaction hashes
 * @param ascending if true, emits blocks in ascending order between range, otherwise in
 *     descending order
 * @return a {@link Flowable} instance to emit these blocks
 */
Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock,
        DefaultBlockParameter endBlock,
        boolean fullTransactionObjects,
        boolean ascending);
 
Example #26
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link Flowable} instance that emits all blocks from the requested block number to
 * the most current. Once it has emitted the most current block, it starts emitting new blocks
 * as they are created.
 *
 * @param startBlock the block number we wish to request from
 * @param fullTransactionObjects if we require full {@link Transaction} objects to be provided
 *     in the {@link BcosBlock} responses
 * @return a {@link Flowable} instance to emit all requested blocks and future
 */
Flowable<BcosBlock> replayPastAndFutureBlocksFlowable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects);
 
Example #27
Source File: Web3jRx.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link Flowable} instance that emits all blocks from the requested block number to
 * the most current. Once it has emitted the most current block, onComplete is called.
 *
 * @param startBlock the block number we wish to request from
 * @param fullTransactionObjects if we require full {@link Transaction} objects to be provided
 *     in the {@link BcosBlock} responses
 * @return a {@link Flowable} instance to emit all requested blocks
 */
Flowable<BcosBlock> replayPastBlocksFlowable(
        DefaultBlockParameter startBlock, boolean fullTransactionObjects);
 
Example #28
Source File: Ethereum.java    From web3sdk with Apache License 2.0 votes vote down vote up
Request<?, BcosBlock> getBlockByHash(String blockHash, boolean returnFullTransactionObjects);