Search in sources :

Example 1 with P2pMessageFactory

use of org.ethereum.net.p2p.P2pMessageFactory 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 P2pMessageFactory

use of org.ethereum.net.p2p.P2pMessageFactory in project rskj by rsksmart.

the class Channel method init.

public void init(ChannelPipeline pipeline, String remoteId, boolean discoveryMode) {
    isActive = remoteId != null && !remoteId.isEmpty();
    pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(config.peerChannelReadTimeout(), TimeUnit.SECONDS));
    pipeline.addLast("handshakeHandler", handshakeHandler);
    this.discoveryMode = discoveryMode;
    if (discoveryMode) {
        // temporary key/nodeId to not accidentally smear our reputation with
        // unexpected disconnect
        handshakeHandler.generateTempKey();
    }
    handshakeHandler.setRemoteId(remoteId, this);
    messageCodec.setChannel(this);
    msgQueue.setChannel(this);
    p2pHandler.setMsgQueue(msgQueue);
    messageCodec.setP2pMessageFactory(new P2pMessageFactory());
}
Also used : P2pMessageFactory(org.ethereum.net.p2p.P2pMessageFactory) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Aggregations

P2pMessageFactory (org.ethereum.net.p2p.P2pMessageFactory)2 ByteBuf (io.netty.buffer.ByteBuf)1 ReadTimeoutHandler (io.netty.handler.timeout.ReadTimeoutHandler)1 Message (org.ethereum.net.message.Message)1 DisconnectMessage (org.ethereum.net.p2p.DisconnectMessage)1 HelloMessage (org.ethereum.net.p2p.HelloMessage)1 Frame (org.ethereum.net.rlpx.FrameCodec.Frame)1 InvalidCipherTextException (org.spongycastle.crypto.InvalidCipherTextException)1 ECPoint (org.spongycastle.math.ec.ECPoint)1