2020
2121import java .util .ArrayList ;
2222import java .util .Collections ;
23+ import java .util .HashMap ;
2324import java .util .List ;
25+ import java .util .Map ;
26+
2427import lombok .extern .slf4j .Slf4j ;
2528import org .tron .common .overlay .discover .node .Node ;
2629
@@ -29,7 +32,7 @@ public class NodeTable {
2932
3033 private final Node node ; // our node
3134 private transient NodeBucket [] buckets ;
32- private transient List < NodeEntry > nodes ;
35+ private transient Map < String , NodeEntry > nodes ;
3336
3437 public NodeTable (Node n ) {
3538 this .node = n ;
@@ -41,15 +44,19 @@ public Node getNode() {
4144 }
4245
4346 public final void initialize () {
44- nodes = new ArrayList <>();
47+ nodes = new HashMap <>();
4548 buckets = new NodeBucket [KademliaOptions .BINS ];
4649 for (int i = 0 ; i < KademliaOptions .BINS ; i ++) {
4750 buckets [i ] = new NodeBucket (i );
4851 }
4952 }
5053
5154 public synchronized Node addNode (Node n ) {
52- NodeEntry entry = getNodeEntry (n );
55+ if (n .getHost ().equals (node .getHost ())) {
56+ return null ;
57+ }
58+
59+ NodeEntry entry = nodes .get (n .getHost ());
5360 if (entry != null ) {
5461 entry .touch ();
5562 return null ;
@@ -60,24 +67,24 @@ public synchronized Node addNode(Node n) {
6067 if (lastSeen != null ) {
6168 return lastSeen .getNode ();
6269 }
63- nodes .add ( e );
70+ nodes .put ( n . getHost (), e );
6471 return null ;
6572 }
6673
6774 public synchronized void dropNode (Node n ) {
68- NodeEntry entry = getNodeEntry ( n );
75+ NodeEntry entry = nodes . get ( n . getHost () );
6976 if (entry != null ) {
70- nodes .remove (entry );
77+ nodes .remove (n . getHost () );
7178 buckets [getBucketId (entry )].dropNode (entry );
7279 }
7380 }
7481
7582 public synchronized boolean contains (Node n ) {
76- return getNodeEntry ( n ) != null ;
83+ return nodes . containsKey ( n . getHost ()) ;
7784 }
7885
7986 public synchronized void touchNode (Node n ) {
80- NodeEntry entry = getNodeEntry ( n );
87+ NodeEntry entry = nodes . get ( n . getHost () );
8188 if (entry != null ) {
8289 entry .touch ();
8390 }
@@ -103,9 +110,7 @@ public synchronized int getNodesCount() {
103110 }
104111
105112 public synchronized List <NodeEntry > getAllNodes () {
106- List <NodeEntry > list = new ArrayList <>(nodes );
107- list .remove (new NodeEntry (node .getId (), node ));
108- return list ;
113+ return new ArrayList <>(nodes .values ());
109114 }
110115
111116 public synchronized List <Node > getClosestNodes (byte [] targetId ) {
@@ -123,14 +128,4 @@ public synchronized List<Node> getClosestNodes(byte[] targetId) {
123128 return closestNodes ;
124129 }
125130
126- private NodeEntry getNodeEntry (Node n ) {
127- NodeEntry entry = null ;
128- for (NodeEntry e : nodes ) {
129- if (e .getNode ().getHost ().equals (n .getHost ())) {
130- entry = e ;
131- break ;
132- }
133- }
134- return entry ;
135- }
136131}
0 commit comments