Repository navigation
Expand file tree
/
Copy pathTcpTest.java
More file actions
262 lines (236 loc) · 10.2 KB
/
Copy pathTcpTest.java
File metadata and controls
262 lines (236 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package org.tron.core.net;
import static org.tron.core.net.message.MessageTypes.P2P_DISCONNECT;
import static org.tron.core.net.message.MessageTypes.P2P_HELLO;
import static org.tron.protos.Protocol.ReasonCode.DUPLICATE_PEER;
import static org.tron.protos.Protocol.ReasonCode.FORKED;
import static org.tron.protos.Protocol.ReasonCode.INCOMPATIBLE_CHAIN;
import static org.tron.protos.Protocol.ReasonCode.INCOMPATIBLE_VERSION;
import com.google.common.cache.CacheBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Assert;
import org.tron.common.application.TronApplicationContext;
import org.tron.common.overlay.discover.node.Node;
import org.tron.common.overlay.message.DisconnectMessage;
import org.tron.common.overlay.message.HelloMessage;
import org.tron.common.overlay.message.Message;
import org.tron.common.overlay.message.P2pMessage;
import org.tron.common.overlay.message.P2pMessageFactory;
import org.tron.common.overlay.server.ChannelManager;
import org.tron.common.overlay.server.SyncPool;
import org.tron.common.utils.ReflectUtils;
import org.tron.core.capsule.BlockCapsule;
import org.tron.core.capsule.BlockCapsule.BlockId;
import org.tron.core.config.args.Args;
import org.tron.core.db.Manager;
import org.tron.core.net.message.BlockMessage;
import org.tron.core.net.peer.PeerConnection;
import org.tron.protos.Protocol.Block;
@Slf4j
public class TcpTest {
private ChannelManager channelManager;
private Manager manager;
private SyncPool pool;
private TronNetDelegate tronNetDelegate;
private int tryTimes = 10;
private int sleepTime = 1000;
private boolean finish = false;
Node node = Node.instanceOf("127.0.0.1:" + Args.getInstance().getNodeListenPort());
public TcpTest(TronApplicationContext context) {
channelManager = context.getBean(ChannelManager.class);
manager = context.getBean(Manager.class);
pool = context.getBean(SyncPool.class);
tronNetDelegate = context.getBean(TronNetDelegate.class);
}
private enum TestType {
normal, errorGenesisBlock, errorVersion, errorSolid, repeatConnect
}
private class HandshakeHandler extends ByteToMessageDecoder {
private P2pMessageFactory messageFactory = new P2pMessageFactory();
private TestType testType;
public HandshakeHandler(TestType testType) {
this.testType = testType;
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out)
throws Exception {
byte[] encoded = new byte[buffer.readableBytes()];
buffer.readBytes(encoded);
P2pMessage msg = messageFactory.create(encoded);
switch (testType) {
case normal:
Assert.assertEquals(msg.getType(), P2P_HELLO);
break;
case errorGenesisBlock:
Assert.assertEquals(msg.getType(), P2P_DISCONNECT);
Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), INCOMPATIBLE_CHAIN);
break;
case errorVersion:
Assert.assertEquals(msg.getType(), P2P_DISCONNECT);
Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), INCOMPATIBLE_VERSION);
break;
case errorSolid:
Assert.assertEquals(msg.getType(), P2P_DISCONNECT);
Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), FORKED);
break;
case repeatConnect:
Assert.assertEquals(msg.getType(), P2P_DISCONNECT);
Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), DUPLICATE_PEER);
break;
default:
break;
}
finish = true;
}
}
public void normalTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal));
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(),
manager.getGenesisBlockId(), manager.getSolidBlockId(), manager.getHeadBlockId());
sendMessage(channel, message);
validResultCloseConnect(channel);
}
public void errorGenesisBlockIdTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorGenesisBlock));
BlockId genesisBlockId = new BlockId();
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), genesisBlockId,
manager.getSolidBlockId(), manager.getHeadBlockId());
sendMessage(channel, message);
validResultCloseConnect(channel);
}
public void errorVersionTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorVersion));
Args.getInstance().setNodeP2pVersion(1);
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(),
manager.getGenesisBlockId(), manager.getSolidBlockId(), manager.getHeadBlockId());
Args.getInstance().setNodeP2pVersion(2);
sendMessage(channel, message);
validResultCloseConnect(channel);
}
public void errorSolidBlockIdTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorSolid));
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(),
manager.getGenesisBlockId(), new BlockId(), manager.getHeadBlockId());
sendMessage(channel, message);
validResultCloseConnect(channel);
}
public void repeatConnectTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal));
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(),
manager.getGenesisBlockId(), manager.getSolidBlockId(), manager.getHeadBlockId());
sendMessage(channel, message);
validResultUnCloseConnect();
Channel repeatChannel = BaseNet.connect(new HandshakeHandler(TestType.repeatConnect));
sendMessage(repeatChannel, message);
validResultCloseConnect(repeatChannel);
clearConnect(channel);
}
public void unHandshakeTest() throws InterruptedException {
List<PeerConnection> beforeActivePeers = ReflectUtils.getFieldValue(pool, "activePeers");
int beforeSize = beforeActivePeers.size();
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal));
BlockMessage message = new BlockMessage(new BlockCapsule(Block.getDefaultInstance()));
sendMessage(channel, message);
List<PeerConnection> afterActivePeers = ReflectUtils.getFieldValue(pool, "activePeers");
int afterSize = afterActivePeers.size();
Assert.assertEquals(beforeSize, afterSize);
clearConnect(channel);
}
public void errorMsgTest() throws InterruptedException {
Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal));
HelloMessage message = new HelloMessage(node, System.currentTimeMillis(),
manager.getGenesisBlockId(), manager.getSolidBlockId(), manager.getHeadBlockId());
sendMessage(channel, message);
validResultUnCloseConnect();
List<PeerConnection> beforeActivePeers = ReflectUtils.getFieldValue(pool, "activePeers");
int beforeSize = beforeActivePeers.size();
logger.info("beforeSize : {}", beforeSize);
channel.writeAndFlush(Unpooled.wrappedBuffer(ArrayUtils.add("nihao".getBytes(), 0, (byte) 1)))
.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
logger.info("send msg success");
} else {
logger.error("send msg fail", future.cause());
}
});
Thread.sleep(2000);
List<PeerConnection> afterActivePeers = ReflectUtils.getFieldValue(pool, "activePeers");
int afterSize = afterActivePeers.size();
logger.info("afterSize : {}", afterSize);
Assert.assertEquals(beforeSize, afterSize + 1);
clearConnect(channel);
}
private void sendMessage(Channel channel, Message message) {
channel.writeAndFlush(message.getSendData())
.addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
logger.info("send msg success");
} else {
logger.error("send msg fail", future.cause());
}
});
}
private void validResultCloseConnect(Channel channel) throws InterruptedException {
int trys = 0;
while (!finish && ++trys < tryTimes) {
Thread.sleep(sleepTime);
}
Assert.assertEquals(finish, true);
finish = false;
channel.close();
Thread.sleep(sleepTime);
Collection<PeerConnection> peerConnections = ReflectUtils
.invokeMethod(tronNetDelegate, "getActivePeer");
for (PeerConnection peer : peerConnections) {
peer.close();
}
ReflectUtils.setFieldValue(channelManager, "recentlyDisconnected",
CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterWrite(30, TimeUnit.SECONDS).recordStats().build());
}
private void validResultUnCloseConnect() throws InterruptedException {
int n = 0;
while (!finish && ++n < tryTimes) {
Thread.sleep(sleepTime);
}
Assert.assertEquals(finish, true);
finish = false;
}
private void clearConnect(Channel channel) throws InterruptedException {
channel.close();
Thread.sleep(sleepTime);
Collection<PeerConnection> peerConnections = ReflectUtils
.invokeMethod(tronNetDelegate, "getActivePeer");
for (PeerConnection peer : peerConnections) {
peer.close();
}
ReflectUtils.setFieldValue(channelManager, "recentlyDisconnected",
CacheBuilder.newBuilder().maximumSize(1000)
.expireAfterWrite(30, TimeUnit.SECONDS).recordStats().build());
}
public void test() throws InterruptedException {
logger.info("begin normal test ");
normalTest();
logger.info("begin errorGenesisBlockId test ");
errorGenesisBlockIdTest();
logger.info("begin errorVersion test ");
errorVersionTest();
logger.info("begin errorSolidBlockId test ");
errorSolidBlockIdTest();
logger.info("begin repeatConnect test");
repeatConnectTest();
logger.info("begin unHandshake test");
unHandshakeTest();
logger.info("begin errorMsg test");
errorMsgTest();
}
}