org.fisco.bcos.web3j.protocol.core.Request Java Examples

The following examples show how to use org.fisco.bcos.web3j.protocol.core.Request. 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: RawTransactionManager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public SendTransaction signAndSend(
        RawTransaction rawTransaction, TransactionSucCallback callback) throws IOException {

    byte[] signedMessage;

    if (chainId > ChainId.NONE) {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
    } else {
        signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
    }

    String hexValue = Numeric.toHexString(signedMessage);
    Request<?, SendTransaction> request = web3j.sendRawTransaction(hexValue);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(callback);
    request.sendOnly();

    return null;
}
 
Example #2
Source File: ExtendedRawTransactionManager.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Override
public SendTransaction sendTransaction(
        String signedTransaction, TransactionSucCallback callback)
        throws IOException, TxHashMismatchException {
    Request<?, SendTransaction> request = web3j.sendRawTransaction(signedTransaction);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(callback);

    request.sendOnly();

    return null;

    /*
    if (ethSendTransaction != null && !ethSendTransaction.hasError()) {
        String txHashLocal = Hash.sha3(signedTransaction);
        String txHashRemote = ethSendTransaction.getTransactionHash();
        if (!txHashVerifier.verify(txHashLocal, txHashRemote)) {
            throw new TxHashMismatchException(txHashLocal, txHashRemote);
        }
    }

    return ethSendTransaction;
    */
}
 
Example #3
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 #4
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Notification<?>> Flowable<T> subscribe(
        Request request, String unsubscribeMethod, Class<T> responseType) {
    // We can't use usual Observer since we can call "onError"
    // before first client is subscribed and we need to
    // preserve it
    BehaviorSubject<T> subject = BehaviorSubject.create();

    // We need to subscribe synchronously, since if we return
    // an Flowable to a client before we got a reply
    // a client can unsubscribe before we know a subscription
    // id and this can cause a race condition
    subscribeToEventsStream(request, subject, responseType);

    return subject.doOnDispose(() -> closeSubscription(subject, unsubscribeMethod))
            .toFlowable(BackpressureStrategy.BUFFER);
}
 
Example #5
Source File: TransService.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * send message to node.
 * 
 * @param signMsg signMsg
 * @param future future
 */
public void sendMessage(int groupId, String signMsg,
        final CompletableFuture<TransactionReceipt> future) throws IOException {
    Request<?, SendTransaction> request = web3jMap.get(groupId).sendRawTransaction(signMsg);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(new TransactionSucCallback() {
        @Override
        public void onResponse(TransactionReceipt receipt) {
            log.info("onResponse receipt:{}", receipt);
            future.complete(receipt);
            return;
        }
    });
    request.send();
}
 
Example #6
Source File: ManagedTransactionTester.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void prepareTransactionReceipt(TransactionReceipt transactionReceipt) throws IOException {
    BcosTransactionReceipt ethGetTransactionReceipt = new BcosTransactionReceipt();
    ethGetTransactionReceipt.setResult(transactionReceipt);

    Request<?, BcosTransactionReceipt> getTransactionReceiptRequest = mock(Request.class);
    when(getTransactionReceiptRequest.send()).thenReturn(ethGetTransactionReceipt);
    when(web3j.getTransactionReceipt(TRANSACTION_HASH))
            .thenReturn((Request) getTransactionReceiptRequest);
}
 
Example #7
Source File: ManagedTransactionTester.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void prepareTransactionRequest() throws IOException {
    SendTransaction sendTransaction = new SendTransaction();
    sendTransaction.setResult(TRANSACTION_HASH);

    Request<?, SendTransaction> rawTransactionRequest = mock(Request.class);
    when(rawTransactionRequest.send()).thenReturn(sendTransaction);
    when(web3j.sendRawTransaction(any(String.class)))
            .thenReturn((Request) rawTransactionRequest);
}
 
Example #8
Source File: ManagedTransactionTester.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
void prepareBlockNumberRequest() throws IOException {
    BlockNumber ethBlockNumber = new BlockNumber();
    ethBlockNumber.setResult("0x1");

    Request<?, BlockNumber> ethBlockNumberRequest = mock(Request.class);
    when(ethBlockNumberRequest.send()).thenReturn(ethBlockNumber);
    when(web3j.getBlockNumber()).thenReturn((Request) ethBlockNumberRequest);
    when(web3j.getBlockNumberCache()).thenReturn(new BigInteger("1"));
}
 
Example #9
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private Request<String, BcosUnsubscribe> unsubscribeRequest(
        String subscriptionId, String unsubscribeMethod) {
    return new Request<>(
            unsubscribeMethod,
            Collections.singletonList(subscriptionId),
            this,
            BcosUnsubscribe.class);
}
 
Example #10
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private <T extends Notification<?>> void subscribeToEventsStream(
        Request request, BehaviorSubject<T> subject, Class<T> responseType) {

    subscriptionRequestForId.put(
            request.getId(), new WebSocketSubscription<>(subject, responseType));
    try {
        send(request, BcosSubscribe.class);
    } catch (IOException e) {
        log.error("Failed to subscribe to RPC events with request id {}", request.getId());
        subject.onError(e);
    }
}
 
Example #11
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Response> CompletableFuture<T> sendAsync(
        Request request, Class<T> responseType) {

    CompletableFuture<T> result = new CompletableFuture<>();
    long requestId = request.getId();
    requestForId.put(requestId, new WebSocketRequest<>(result, responseType));
    try {
        sendRequest(request, requestId);
    } catch (IOException e) {
        closeRequest(requestId, e);
    }

    return result;
}
 
Example #12
Source File: Service.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Notification<?>> Flowable<T> subscribe(
        Request request, String unsubscribeMethod, Class<T> responseType) {
    throw new UnsupportedOperationException(
            String.format(
                    "Service %s does not support subscriptions",
                    this.getClass().getSimpleName()));
}
 
Example #13
Source File: ExtendedRawTransactonAndGetProofManager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public SendTransaction sendTransaction(
        String signedTransaction, TransactionSucCallback callback)
        throws IOException, TxHashMismatchException {
    Request<?, SendTransaction> request =
            getWeb3j().sendRawTransactionAndGetProof(signedTransaction);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(callback);

    request.sendOnly();

    return null;
}
 
Example #14
Source File: TransService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * send message to node.
 *
 * @param signMsg signMsg
 * @param future future
 */
public void sendMessage(Web3j web3j, String signMsg,
        final CompletableFuture<TransactionReceipt> future) throws IOException {
    Request<?, SendTransaction> request = web3j.sendRawTransaction(signMsg);
    request.setNeedTransCallback(true);
    request.setTransactionSucCallback(new TransactionSucCallback() {
        @Override
        public void onResponse(TransactionReceipt receipt) {
            log.info("onResponse receipt:{}", receipt);
            future.complete(receipt);
            return;
        }
    });
    request.send();
}
 
Example #15
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public void sendOnly(Request request) throws IOException {}
 
Example #16
Source File: Service.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Response> CompletableFuture<T> sendAsync(
        Request jsonRpc20Request, Class<T> responseType) {
    return Async.run(() -> send(jsonRpc20Request, responseType));
}
 
Example #17
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public void sendOnly(Request request) throws IOException {}
 
Example #18
Source File: ChannelEthereumService.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public String sendSpecial(Request request) throws IOException {
    byte[] payload = objectMapper.writeValueAsBytes(request);

    BcosRequest bcosRequest = new BcosRequest();
    if (channelService.getOrgID() != null) {
        bcosRequest.setKeyID(channelService.getOrgID());
    } else {
        bcosRequest.setKeyID(channelService.getAgencyName());
    }
    bcosRequest.setBankNO("");
    bcosRequest.setContent(new String(payload));
    bcosRequest.setMessageID(channelService.newSeq());

    if (timeout != 0) {
        bcosRequest.setTimeout(timeout);
    }

    BcosResponse response;
    if (!request.isNeedTransCallback()) {
        response = channelService.sendEthereumMessage(bcosRequest);
    } else {
        response =
                channelService.sendEthereumMessage(
                        bcosRequest, request.getTransactionSucCallback());
    }
    logger.trace(
            "bcos request:{} {}",
            bcosRequest.getMessageID(),
            objectMapper.writeValueAsString(request));
    logger.trace(
            "bcos response:{} {} {}",
            bcosRequest.getMessageID(),
            response.getErrorCode(),
            response.getContent());
    if (response.getErrorCode() == 0) {
        if (response.getContent().contains("error")) {
            Response t = objectMapper.readValue(response.getContent(), Response.class);
            throw new ResponseExcepiton(t.getError().getCode(), t.getError().getMessage());
        } else {
            String[] resultArray = response.getContent().split("result");
            String resultStr = resultArray[1];
            if ("\"".equals(resultStr.substring(2, 3)))
                return resultStr.substring(3, resultStr.length() - 3);
            else return resultStr.substring(2, resultStr.length() - 2);
        }
    } else {
        throw new IOException(response.getErrorMessage());
    }
}
 
Example #19
Source File: WebSocketService.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
private void sendRequest(Request request, long requestId) throws JsonProcessingException {
    String payload = objectMapper.writeValueAsString(request);
    log.debug("Sending request: {}", payload);
    webSocketClient.send(payload);
    setRequestTimeout(requestId);
}
 
Example #20
Source File: ConnectionCallback.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
private void queryBlockNumber(ChannelHandlerContext ctx) throws JsonProcessingException {

        final String host = ChannelHandlerContextHelper.getPeerHost(ctx);

        String seq = channelService.newSeq();

        BcosMessage bcosMessage = new BcosMessage();
        bcosMessage.setType((short) ChannelMessageType.CHANNEL_RPC_REQUEST.getType());
        bcosMessage.setSeq(seq);
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(channelService);

        Request<Integer, BlockNumber> request =
                new Request<>(
                        "getBlockNumber",
                        Arrays.asList(channelService.getGroupId()),
                        channelEthereumService,
                        BlockNumber.class);

        bcosMessage.setData(ObjectMapperFactory.getObjectMapper().writeValueAsBytes(request));
        ByteBuf byteBuf = ctx.alloc().buffer();
        bcosMessage.writeHeader(byteBuf);
        bcosMessage.writeExtra(byteBuf);
        ctx.writeAndFlush(byteBuf);

        String content = new String(bcosMessage.getData());
        logger.info(" query block number host: {}, seq: {}, content: {}", host, seq, content);

        channelService
                .getSeq2Callback()
                .put(
                        seq,
                        new BcosResponseCallback() {
                            @Override
                            public void onResponse(BcosResponse response) {
                                try {
                                    BlockNumber blockNumber =
                                            ObjectMapperFactory.getObjectMapper()
                                                    .readValue(
                                                            response.getContent(),
                                                            BlockNumber.class);

                                    SocketChannel socketChannel = (SocketChannel) ctx.channel();
                                    InetSocketAddress socketAddress = socketChannel.remoteAddress();
                                    channelService
                                            .getNodeToBlockNumberMap()
                                            .put(
                                                    socketAddress.getAddress().getHostAddress()
                                                            + socketAddress.getPort(),
                                                    blockNumber.getBlockNumber());

                                    logger.info(
                                            " query blocknumer, host:{}, blockNumber: {} ",
                                            host,
                                            blockNumber.getBlockNumber());
                                } catch (Exception e) {
                                    logger.error(
                                            " query blocknumer failed, host: {}, message: {} ",
                                            host,
                                            e.getMessage());

                                    throw new MessageDecodingException(response.getContent());
                                }
                            }
                        });
    }
 
Example #21
Source File: Web3jService.java    From web3sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Subscribe to a stream of notifications. A stream of notifications is opened by by performing
 * a specified JSON-RPC request and is closed by calling the unsubscribe method. Different
 * WebSocket implementations use different pair of subscribe/unsubscribe methods.
 *
 * <p>This method creates an Flowable that can be used to subscribe to new notifications. When a
 * client unsubscribes from this Flowable the service unsubscribes from the underlying stream of
 * events.
 *
 * @param request JSON-RPC request that will be send to subscribe to a stream of events
 * @param unsubscribeMethod method that will be called to unsubscribe from a stream of
 *     notifications
 * @param responseType class of incoming events objects in a stream
 * @param <T> type of incoming event objects
 * @return a {@link Flowable} instance that emits incoming events
 */
@Deprecated
<T extends Notification<?>> Flowable<T> subscribe(
        Request request, String unsubscribeMethod, Class<T> responseType);
 
Example #22
Source File: Web3jService.java    From web3sdk with Apache License 2.0 votes vote down vote up
<T extends Response> CompletableFuture<T> sendAsync(Request request, Class<T> responseType); 
Example #23
Source File: Web3jService.java    From web3sdk with Apache License 2.0 votes vote down vote up
void sendOnly(Request request) throws IOException; 
Example #24
Source File: Web3jService.java    From web3sdk with Apache License 2.0 votes vote down vote up
<T extends Response> T send(Request request, Class<T> responseType) throws IOException;