Search in sources :

Example 1 with Frame

use of org.ethereum.net.rlpx.FrameCodec.Frame in project rskj by rsksmart.

the class HandshakeHandler method decodeHandshake.

// consume handshake, producing no resulting message to upper layers
private void decodeHandshake(final ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    if (handshake.isInitiator()) {
        if (frameCodec == null) {
            byte[] responsePacket = new byte[AuthResponseMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(responsePacket.length)) {
                return;
            }
            buffer.readBytes(responsePacket);
            try {
                // trying to decode as pre-EIP-8
                AuthResponseMessage response = handshake.handleAuthResponse(myKey, initiatePacket, responsePacket);
                loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), response);
            } catch (Throwable t) {
                // it must be format defined by EIP-8 then
                responsePacket = readEIP8Packet(buffer, responsePacket);
                if (responsePacket == null) {
                    return;
                }
                AuthResponseMessageV4 response = handshake.handleAuthResponseV4(myKey, initiatePacket, responsePacket);
                loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), response);
            }
            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);
            loggerNet.trace("auth exchange done");
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId), null);
        } else {
            loggerWire.debug("MessageCodec: Buffer bytes: " + buffer.readableBytes());
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty()) {
                return;
            }
            Frame frame = frames.get(0);
            byte[] payload = ByteStreams.toByteArray(frame.getStream());
            if (frame.getType() == P2pMessageCodes.HELLO.asByte()) {
                HelloMessage helloMessage = new HelloMessage(payload);
                loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), helloMessage);
                isHandshakeDone = true;
                this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, helloMessage);
                recordSuccessfulHandshake(ctx);
            } else {
                DisconnectMessage message = new DisconnectMessage(payload);
                loggerNet.trace("From: \t{} \tRecv: \t{}", channel, message);
                channel.getNodeStatistics().nodeDisconnectedRemote(message.getReason());
            }
        }
    } else {
        loggerWire.debug("Not initiator.");
        if (frameCodec == null) {
            loggerWire.debug("FrameCodec == null");
            byte[] authInitPacket = new byte[AuthInitiateMessage.getLength() + ECIESCoder.getOverhead()];
            if (!buffer.isReadable(authInitPacket.length)) {
                return;
            }
            buffer.readBytes(authInitPacket);
            this.handshake = new EncryptionHandshake();
            byte[] responsePacket;
            try {
                // trying to decode as pre-EIP-8
                AuthInitiateMessage initiateMessage = handshake.decryptAuthInitiate(authInitPacket, myKey);
                loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), initiateMessage);
                AuthResponseMessage response = handshake.makeAuthInitiate(initiateMessage, myKey);
                loggerNet.trace("To: \t{} \tSend: \t{}", ctx.channel().remoteAddress(), response);
                responsePacket = handshake.encryptAuthResponse(response);
            } catch (Throwable t) {
                // it must be format defined by EIP-8 then
                try {
                    authInitPacket = readEIP8Packet(buffer, authInitPacket);
                    if (authInitPacket == null) {
                        return;
                    }
                    AuthInitiateMessageV4 initiateMessage = handshake.decryptAuthInitiateV4(authInitPacket, myKey);
                    loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), initiateMessage);
                    AuthResponseMessageV4 response = handshake.makeAuthInitiateV4(initiateMessage, myKey);
                    loggerNet.trace("To: \t{} \tSend: \t{}", ctx.channel().remoteAddress(), response);
                    responsePacket = handshake.encryptAuthResponseV4(response);
                } catch (InvalidCipherTextException ce) {
                    loggerNet.warn("Can't decrypt AuthInitiateMessage from " + ctx.channel().remoteAddress() + ". Most likely the remote peer used wrong public key (NodeID) to encrypt message.");
                    return;
                }
            }
            handshake.agreeSecret(authInitPacket, responsePacket);
            EncryptionHandshake.Secrets secrets = this.handshake.getSecrets();
            this.frameCodec = new FrameCodec(secrets);
            ECPoint remotePubKey = this.handshake.getRemotePublicKey();
            byte[] compressed = remotePubKey.getEncoded(false);
            this.remoteId = new byte[compressed.length - 1];
            System.arraycopy(compressed, 1, this.remoteId, 0, this.remoteId.length);
            channel.setNode(remoteId);
            final ByteBuf byteBufMsg = ctx.alloc().buffer(responsePacket.length);
            byteBufMsg.writeBytes(responsePacket);
            ctx.writeAndFlush(byteBufMsg).sync();
        } else {
            List<Frame> frames = frameCodec.readFrames(buffer);
            if (frames == null || frames.isEmpty()) {
                return;
            }
            Frame frame = frames.get(0);
            Message message = new P2pMessageFactory().create((byte) frame.getType(), ByteStreams.toByteArray(frame.getStream()));
            loggerNet.trace("From: \t{} \tRecv: \t{}", ctx.channel().remoteAddress(), message);
            if (frame.getType() == P2pMessageCodes.DISCONNECT.asByte()) {
                loggerNet.info("Active remote peer disconnected right after handshake.");
                return;
            }
            if (frame.getType() != P2pMessageCodes.HELLO.asByte()) {
                throw new RuntimeException("The message type is not HELLO or DISCONNECT: " + message);
            }
            HelloMessage inboundHelloMessage = (HelloMessage) message;
            // Secret authentication finish here
            channel.sendHelloMessage(ctx, frameCodec, Hex.toHexString(nodeId), inboundHelloMessage);
            isHandshakeDone = true;
            this.channel.publicRLPxHandshakeFinished(ctx, frameCodec, inboundHelloMessage);
            recordSuccessfulHandshake(ctx);
        }
    }
    channel.getNodeStatistics().rlpxInHello.add();
}
Also used : Frame(org.ethereum.net.rlpx.FrameCodec.Frame) InvalidCipherTextException(org.spongycastle.crypto.InvalidCipherTextException) HelloMessage(org.ethereum.net.p2p.HelloMessage) DisconnectMessage(org.ethereum.net.p2p.DisconnectMessage) Message(org.ethereum.net.message.Message) HelloMessage(org.ethereum.net.p2p.HelloMessage) DisconnectMessage(org.ethereum.net.p2p.DisconnectMessage) P2pMessageFactory(org.ethereum.net.p2p.P2pMessageFactory) ECPoint(org.spongycastle.math.ec.ECPoint) ByteBuf(io.netty.buffer.ByteBuf)

Example 2 with Frame

use of org.ethereum.net.rlpx.FrameCodec.Frame in project rskj by rsksmart.

the class MessageCodec method splitMessageToFrames.

private List<Frame> splitMessageToFrames(Message msg) {
    byte code = getCode(msg.getCommand());
    List<Frame> ret = new ArrayList<>();
    byte[] bytes = msg.getEncoded();
    int curPos = 0;
    while (curPos < bytes.length) {
        int newPos = min(curPos + maxFramePayloadSize, bytes.length);
        byte[] frameBytes = curPos == 0 && newPos == bytes.length ? bytes : Arrays.copyOfRange(bytes, curPos, newPos);
        ret.add(new Frame(code, frameBytes));
        curPos = newPos;
    }
    if (ret.size() > 1) {
        // frame has been split
        int contextId = contextIdCounter.getAndIncrement();
        ret.get(0).totalFrameSize = bytes.length;
        loggerWire.debug("Message (size " + bytes.length + ") split to " + ret.size() + " frames. Context-id: " + contextId);
        for (Frame frame : ret) {
            frame.contextId = contextId;
        }
    }
    return ret;
}
Also used : Frame(org.ethereum.net.rlpx.FrameCodec.Frame)

Example 3 with Frame

use of org.ethereum.net.rlpx.FrameCodec.Frame in project rskj by rsksmart.

the class MessageCodec method decode.

@Override
protected void decode(ChannelHandlerContext ctx, Frame frame, List<Object> out) throws Exception {
    if (frame.isChunked()) {
        if (!supportChunkedFrames && frame.totalFrameSize > 0) {
            throw new RuntimeException("Faming is not supported in this configuration.");
        }
        Pair<? extends List<Frame>, AtomicInteger> frameParts = incompleteFrames.get(frame.contextId);
        if (frameParts == null) {
            if (frame.totalFrameSize < 0) {
                // TODO: refactor this logic (Cpp sends non-chunked frames with context-id)
                Message message = decodeMessage(Collections.singletonList(frame));
                out.add(message);
                return;
            } else {
                frameParts = Pair.of(new ArrayList<Frame>(), new AtomicInteger(0));
                incompleteFrames.put(frame.contextId, frameParts);
            }
        } else {
            if (frame.totalFrameSize >= 0) {
                loggerNet.warn("Non-initial chunked frame shouldn't contain totalFrameSize field (context-id: " + frame.contextId + ", totalFrameSize: " + frame.totalFrameSize + "). Discarding this frame and all previous.");
                incompleteFrames.remove(frame.contextId);
                return;
            }
        }
        frameParts.getLeft().add(frame);
        int curSize = frameParts.getRight().addAndGet(frame.size);
        if (loggerWire.isDebugEnabled()) {
            loggerWire.debug("Recv: Chunked (" + curSize + " of " + frameParts.getLeft().get(0).totalFrameSize + ") [size: " + frame.getSize() + "]");
        }
        if (curSize > frameParts.getLeft().get(0).totalFrameSize) {
            loggerNet.warn("The total frame chunks size (" + curSize + ") is greater than expected (" + frameParts.getLeft().get(0).totalFrameSize + "). Discarding the frame.");
            incompleteFrames.remove(frame.contextId);
            return;
        }
        if (curSize == frameParts.getLeft().get(0).totalFrameSize) {
            Message message = decodeMessage(frameParts.getLeft());
            incompleteFrames.remove(frame.contextId);
            out.add(message);
        }
    } else {
        Message message = decodeMessage(Collections.singletonList(frame));
        out.add(message);
    }
}
Also used : Frame(org.ethereum.net.rlpx.FrameCodec.Frame) Message(org.ethereum.net.message.Message) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 4 with Frame

use of org.ethereum.net.rlpx.FrameCodec.Frame in project rskj by rsksmart.

the class MessageCodec method decodeMessage.

private Message decodeMessage(List<Frame> frames) throws IOException {
    long frameType = frames.get(0).getType();
    byte[] payload = new byte[frames.size() == 1 ? frames.get(0).getSize() : frames.get(0).totalFrameSize];
    int pos = 0;
    for (Frame frame : frames) {
        pos += ByteStreams.read(frame.getStream(), payload, pos, frame.getSize());
    }
    if (loggerWire.isDebugEnabled()) {
        loggerWire.debug("Recv: Encoded: {} [{}]", frameType, Hex.toHexString(payload));
    }
    Message msg = createMessage((byte) frameType, payload);
    loggerNet.trace("From: \t{} \tRecv: \t{}", channel, msg);
    ethereumListener.onRecvMessage(channel, msg);
    channel.getNodeStatistics().rlpxInMessages.add();
    return msg;
}
Also used : Frame(org.ethereum.net.rlpx.FrameCodec.Frame) Message(org.ethereum.net.message.Message)

Aggregations

Frame (org.ethereum.net.rlpx.FrameCodec.Frame)4 Message (org.ethereum.net.message.Message)3 ByteBuf (io.netty.buffer.ByteBuf)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 DisconnectMessage (org.ethereum.net.p2p.DisconnectMessage)1 HelloMessage (org.ethereum.net.p2p.HelloMessage)1 P2pMessageFactory (org.ethereum.net.p2p.P2pMessageFactory)1 InvalidCipherTextException (org.spongycastle.crypto.InvalidCipherTextException)1 ECPoint (org.spongycastle.math.ec.ECPoint)1