use of org.fisco.bcos.channel.dto.BcosResponse 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);
}
}
use of org.fisco.bcos.channel.dto.BcosResponse in project web3sdk by FISCO-BCOS.
the class Service method sendEthereumMessage.
public BcosResponse sendEthereumMessage(BcosRequest request) {
class Callback extends BcosResponseCallback {
public transient BcosResponse bcosResponse;
public transient Semaphore semaphore = new Semaphore(1, true);
Callback() {
try {
semaphore.acquire(1);
} catch (InterruptedException e) {
logger.error("error :", e);
Thread.currentThread().interrupt();
}
}
@Override
public void onResponse(BcosResponse response) {
bcosResponse = response;
if (bcosResponse != null && bcosResponse.getContent() != null) {
logger.debug("response: {}", response.getContent());
} else {
logger.error("response is null");
}
semaphore.release();
}
}
;
Callback callback = new Callback();
asyncSendEthereumMessage(request, callback);
try {
callback.semaphore.acquire(1);
} catch (InterruptedException e) {
logger.error("system error:", e);
Thread.currentThread().interrupt();
}
return callback.bcosResponse;
}
use of org.fisco.bcos.channel.dto.BcosResponse 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);
}
use of org.fisco.bcos.channel.dto.BcosResponse 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);
}
use of org.fisco.bcos.channel.dto.BcosResponse in project web3sdk by FISCO-BCOS.
the class ChannelEthereumService method sendOnly.
@Override
public void sendOnly(Request request) throws IOException {
byte[] payload = objectMapper.writeValueAsBytes(request);
BcosRequest fiscoRequest = new BcosRequest();
fiscoRequest.setKeyID(channelService.getOrgID());
fiscoRequest.setBankNO("");
fiscoRequest.setContent(new String(payload));
fiscoRequest.setMessageID(channelService.newSeq());
if (timeout != 0) {
fiscoRequest.setTimeout(timeout);
}
if (!request.isNeedTransCallback()) {
channelService.asyncSendEthereumMessage(fiscoRequest, new BcosResponseCallback() {
@Override
public void onResponse(BcosResponse response) {
try {
logger.debug("fisco Request:{} {}", fiscoRequest.getMessageID(), objectMapper.writeValueAsString(request));
logger.debug("fisco Response:{} {} {}", fiscoRequest.getMessageID(), response.getErrorCode(), response.getContent());
if (response.getErrorCode() != 0) {
logger.error("Error: " + response.getErrorCode());
}
} catch (Exception e) {
logger.error("Error: ", e);
}
}
});
} else {
channelService.asyncSendEthereumMessage(fiscoRequest, new BcosResponseCallback() {
@Override
public void onResponse(BcosResponse response) {
try {
logger.debug("fisco Request:{} {}", fiscoRequest.getMessageID(), objectMapper.writeValueAsString(request));
logger.debug("fisco Response:{} {} {}", fiscoRequest.getMessageID(), response.getErrorCode(), response.getContent());
if (response.getErrorCode() == 0) {
// SendTransaction
SendTransaction sendTransaction = objectMapper.readValue(response.getContent(), SendTransaction.class);
if (sendTransaction.getError() == null) {
logger.debug("sendRawTransaction response ok, transaction hash: {} ", sendTransaction.getResult());
} else {
TransactionReceipt receipt = new TransactionReceipt();
receipt.setStatus(String.valueOf(sendTransaction.getError().getCode()));
receipt.setMessage(sendTransaction.getError().getMessage());
// optional code
if (channelService.getThreadPool() == null) {
channelService.onReceiveTransactionMessage(fiscoRequest.getMessageID(), receipt);
} else {
// Execute the callback function in the thread pool
channelService.getThreadPool().execute(new Runnable() {
@Override
public void run() {
channelService.onReceiveTransactionMessage(fiscoRequest.getMessageID(), receipt);
}
});
}
logger.debug(" sendRawTransaction response not ok, code: {}, message: {} ", receipt.getStatus(), receipt.getMessage());
}
}
} catch (Exception e) {
logger.error("Error: ", e);
}
}
}, request.getTransactionSucCallback());
}
}
Aggregations