1717 */
1818package org .tron .common .overlay .message ;
1919
20- import static java .lang .Math .min ;
21- import static org .ethereum .net .rlpx .FrameCodec .Frame ;
22-
23- import com .google .common .io .ByteStreams ;
2420import io .netty .buffer .ByteBuf ;
2521import io .netty .channel .ChannelHandlerContext ;
2622import io .netty .handler .codec .MessageToMessageCodec ;
2723import java .io .IOException ;
28- import java .util .ArrayList ;
29- import java .util .Arrays ;
30- import java .util .Collections ;
3124import java .util .List ;
32- import java .util .Map ;
33- import java .util .concurrent .atomic .AtomicInteger ;
34- import org .apache .commons .collections4 .map .LRUMap ;
35- import org .apache .commons .lang3 .tuple .Pair ;
36- import org .ethereum .config .SystemProperties ;
37- import org .ethereum .listener .EthereumListener ;
38- import org .ethereum .net .client .Capability ;
39- import org .ethereum .net .eth .EthVersion ;
40- import org .ethereum .net .eth .message .EthMessageCodes ;
41- import org .ethereum .net .shh .ShhMessageCodes ;
42- import org .ethereum .net .swarm .bzz .BzzMessageCodes ;
4325import org .slf4j .Logger ;
4426import org .slf4j .LoggerFactory ;
45- import org .spongycastle .util .encoders .Hex ;
4627import org .springframework .beans .factory .annotation .Autowired ;
4728import org .springframework .context .annotation .Scope ;
4829import org .springframework .stereotype .Component ;
49- import org .springframework . validation . MessageCodesResolver ;
30+ import org .tron . common . overlay . SystemProperties ;
5031import org .tron .common .overlay .server .Channel ;
5132
5233
@@ -60,135 +41,31 @@ public class MessageCodec extends MessageToMessageCodec<ByteBuf, Message> {
6041 private static final Logger loggerWire = LoggerFactory .getLogger ("wire" );
6142 private static final Logger loggerNet = LoggerFactory .getLogger ("net" );
6243
63- public static final int NO_FRAMING = Integer .MAX_VALUE >> 1 ;
64-
65- private int maxFramePayloadSize = NO_FRAMING ;
66-
6744 private Channel channel ;
68- private MessageCodesResolver messageCodesResolver ;
69-
70- private MessageFactory p2pMessageFactory ;
71- private MessageFactory ethMessageFactory ;
72- private MessageFactory shhMessageFactory ;
73- private MessageFactory bzzMessageFactory ;
74- private EthVersion ethVersion ;
45+ private P2pMessageFactory p2pMessageFactory ;
46+ //private tronMessageFactory;
7547
7648 @ Autowired
77- EthereumListener ethereumListener ;
49+ // EthereumListener ethereumListener;
7850
7951 private SystemProperties config ;
80-
8152 private boolean supportChunkedFrames = false ;
8253
83- Map <Integer , Pair <? extends List <Frame >, AtomicInteger >> incompleteFrames = new LRUMap <>(16 );
84- // LRU avoids OOM on invalid peers
85- AtomicInteger contextIdCounter = new AtomicInteger (1 );
8654
8755 public MessageCodec () {
8856 }
8957
9058 @ Autowired
9159 private MessageCodec (final SystemProperties config ) {
9260 this .config = config ;
93- setMaxFramePayloadSize (config .rlpxMaxFrameSize ());
94- }
95-
96- @ Override
97- protected void decode (ChannelHandlerContext ctx , Frame frame , List <Object > out ) throws Exception {
98- Frame completeFrame = null ;
99- if (frame .isChunked ()) {
100- if (!supportChunkedFrames && frame .totalFrameSize > 0 ) {
101- throw new RuntimeException ("Faming is not supported in this configuration." );
102- }
103-
104- Pair <? extends List <Frame >, AtomicInteger > frameParts = incompleteFrames .get (frame .contextId );
105- if (frameParts == null ) {
106- if (frame .totalFrameSize < 0 ) {
107- // loggerNet.warn("No initial frame received for context-id: " + frame.contextId + ". Discarding this frame as invalid.");
108- // TODO: refactor this logic (Cpp sends non-chunked frames with context-id)
109- Message message = decodeMessage (ctx , Collections .singletonList (frame ));
110- if (message == null ) return ;
111- out .add (message );
112- return ;
113- } else {
114- frameParts = Pair .of (new ArrayList <Frame >(), new AtomicInteger (0 ));
115- incompleteFrames .put (frame .contextId , frameParts );
116- }
117- } else {
118- if (frame .totalFrameSize >= 0 ) {
119- loggerNet .warn ("Non-initial chunked frame shouldn't contain totalFrameSize field (context-id: " + frame .contextId + ", totalFrameSize: " + frame .totalFrameSize + "). Discarding this frame and all previous." );
120- incompleteFrames .remove (frame .contextId );
121- return ;
122- }
123- }
124-
125- frameParts .getLeft ().add (frame );
126- int curSize = frameParts .getRight ().addAndGet (frame .size );
127-
128- if (loggerWire .isDebugEnabled ())
129- loggerWire .debug ("Recv: Chunked (" + curSize + " of " + frameParts .getLeft ().get (0 ).totalFrameSize + ") [size: " + frame .getSize () + "]" );
130-
131- if (curSize > frameParts .getLeft ().get (0 ).totalFrameSize ) {
132- loggerNet .warn ("The total frame chunks size (" + curSize + ") is greater than expected (" + frameParts .getLeft ().get (0 ).totalFrameSize + "). Discarding the frame." );
133- incompleteFrames .remove (frame .contextId );
134- return ;
135- }
136- if (curSize == frameParts .getLeft ().get (0 ).totalFrameSize ) {
137- Message message = decodeMessage (ctx , frameParts .getLeft ());
138- incompleteFrames .remove (frame .contextId );
139- out .add (message );
140- }
141- } else {
142- Message message = decodeMessage (ctx , Collections .singletonList (frame ));
143- out .add (message );
144- }
145- }
146-
147- private Message decodeMessage (ChannelHandlerContext ctx , List <Frame > frames ) throws IOException {
148- long frameType = frames .get (0 ).getType ();
149-
150- byte [] payload = new byte [frames .size () == 1 ? frames .get (0 ).getSize () : frames .get (0 ).totalFrameSize ];
151- int pos = 0 ;
152- for (Frame frame : frames ) {
153- pos += ByteStreams .read (frame .getStream (), payload , pos , frame .getSize ());
154- }
155-
156- if (loggerWire .isDebugEnabled ())
157- loggerWire .debug ("Recv: Encoded: {} [{}]" , frameType , Hex .toHexString (payload ));
158-
159- Message msg ;
160- try {
161- msg = createMessage ((byte ) frameType , payload );
162- } catch (Exception ex ) {
163- loggerNet .debug ("Incorrectly encoded message from: \t {}, dropping peer" , channel );
164- channel .disconnect (ReasonCode .BAD_PROTOCOL );
165- return null ;
166- }
167-
168- if (loggerNet .isDebugEnabled ())
169- loggerNet .debug ("From: {} Recv: {}" , channel , msg .toString ());
170-
171- ethereumListener .onRecvMessage (channel , msg );
172-
173- channel .getNodeStatistics ().rlpxInMessages .add ();
174- return msg ;
61+ //setMaxFramePayloadSize(config.rlpxMaxFrameSize());
17562 }
17663
17764 private Message decodeMessage (ChannelHandlerContext ctx , ByteBuf buffer ) throws IOException {
178- long frameType = frames .get (0 ).getType ();
179-
180- byte [] payload = new byte [frames .size () == 1 ? frames .get (0 ).getSize () : frames .get (0 ).totalFrameSize ];
181- int pos = 0 ;
182- for (Frame frame : frames ) {
183- pos += ByteStreams .read (frame .getStream (), payload , pos , frame .getSize ());
184- }
185-
186- if (loggerWire .isDebugEnabled ())
187- loggerWire .debug ("Recv: Encoded: {} [{}]" , frameType , Hex .toHexString (payload ));
18865
18966 Message msg ;
19067 try {
191- msg = createMessage (( byte ) frameType , payload );
68+ msg = createMessage (buffer . array () );
19269 } catch (Exception ex ) {
19370 loggerNet .debug ("Incorrectly encoded message from: \t {}, dropping peer" , channel );
19471 channel .disconnect (ReasonCode .BAD_PROTOCOL );
@@ -198,7 +75,8 @@ private Message decodeMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws
19875 if (loggerNet .isDebugEnabled ())
19976 loggerNet .debug ("From: {} Recv: {}" , channel , msg .toString ());
20077
201- ethereumListener .onRecvMessage (channel , msg );
78+ //TODO: let peer know.
79+ //ethereumListener.onRecvMessage(channel, msg);
20280
20381 channel .getNodeStatistics ().rlpxInMessages .add ();
20482 return msg ;
@@ -207,117 +85,31 @@ private Message decodeMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws
20785 @ Override
20886 protected void encode (ChannelHandlerContext ctx , Message msg , List <Object > out ) throws Exception {
20987 String output = String .format ("To: \t %s \t Send: \t %s" , ctx .channel ().remoteAddress (), msg );
210- ethereumListener .trace (output );
21188
21289 if (loggerNet .isDebugEnabled ())
21390 loggerNet .debug ("To: {} Send: {}" , channel , msg );
21491
215- byte [] encoded = msg .getEncoded ();
216-
217- if (loggerWire .isDebugEnabled ())
218- loggerWire .debug ("Send: Encoded: {} [{}]" , getCode (msg .getCommand ()), Hex .toHexString (encoded ));
219-
220- List <Frame > frames = splitMessageToFrames (msg );
221-
222- out .addAll (frames );
92+ //TODO: get data to send.
93+ byte [] encoded = msg .getData ();
94+ out .add (encoded );
22395
22496 channel .getNodeStatistics ().rlpxOutMessages .add ();
22597 }
22698
22799 @ Override
228100 protected void decode (ChannelHandlerContext ctx , ByteBuf msg , List <Object > out )
229101 throws Exception {
230-
231- Message message = decodeMessage (ctx , Collections .singletonList (frame ));
102+ Message message = decodeMessage (ctx , msg );
232103 out .add (message );
233-
234- }
235-
236- private List <Frame > splitMessageToFrames (Message msg ) {
237- byte code = getCode (msg .getCommand ());
238- List <Frame > ret = new ArrayList <>();
239- byte [] bytes = msg .getEncoded ();
240- int curPos = 0 ;
241- while (curPos < bytes .length ) {
242- int newPos = min (curPos + maxFramePayloadSize , bytes .length );
243- byte [] frameBytes = curPos == 0 && newPos == bytes .length ? bytes :
244- Arrays .copyOfRange (bytes , curPos , newPos );
245- ret .add (new Frame (code , frameBytes ));
246- curPos = newPos ;
247- }
248-
249- if (ret .size () > 1 ) {
250- // frame has been split
251- int contextId = contextIdCounter .getAndIncrement ();
252- ret .get (0 ).totalFrameSize = bytes .length ;
253- loggerWire .debug ("Message (size " + bytes .length + ") split to " + ret .size () + " frames. Context-id: " + contextId );
254- for (Frame frame : ret ) {
255- frame .contextId = contextId ;
256- }
257- }
258- return ret ;
259- }
260-
261- public void setSupportChunkedFrames (boolean supportChunkedFrames ) {
262- this .supportChunkedFrames = supportChunkedFrames ;
263- if (!supportChunkedFrames ) {
264- setMaxFramePayloadSize (NO_FRAMING );
265- }
266- }
267-
268- /* TODO: this dirty hack is here cause we need to use message
269- TODO: adaptive id on high message abstraction level,
270- TODO: need a solution here*/
271- private byte getCode (Enum msgCommand ){
272- byte code = 0 ;
273-
274- if (msgCommand instanceof P2pMessageCodes ){
275- code = messageCodesResolver .withP2pOffset (((P2pMessageCodes ) msgCommand ).asByte ());
276- }
277-
278- if (msgCommand instanceof EthMessageCodes ){
279- code = messageCodesResolver .withEthOffset (((EthMessageCodes ) msgCommand ).asByte ());
280- }
281-
282- if (msgCommand instanceof ShhMessageCodes ){
283- code = messageCodesResolver .withShhOffset (((ShhMessageCodes )msgCommand ).asByte ());
284- }
285-
286- if (msgCommand instanceof BzzMessageCodes ){
287- code = messageCodesResolver .withBzzOffset (((BzzMessageCodes ) msgCommand ).asByte ());
288- }
289-
290- return code ;
291104 }
292105
293- private Message createMessage (byte code , byte [] payload ) {
294-
295- byte resolved = messageCodesResolver .resolveP2p (code );
296- if (p2pMessageFactory != null && P2pMessageCodes .inRange (resolved )) {
297- return p2pMessageFactory .create (resolved , payload );
298- }
299-
300- resolved = messageCodesResolver .resolveEth (code );
301- if (ethMessageFactory != null && EthMessageCodes .inRange (resolved , ethVersion )) {
302- return ethMessageFactory .create (resolved , payload );
303- }
304-
305- throw new IllegalArgumentException ("No such message: " + code + " [" + Hex .toHexString (payload ) + "]" );
306- }
106+ private Message createMessage (byte [] data ) {
107+ //TODO:add tron message factory here
108+ return p2pMessageFactory .create (data );
109+ }
307110
308111 public void setChannel (Channel channel ){
309112 this .channel = channel ;
310113 }
311114
312- public void setMaxFramePayloadSize (int maxFramePayloadSize ) {
313- this .maxFramePayloadSize = maxFramePayloadSize ;
314- }
315-
316- public void initMessageCodes (List <Capability > caps ) {
317- this .messageCodesResolver = new MessageCodesResolver (caps );
318- }
319-
320- public void setP2pMessageFactory (MessageFactory p2pMessageFactory ) {
321- this .p2pMessageFactory = p2pMessageFactory ;
322- }
323115}
0 commit comments