Skip to content

Commit

Permalink
feat(net):improve chain inventory generating logic (#5393)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwrct authored Aug 17, 2023
1 parent a9c4f43 commit 83151aa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ private boolean check(PeerConnection peer, SyncBlockChainMessage msg) throws P2p

private LinkedList<BlockId> getLostBlockIds(List<BlockId> blockIds) throws P2pException {

BlockId unForkId = getUnForkId(blockIds);
LinkedList<BlockId> ids = getBlockIds(unForkId.getNum());

if (ids.isEmpty() || !unForkId.equals(ids.peekFirst())) {
unForkId = getUnForkId(blockIds);
ids = getBlockIds(unForkId.getNum());
}

return ids;
}

private BlockId getUnForkId(List<BlockId> blockIds) throws P2pException {
BlockId unForkId = null;
for (int i = blockIds.size() - 1; i >= 0; i--) {
if (tronNetDelegate.containBlockInMainChain(blockIds.get(i))) {
Expand All @@ -99,13 +111,17 @@ private LinkedList<BlockId> getLostBlockIds(List<BlockId> blockIds) throws P2pEx
throw new P2pException(TypeEnum.SYNC_FAILED, "unForkId is null");
}

return unForkId;
}

private LinkedList<BlockId> getBlockIds(Long unForkNum) throws P2pException {
BlockId headID = tronNetDelegate.getHeadBlockId();
long headNum = headID.getNum();

long len = Math.min(headNum, unForkId.getNum() + NetConstants.SYNC_FETCH_BATCH_NUM);
long len = Math.min(headNum, unForkNum + NetConstants.SYNC_FETCH_BATCH_NUM);

LinkedList<BlockId> ids = new LinkedList<>();
for (long i = unForkId.getNum(); i <= len; i++) {
for (long i = unForkNum; i <= len; i++) {
if (i == headNum) {
ids.add(headID);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.ArrayList;
Expand Down Expand Up @@ -64,6 +65,21 @@ public void testProcessMessage() throws Exception {
method.setAccessible(true);
boolean f = (boolean)method.invoke(handler, peer, message);
Assert.assertTrue(!f);

Method method1 = handler.getClass().getDeclaredMethod(
"getLostBlockIds", List.class);
method1.setAccessible(true);
try {
method1.invoke(handler, blockIds);
} catch (InvocationTargetException e) {
Assert.assertEquals("unForkId is null", e.getTargetException().getMessage());
}

Method method2 = handler.getClass().getDeclaredMethod(
"getBlockIds", Long.class);
method2.setAccessible(true);
List list = (List) method2.invoke(handler, 0L);
Assert.assertEquals(1, list.size());
}

@After
Expand Down

0 comments on commit 83151aa

Please sign in to comment.