Search in sources :

Example 1 with BcosMessage

use of org.fisco.bcos.channel.dto.BcosMessage in project web3sdk by FISCO-BCOS.

the class Service method asyncSendEthereumMessage.

public void asyncSendEthereumMessage(BcosRequest request, BcosResponseCallback callback) {
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setSeq(request.getMessageID());
    bcosMessage.setResult(0);
    bcosMessage.setType((short) 0x12);
    bcosMessage.setData(request.getContent().getBytes());
    // select node
    try {
        ChannelConnections channelConnections = allChannelConnections.getAllChannelConnections().stream().filter(x -> x.getGroupId() == groupId).findFirst().get();
        if (channelConnections == null) {
            if (orgID != null) {
                logger.error("not found:{}", orgID);
                throw new TransactionException("not found orgID");
            } else {
                logger.error("not found:{}", agencyName);
                throw new TransactionException("not found agencyName");
            }
        }
        ChannelHandlerContext ctx = channelConnections.randomNetworkConnection(nodeToBlockNumberMap);
        ByteBuf out = ctx.alloc().buffer();
        bcosMessage.writeHeader(out);
        bcosMessage.writeExtra(out);
        seq2Callback.put(request.getMessageID(), callback);
        if (request.getTimeout() > 0) {
            final BcosResponseCallback callbackInner = callback;
            callback.setTimeout(timeoutHandler.newTimeout(new TimerTask() {

                BcosResponseCallback _callback = callbackInner;

                @Override
                public void run(Timeout timeout) throws Exception {
                    logger.error("process bcos message timeout, seq: {}, timeout: {}", bcosMessage.getSeq(), request.getTimeout());
                    // handle timer
                    _callback.onTimeout();
                }
            }, request.getTimeout(), TimeUnit.MILLISECONDS));
        }
        ctx.writeAndFlush(out);
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        InetSocketAddress socketAddress = socketChannel.remoteAddress();
        logger.debug("selected node {}:{} bcos request, seq:{}", socketAddress.getAddress().getHostAddress(), socketAddress.getPort(), bcosMessage.getSeq());
    } catch (Exception e) {
        logger.error(" error message:{}, error: {} ", e.getMessage(), e);
        BcosResponse response = new BcosResponse();
        response.setErrorCode(-1);
        response.setErrorMessage(e.getMessage() + " requset send failed! please check the log file content for reasons.");
        response.setContent("");
        response.setMessageID(request.getMessageID());
        if (callback.getTimeout() != null) {
            callback.getTimeout().cancel();
        }
        callback.onResponse(response);
    }
}
Also used : ChannelConnections(org.fisco.bcos.channel.handler.ChannelConnections) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) SocketChannel(io.netty.channel.socket.SocketChannel) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) TimerTask(io.netty.util.TimerTask) Timeout(io.netty.util.Timeout) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 2 with BcosMessage

use of org.fisco.bcos.channel.dto.BcosMessage in project web3sdk by FISCO-BCOS.

the class Service method sendHeartbeatMessage.

public void sendHeartbeatMessage(ChannelHandlerContext ctx) {
    Message message = new BcosMessage();
    message.setSeq(UUID.randomUUID().toString().replaceAll("-", ""));
    message.setResult(0);
    message.setType((short) ChannelMessageType.CLIENT_HEARTBEAT.getType());
    HeartBeatParser heartBeatParser = new HeartBeatParser(ChannelHandlerContextHelper.getProtocolVersion(ctx));
    try {
        message.setData(heartBeatParser.encode("0"));
    } catch (JsonProcessingException e) {
        logger.error(" write json failed, message: {}", e.getMessage());
        return;
    }
    ByteBuf out = ctx.alloc().buffer();
    message.writeHeader(out);
    message.writeExtra(out);
    ctx.writeAndFlush(out);
}
Also used : BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) Message(org.fisco.bcos.channel.handler.Message) TopicVerifyMessage(org.fisco.bcos.channel.dto.TopicVerifyMessage) HeartBeatParser(org.fisco.bcos.channel.protocol.parser.HeartBeatParser) ByteBuf(io.netty.buffer.ByteBuf) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with BcosMessage

use of org.fisco.bcos.channel.dto.BcosMessage in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method queryNodeVersion.

private void queryNodeVersion(ChannelHandlerContext ctx) throws JsonProcessingException {
    final String host = ChannelHandlerContextHelper.getPeerHost(ctx);
    String seq = UUID.randomUUID().toString().replaceAll("-", "");
    Request<?, NodeVersion> request = new Request<>("getClientVersion", Arrays.asList(), null, NodeVersion.class);
    byte[] payload = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(request);
    String content = new String(payload);
    logger.info(" query node version host: {}, seq: {}, content: {}", host, seq, content);
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setType((short) ChannelMessageType.CHANNEL_RPC_REQUEST.getType());
    bcosMessage.setSeq(seq);
    bcosMessage.setResult(0);
    bcosMessage.setData(payload);
    ByteBuf byteBuf = ctx.alloc().buffer();
    bcosMessage.writeHeader(byteBuf);
    bcosMessage.writeExtra(byteBuf);
    BcosResponseCallback callback = new BcosResponseCallback() {

        @Override
        public void onResponse(BcosResponse response) {
            try {
                if (response.getErrorCode() == ChannelMessageError.MESSAGE_TIMEOUT.getError()) {
                    // The fisco node version number is below 2.1.0 when request timeout
                    ChannelHandlerContextHelper.setProtocolVersion(ctx, EnumChannelProtocolVersion.VERSION_1, "below-2.1.0-timeout");
                    logger.info(" query node version timeout, content: {}", response.getContent());
                    sendUpdateTopicMessage(ctx);
                    queryBlockNumber(ctx);
                    return;
                } else if (response.getErrorCode() != 0) {
                    logger.error(" fisco node version response, code: {}, message: {}", response.getErrorCode(), response.getErrorMessage());
                    throw new ChannelPrococolExceiption(" query node version failed, code: " + response.getErrorCode() + ", message: " + response.getErrorMessage());
                }
                Response<NodeVersion.Version> nodeVersion = ObjectMapperFactory.getObjectMapper().readValue(response.getContent(), NodeVersion.class);
                logger.info(" node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                if (EnumNodeVersion.channelProtocolHandleShakeSupport(nodeVersion.getResult().getSupportedVersion())) {
                    // fisco node support channel protocol handshake, start it
                    logger.info(" support channel handshake node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                    queryChannelProtocolVersion(ctx);
                } else {
                    // default channel protocol
                    ChannelHandlerContextHelper.setProtocolVersion(ctx, EnumChannelProtocolVersion.VERSION_1, nodeVersion.getResult().getSupportedVersion());
                    logger.info(" not support channel handshake set default ,node: {}, content: {}", nodeVersion.getResult(), response.getContent());
                    sendUpdateTopicMessage(ctx);
                    queryBlockNumber(ctx);
                // channelService.getEventLogFilterManager().sendFilter();
                }
            } catch (Exception e) {
                logger.error(" query node version failed, message: {}", e.getMessage());
                ctx.writeAndFlush("").addListener(ChannelFutureListener.CLOSE);
            }
        }
    };
    final BcosResponseCallback callbackInner = callback;
    callback.setTimeout(channelService.getTimeoutHandler().newTimeout(new TimerTask() {

        BcosResponseCallback _callback = callbackInner;

        @Override
        public void run(Timeout timeout) throws Exception {
            // handle timer
            _callback.onTimeout();
            logger.error("queryNodeVersion timeout, seq: {}", bcosMessage.getSeq());
        }
    }, queryNodeVersionTimeoutMS, TimeUnit.MILLISECONDS));
    channelService.getSeq2Callback().put(seq, callback);
    ctx.writeAndFlush(byteBuf);
}
Also used : BcosResponseCallback(org.fisco.bcos.channel.client.BcosResponseCallback) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) ChannelPrococolExceiption(org.fisco.bcos.channel.protocol.ChannelPrococolExceiption) Timeout(io.netty.util.Timeout) Request(org.fisco.bcos.web3j.protocol.core.Request) ByteBuf(io.netty.buffer.ByteBuf) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) EnumNodeVersion(org.fisco.bcos.fisco.EnumNodeVersion) NodeVersion(org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) TimerTask(io.netty.util.TimerTask) EnumNodeVersion(org.fisco.bcos.fisco.EnumNodeVersion) EnumChannelProtocolVersion(org.fisco.bcos.channel.protocol.EnumChannelProtocolVersion) NodeVersion(org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion)

Example 4 with BcosMessage

use of org.fisco.bcos.channel.dto.BcosMessage in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method queryChannelProtocolVersion.

private void queryChannelProtocolVersion(ChannelHandlerContext ctx) throws ChannelPrococolExceiption, IOException {
    final String host = ChannelHandlerContextHelper.getPeerHost(ctx);
    ChannelHandshake channelHandshake = new ChannelHandshake();
    String seq = UUID.randomUUID().toString().replaceAll("-", "");
    byte[] payload = ObjectMapperFactory.getObjectMapper().writeValueAsBytes(channelHandshake);
    String content = new String(payload);
    logger.debug(" channel protocol handshake, host: {}, seq: {}, content: {}", host, seq, content);
    BcosMessage bcosMessage = new BcosMessage();
    bcosMessage.setType((short) ChannelMessageType.CLIENT_HANDSHAKE.getType());
    bcosMessage.setSeq(seq);
    bcosMessage.setResult(0);
    bcosMessage.setData(payload);
    ByteBuf byteBuf = ctx.alloc().buffer();
    bcosMessage.writeHeader(byteBuf);
    bcosMessage.writeExtra(byteBuf);
    channelService.getSeq2Callback().put(seq, new BcosResponseCallback() {

        @Override
        public void onResponse(BcosResponse response) {
            try {
                if (response.getErrorCode() != 0) {
                    logger.error(" channel protocol handshake request failed, code: {}, message: {}", response.getErrorCode(), response.getErrorMessage());
                    throw new ChannelPrococolExceiption(" channel protocol handshake request failed, code: " + response.getErrorCode() + ", message: " + response.getErrorMessage());
                }
                ChannelProtocol channelProtocol = ObjectMapperFactory.getObjectMapper().readValue(response.getContent(), ChannelProtocol.class);
                EnumChannelProtocolVersion enumChannelProtocolVersion = EnumChannelProtocolVersion.toEnum(channelProtocol.getProtocol());
                channelProtocol.setEnumProtocol(enumChannelProtocolVersion);
                logger.info(" channel protocol handshake success, set socket channel protocol, host: {}, channel protocol: {}", host, channelProtocol);
                ctx.channel().attr(AttributeKey.valueOf(EnumSocketChannelAttributeKey.CHANNEL_PROTOCOL_KEY.getKey())).set(channelProtocol);
                // 
                sendUpdateTopicMessage(ctx);
                queryBlockNumber(ctx);
            // channelService.getEventLogFilterManager().sendFilter();
            } catch (Exception e) {
                logger.error(" channel protocol handshake failed, exception: {}", e.getMessage());
                ctx.writeAndFlush("").addListener(ChannelFutureListener.CLOSE);
            }
        }
    });
    ctx.writeAndFlush(byteBuf);
}
Also used : EnumChannelProtocolVersion(org.fisco.bcos.channel.protocol.EnumChannelProtocolVersion) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) BcosResponseCallback(org.fisco.bcos.channel.client.BcosResponseCallback) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) ChannelPrococolExceiption(org.fisco.bcos.channel.protocol.ChannelPrococolExceiption) ChannelProtocol(org.fisco.bcos.channel.protocol.ChannelProtocol) ByteBuf(io.netty.buffer.ByteBuf) ChannelHandshake(org.fisco.bcos.channel.protocol.ChannelHandshake) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 5 with BcosMessage

use of org.fisco.bcos.channel.dto.BcosMessage in project web3sdk by FISCO-BCOS.

the class ConnectionCallback method onMessage.

@Override
public void onMessage(ChannelHandlerContext ctx, ByteBuf message) {
    try {
        Message msg = new Message();
        try {
            msg.readHeader(message);
        } catch (Exception e) {
            String host = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
            Integer port = ((SocketChannel) ctx.channel()).remoteAddress().getPort();
            logger.error(" Maybe p2p port is used to channel connection, please check the configuration, peer {}:{}", host, port);
            throw new RuntimeException(e.getCause());
        }
        logger.trace("onMessage, seq:{}, type: {}, result: {}", msg.getSeq(), msg.getType(), msg.getResult());
        if (msg.getType() == ChannelMessageType.AMOP_REQUEST.getType() || msg.getType() == ChannelMessageType.AMOP_RESPONSE.getType() || msg.getType() == ChannelMessageType.AMOP_MULBROADCAST.getType()) {
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveChannelMessage2(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.CHANNEL_RPC_REQUEST.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveEthereumMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.CLIENT_HEARTBEAT.getType()) {
            msg.readExtra(message);
            channelService.onReceiveHeartbeat(ctx, msg);
        } else if (msg.getType() == ChannelMessageType.CLIENT_HANDSHAKE.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveEthereumMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.CLIENT_REGISTER_EVENT_LOG.getType()) {
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveRegisterEventResponse(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.TRANSACTION_NOTIFY.getType()) {
            BcosMessage fiscoMessage = new BcosMessage(msg);
            fiscoMessage.readExtra(message);
            channelService.onReceiveTransactionMessage(ctx, fiscoMessage);
        } else if (msg.getType() == ChannelMessageType.BLOCK_NOTIFY.getType()) {
            // new block notify
            ChannelMessage2 channelMessage = new ChannelMessage2(msg);
            channelMessage.readExtra(message);
            channelService.onReceiveBlockNotify(ctx, channelMessage);
        } else if (msg.getType() == ChannelMessageType.EVENT_LOG_PUSH.getType()) {
            BcosMessage bcosMessage = new BcosMessage(msg);
            bcosMessage.readExtra(message);
            channelService.onReceiveEventLogPush(ctx, bcosMessage);
        } else if (msg.getType() == ChannelMessageType.REQUEST_TOPICCERT.getType()) {
            logger.info("get generate rand value request data");
            TopicVerifyMessage channelMessage = new TopicVerifyMessage(msg);
            channelMessage.readExtra(message);
            try {
                channelService.checkTopicVerify(ctx, channelMessage);
            } catch (IOException e) {
                logger.error("on receive channel failed");
            }
        } else {
            logger.error("unknown message type:{}", msg.getType());
        }
    } finally {
        message.release();
    }
}
Also used : BigInteger(java.math.BigInteger) SocketChannel(io.netty.channel.socket.SocketChannel) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) ChannelMessage2(org.fisco.bcos.channel.dto.ChannelMessage2) BcosMessage(org.fisco.bcos.channel.dto.BcosMessage) TopicVerifyMessage(org.fisco.bcos.channel.dto.TopicVerifyMessage) IOException(java.io.IOException) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) TopicVerifyMessage(org.fisco.bcos.channel.dto.TopicVerifyMessage)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 BcosMessage (org.fisco.bcos.channel.dto.BcosMessage)6 ByteBuf (io.netty.buffer.ByteBuf)5 IOException (java.io.IOException)5 BcosResponse (org.fisco.bcos.channel.dto.BcosResponse)4 MessageDecodingException (org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException)4 SocketChannel (io.netty.channel.socket.SocketChannel)3 BcosResponseCallback (org.fisco.bcos.channel.client.BcosResponseCallback)3 Timeout (io.netty.util.Timeout)2 TimerTask (io.netty.util.TimerTask)2 BigInteger (java.math.BigInteger)2 InetSocketAddress (java.net.InetSocketAddress)2 TopicVerifyMessage (org.fisco.bcos.channel.dto.TopicVerifyMessage)2 ChannelPrococolExceiption (org.fisco.bcos.channel.protocol.ChannelPrococolExceiption)2 EnumChannelProtocolVersion (org.fisco.bcos.channel.protocol.EnumChannelProtocolVersion)2 Request (org.fisco.bcos.web3j.protocol.core.Request)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1