Guest User

Untitled

a guest
Apr 25th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. package kademlia
  2.  
  3. import (
  4. "container/list";
  5. "container/vector";
  6. "exp/iterable";
  7. "sort";
  8. )
  9.  
  10. const BucketSize = 20;
  11.  
  12. type RoutingTable struct {
  13. node Contact;
  14. buckets [IdLength*8]*list.List;
  15. }
  16.  
  17. type ContactRecord struct {
  18. node *Contact;
  19. sortKey NodeID;
  20. }
  21.  
  22. func (rec *ContactRecord) Less(other interface{}) bool {
  23. return rec.sortKey.Less(other.(*ContactRecord).sortKey);
  24. }
  25.  
  26. func NewRoutingTable(node *Contact) (ret *RoutingTable) {
  27. ret = new(RoutingTable);
  28. for i := 0; i < IdLength * 8; i++ {
  29. ret.buckets[i] = list.New();
  30. }
  31. ret.node = *node;
  32. return;
  33. }
  34.  
  35. func (table *RoutingTable) Update(contact *Contact) {
  36. prefix_length := contact.id.Xor(table.node.id).PrefixLen();
  37. bucket := table.buckets[prefix_length];
  38. element := iterable.Find(bucket, func(x interface{}) bool {
  39. return x.(*Contact).id.Equals(table.node.id);
  40. });
  41. if element == nil {
  42. if bucket.Len() <= BucketSize {
  43. bucket.PushFront(contact);
  44. }
  45. // TODO: Handle insertion when the list is full by evicting old elements if
  46. // they don't respond to a ping.
  47. } else {
  48. bucket.MoveToFront(element.(*list.Element));
  49. }
  50. }
  51.  
  52. func copyToVector(start, end *list.Element, vec *vector.Vector, target NodeID) {
  53. for elt := start; elt != end; elt = elt.Next() {
  54. contact := elt.Value.(*Contact);
  55. vec.Push(&ContactRecord{contact, contact.id.Xor(target)});
  56. }
  57. }
  58.  
  59. func (table *RoutingTable) FindClosest(target NodeID, count int) (ret *vector.Vector) {
  60. ret = new(vector.Vector).Resize(0, count);
  61.  
  62. bucket_num := target.Xor(table.node.id).PrefixLen();
  63. bucket := table.buckets[bucket_num];
  64. copyToVector(bucket.Front(), nil, ret, target);
  65.  
  66. for i := 1; (bucket_num-i >= 0 || bucket_num+i < IdLength*8) && ret.Len() < count; i++ {
  67. if bucket_num - i >= 0 {
  68. bucket = table.buckets[bucket_num - i];
  69. copyToVector(bucket.Front(), nil, ret, target);
  70. }
  71. if bucket_num + i < IdLength * 8 {
  72. bucket = table.buckets[bucket_num + i];
  73. copyToVector(bucket.Front(), nil, ret, target);
  74. }
  75. }
  76.  
  77. sort.Sort(ret);
  78. if ret.Len() > count {
  79. ret.Cut(count, ret.Len());
  80. }
  81. return;
  82. }
Add Comment
Please, Sign In to add comment