remove protocol violation
[oweals/gnunet.git] / src / dht / gnunet-service-xdht_neighbours.c
index 70aa47108bd3dfdb31984e02928d37a1a7004743..c2927f1002045e07e2c5b57372028e37506bca19 100644 (file)
 #include "gnunet_hello_lib.h"
 #include "gnunet_constants.h"
 #include "gnunet_protocols.h"
-#include "gnunet_nse_service.h"
 #include "gnunet_ats_service.h"
 #include "gnunet_core_service.h"
 #include "gnunet_datacache_lib.h"
 #include "gnunet_transport_service.h"
-#include "gnunet_hello_lib.h"
 #include "gnunet_dht_service.h"
 #include "gnunet_statistics_service.h"
 #include "gnunet-service-xdht.h"
 #include "gnunet-service-xdht_clients.h"
 #include "gnunet-service-xdht_datacache.h"
-#include "gnunet-service-xdht_hello.h"
 #include "gnunet-service-xdht_neighbours.h"
-#include "gnunet-service-xdht_nse.h"
 #include "gnunet-service-xdht_routing.h"
 #include <fenv.h>
 #include "dht.h"
 
-/* TODO:
- * 1. when should we use const struct and replace wherever needed. 
- * 2. use assert for each function where you need to check the return value.
- 1. Use a global array of all known peers in find_successor, Only when 
- a new peer is added in finger or friend peer map, then re calculate
- the array. Or else use the old one.
- 2. Should we be using const in all the handle for the message we received 
- * and then copy the fields and make changes to the fields instead of sending
- * them as they come.
- * 3. Everywhere you are storing yourself as the first element in the trail.
- * It is obviously taking too much space. Try to remove it and think of something
- * better.
- 4. Choose the correct interval to send finger and verify message.
- 5. Do we need expiration time for trail setup and all other messages? TTL
- 6. In case of trail setup after TTL, we should again send the request but 
- * through a different route. How do we remeber each time which friend we
- * chose last time for the trail setup. We will need a data structure where we
- * add entry in finger table add and when setup is done remove it.
- * 7. I have not added any authentication on messages exachanged between peers.
- * Only when basic put/get is correct I will add it. */
-
 /**
  * Maximum possible fingers of a peer.
  */
-#define MAX_FINGERS 64
+#define MAX_FINGERS 65
 
 /**
  * Maximum allowed number of pending messages per friend peer.
 #define MAXIMUM_PENDING_PER_FRIEND 64
 
 /**
- * How long at least to wait before sending another find finger trail request,
- * at most we wait twice this long.
+ * How long to wait before sending another find finger trail request
  */
 #define DHT_FIND_FINGER_TRAIL_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
 
 /**
- * How long at most to wait for transmission of a GET request to another peer?
+ * How long at most to wait for transmission of a request to another peer?
+ */
+#define GET_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
+
+/**
+ * How long will I remain congested?
+ */
+#define CONGESTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
+
+/**
+ * Maximum number of trails stored per finger.
+ */
+#define MAXIMUM_TRAILS_PER_FINGER 2
+
+/**
+ * Used to distinguish put/get request use of find_successor() from others
+ */
+#define PUT_GET_REQUEST 65
+
+/**
+ * Maximum number of trails that can go through a friend.
+ */
+#define TRAIL_THROUGH_FRIEND_THRESHOLD 64
+
+/**
+ * Finger map index for predecessor entry in finger peermap.
  */
-#define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
+#define PREDECESSOR_FINGER_ID 64
 
 /**
  * Maximum number of trails allowed to go through a friend.
  */
-#define LINK_THRESHOLD 64
+#define TRAILS_THROUGH_FRIEND_THRESHOLD 64
 
+/**
+ * Wrap around in peer identity circle. 
+ */
+#define PEER_IDENTITES_WRAP_AROUND pow(2, 256) - 1
 
 GNUNET_NETWORK_STRUCT_BEGIN
-  
+
 /**
- * P2P PUT message
+ * P2P Trail setup message
  */
-struct PeerPutMessage
+struct PeerTrailSetupMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP
    */
   struct GNUNET_MessageHeader header;
 
-  /**
-   * Processing options
-   */
-  uint32_t options GNUNET_PACKED;
+  /* Bitmask of options, 1 = IS_PREDECESSOR */
+  // int32_t options;
 
   /**
-   * Content type.
+   * Peer closest to this value will be our finger.
    */
-  uint32_t block_type GNUNET_PACKED;
+  uint64_t ultimate_destination_finger;
 
   /**
-   * Hop count
+   * Source peer which wants to setup the trail to one of its finger.
    */
-  uint32_t hop_count GNUNET_PACKED;
+  struct GNUNET_PeerIdentity source_peer;
 
   /**
-   * Replication level for this message
+   * Peer to which this packet is forwarded.
    */
-  uint32_t desired_replication_level GNUNET_PACKED;
+  struct GNUNET_PeerIdentity next_destination; // rename "best_known_dest"
 
   /**
-   * Length of the PUT path that follows (if tracked).
-   */
-  uint32_t put_path_length GNUNET_PACKED;
-  
-  /** 
-   * Current destination to which this message is forwarded.
+   * Index into finger peer map, in Network Byte Order.
    */
-  struct GNUNET_PeerIdentity current_destination;
-  
+  uint32_t finger_map_index; // remove this, include ultimate_destination_finger in response, calculate index from it
+
   /**
-   * Peer whose finger is current_destination. 
+   * Number of entries in trail_list, in Network Byte Order.
    */
-  struct GNUNET_PeerIdentity current_source;
-  
+  uint32_t trail_length GNUNET_PACKED; // remove this, calculte length from message size
+
   /**
-   * When does the content expire?
+   * Trail id of any intermediate trail we may encounter while doing trail setup.
    */
-  struct GNUNET_TIME_AbsoluteNBO expiration_time;
-  
+  struct GNUNET_HashCode intermediate_trail_id;
+
   /**
-   * The key to store the value under.
+   * Trail id for trail which we are trying to setup.
    */
-  struct GNUNET_HashCode key GNUNET_PACKED;
-
-  /* put path (if tracked) */
+  struct GNUNET_HashCode new_trail_id; // rename to "trail_id"
 
-  /* Payload */
+  /* Trail formed in the process. */
+  /* GNUNET_PeerIdentity trail_list[] */
 };
 
-
 /**
* P2P Result message
 * P2P Trail Setup Result message
  */
-struct PeerGetResultMessage
+struct PeerTrailSetupResultMessage
 {
+
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT
    */
   struct GNUNET_MessageHeader header;
 
   /**
-   * The type for the data.
-   */
-  uint32_t type GNUNET_PACKED;
-  
-  /**
-   * Peer which will receive the get result message. 
+   * Finger to which we have found the path.
    */
-  struct GNUNET_PeerIdentity source_peer;
+  struct GNUNET_PeerIdentity finger_identity;
 
   /**
-   * Number of peers recorded in the outgoing path from source to the
-   * stored location of this message.
+   * Peer which was looking for the trail to finger.
    */
-  uint32_t put_path_length GNUNET_PACKED;
-  
+  struct GNUNET_PeerIdentity destination_peer; // querying_peer
+
   /**
-   * Length of the GET path that follows (if tracked).
+   * Index into finger peer map in NBO.
    */
-  uint32_t get_path_length GNUNET_PACKED;
+  uint32_t finger_map_index; // flag/option with IS_PREDECESSOR
 
   /**
-   * When does the content expire?
+   * Number of entries in trail list in NBO.
    */
-  struct GNUNET_TIME_Absolute expiration_time;
+  uint32_t trail_length GNUNET_PACKED; // remove, calculate
 
   /**
-   * The key of the corresponding GET request.
+   * Identifier of the trail.
    */
-  struct GNUNET_HashCode key;
-  /* put path (if tracked) */
-
-  /* get path (if tracked) */
-
-  /* Payload */
+  struct GNUNET_HashCode trail_id;
 
+  /* Trail from "destination_peer" to finger_identity, NOT including both */
+  /* struct GNUNET_PeerIdentity trail[] */
 };
 
-
 /**
- * P2P GET message
+ * P2P Verify Successor Message.
  */
-struct PeerGetMessage
+struct PeerVerifySuccessorMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR
    */
   struct GNUNET_MessageHeader header;
-  
-  /**
-   * Processing options
-   */
-  uint32_t options GNUNET_PACKED;
 
   /**
-   * Desired content type.
-   */
-  uint32_t block_type GNUNET_PACKED;
-  
-  /**
-   * Hop count
-   */
-  uint32_t hop_count GNUNET_PACKED;
-  /**
-   * Desired replication level for this request.
-   */
-  uint32_t desired_replication_level GNUNET_PACKED;
-  
-  /**
-   * Total number of peers in get path. 
+   * Source peer which wants to verify its successor.
    */
-  unsigned int get_path_length;
-  
+  struct GNUNET_PeerIdentity source_peer;
+
   /**
-   * Peer which is an intermediate destination. 
+   * My current successor.
    */
-  struct GNUNET_PeerIdentity current_destination;
-  
+  struct GNUNET_PeerIdentity successor;
+
   /**
-   * Source for which current_destination is the finger. 
+   * Identifier of trail to reach from source_peer to successor.
    */
-  struct GNUNET_PeerIdentity current_source;
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * The key we are looking for.
+   * Total number of peers to reach from source to successor.
    */
-  struct GNUNET_HashCode key;
-  
-  /* Get path. */
+  unsigned int trail_length;
 
+  /* Trail. */
 };
 
-
 /**
- * FIXME: Check the alignment in all the struct  
- * P2P Trail setup message
+ * P2P Verify Successor Result Message
  */
-struct PeerTrailSetupMessage
+struct PeerVerifySuccessorResultMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Successor of this finger value will be our finger peer.
+   * Destination peer which sent the request to verify its successor.
    */
-  uint64_t destination_finger;
+  struct GNUNET_PeerIdentity destination_peer;
 
   /**
-   * Source peer which wants to setup the trail to one of its finger. 
+   * Successor to which PeerVerifySuccessorMessage was sent.
    */
-  struct GNUNET_PeerIdentity source_peer;
-  
+  struct GNUNET_PeerIdentity source_successor;
+
   /**
-   * Peer to which this packet is forwarded.
+   * source_successor's predecessor
    */
-  struct GNUNET_PeerIdentity current_destination;
-  
+  struct GNUNET_PeerIdentity my_predecessor;
+
   /**
-   * In case the packet is forwarded to an intermediate finger, then 
-   * current_source contains the peer id whose finger is the intermediate
-   * finger. In case the packet is forwarded to a friend, then it is NULL.
+   * Trail identifier of trail from my_predecessor to source_successor.
    */
-  struct GNUNET_PeerIdentity current_source;
-  
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * Index into finger peer map, in NBO. 
+   * Direction in which we are looking at the trail.
    */
-  uint32_t finger_map_index;
-  
+  enum GDS_ROUTING_trail_direction trail_direction;
+
   /**
-   * Number of entries in trail list, in NBO.
+   * Total number of peers in trail from source_successor to my_predecessor
+   * if my_predecessor is not same as destination_peer.
    */
-  uint32_t trail_length GNUNET_PACKED;
-  
-};
+  uint32_t trail_length;
 
+  /* Trail from source_successor to my_predecessor where
+   * my_predecessor != destination_peer*/
+};
 
 /**
- * P2P Trail Setup Result message
+ * P2P Notify New Successor Message.
  */
-struct PeerTrailSetupResultMessage
+struct PeerNotifyNewSuccessorMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Finger to which we have found the path. 
+   * Source peer which wants to notify its new successor.
    */
-  struct GNUNET_PeerIdentity finger_identity;
+  struct GNUNET_PeerIdentity source_peer;
 
   /**
-   * Peer which was looking for the trail to finger. 
+   * New successor identity.
    */
   struct GNUNET_PeerIdentity destination_peer;
-  
+
   /**
-   * Index into finger peer map
+   * Total number of peers in trail from source_peer to destination_peer
    */
-  uint32_t finger_map_index;
-  
+  unsigned int trail_length;
+
   /**
-   * Number of entries in trail list.
+   * Unique identifier of the trail.
    */
-  uint32_t trail_length GNUNET_PACKED;
-  
+  struct GNUNET_HashCode trail_id;
+
+  /* Trail. */
 };
 
 /**
- *
+ * P2P Trail Compression Message.
  */
-struct PeerTrailRejectionMessage
+struct PeerTrailCompressionMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to set up the trail. 
+   * Source peer of this trail.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
-  /**
-   * Finger identity value. 
-   */
-  uint64_t finger_identity;
-  
+
   /**
-   * Peer which sent trail rejection message. 
+   * Destination of this trail.
    */
-  struct GNUNET_PeerIdentity congested_peer;
-  
+  struct GNUNET_PeerIdentity destination_peer;
+
   /**
-   * Index in finger peer map of source peer.
+   * Trail from source_peer to destination_peer compressed such that
+   * new_first_friend is the first hop in the trail from source to
+   * destination.
    */
-  unsigned int finger_map_index;
-  
+  struct GNUNET_PeerIdentity new_first_friend;
+
   /**
-   * Total number of peers in the trail.
+   * Unique identifier of trail.
    */
-  unsigned int trail_length;
-  
-  /* trail_list */
+  struct GNUNET_HashCode trail_id;
 };
 
 
 /**
- * P2P Verify Successor message. 
+ * P2P Trail Tear Down message.
  */
-struct PeerVerifySuccessorMessage
+struct PeerTrailTearDownMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to verify its successor. 
+   * Source peer of the trail.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
+
   /**
-   * My current successor.
+   * Destination peer of the trail.
    */
-  struct GNUNET_PeerIdentity successor;
-  
+  struct GNUNET_PeerIdentity destination_peer;
+
   /**
-   * Total number of peers in trail to current successor.
+   * Unique identifier of the trail.
    */
-  unsigned int trail_length;
+  struct GNUNET_HashCode TRAIL_ID;
+
+  /**
+   * Direction of trail.
+   */
+  enum GDS_ROUTING_trail_direction trail_direction;
 };
 
 
 /**
- * P2P Verify Successor Result message. 
+ * P2P Trail Rejection Message.
  */
-struct PeerVerifySuccessorResultMessage
+struct PeerTrailRejectionMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Destination peer which sent the request to verify its successor. 
+   * Source peer which wants to set up the trail.
    */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+  struct GNUNET_PeerIdentity source_peer;
+
   /**
-   * Successor to which PeerVerifySuccessorMessage was sent.
+   * Peer which sent trail rejection message.
    */
-  struct GNUNET_PeerIdentity source_successor;
-  
+  struct GNUNET_PeerIdentity congested_peer;
+
   /**
-   * source_successor's predecessor
+   * Peer identity which will be successor to this value will be finger of
+   * source_peer.
    */
-  struct GNUNET_PeerIdentity my_predecessor;
-  
+  uint64_t ultimate_destination_finger_identity_value;
+
+  /**
+   * Index in finger peer map of source peer.
+   */
+  uint32_t finger_map_index;
+
+  /**
+   * Total number of peers in the trail.
+   */
+  uint32_t trail_length;
+
+  /**
+   * Identifier for the trail source peer is trying to setup.
+   */
+  struct GNUNET_HashCode trail_id;
   /**
-   * Total number of peers in trail.
-   * If source_successor is not destination peer, then trail is from destination_peer
-   * to my_predecessor.
-   * If source_successor is destination peer, then trail is from destination_peer
-   * to source_successor.
+   * Relative time for which congested_peer will remain congested.
    */
-  unsigned int trail_length; 
+  struct GNUNET_TIME_Relative congestion_time;
+
+  /* Trail_list from source_peer to peer which sent the message for trail setup
+   * to congested peer.*/
 };
 
 /**
- * P2P Notify New Successor message.
+ * P2P Add Trail Message.
  */
-struct PeerNotifyNewSuccessorMessage
+struct PeerAddTrailMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to notify its new successor. 
+   * Source peer of the routing trail.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
+
   /**
-   * New successor identity.
+   * Destination peer of the routing trail.
    */
   struct GNUNET_PeerIdentity destination_peer;
-  
+
   /**
-   * Number of peers in trail from source_peer to new successor.
+   * Total number of peers from source peer to destination peer.
    */
   unsigned int trail_length;
-};
 
+  /**
+   * Unique identifier of the trail.
+   */
+  struct GNUNET_HashCode trail_id;
+
+  /* Trail from source peer to destination peer. */
+};
 
 GNUNET_NETWORK_STRUCT_END
 
-
 /**
  * Linked list of messages to send to a particular other peer.
  */
@@ -495,15 +470,15 @@ struct P2PPendingMessage
   struct P2PPendingMessage *prev;
 
   /**
-   * When does this message time out?
-   */
-  struct GNUNET_TIME_Absolute timeout;
-
-   /**
    * Message importance level.  FIXME: used? useful?
    */
   unsigned int importance;
 
+  /**
+   * When does this message time out?
+   */
+  struct GNUNET_TIME_Absolute timeout;
+
   /**
    * Actual message to be sent, allocated at the end of the struct:
    * // msg = (cast) &pm[1];
@@ -515,48 +490,30 @@ struct P2PPendingMessage
 
 
 /**
- * Linked List of peers which are part of trail to reach a particular Finger.
- */
-struct TrailPeerList
-{
-   /**
-    * Pointer to next item in the list
-    */
-   struct TrailPeerList *next;
-
-   /**
-    * Pointer to previous item in the list
-    */
-   struct TrailPeerList *prev;
-   
-   /**
-    * An element in this trail list
-    */
-   struct GNUNET_PeerIdentity peer;
-  
-};
-
-
-/** 
  *  Entry in friend_peermap.
  */
 struct FriendInfo
 {
   /**
-   * Friend Identity 
+   * Friend Identity
    */
   struct GNUNET_PeerIdentity id;
 
   /**
-   * Number of trail of which this friend is the first hop.
+   * Number of trails for which this friend is the first hop.
    */
-  unsigned int trail_links;
-  
+  unsigned int trails_count;
+
   /**
    * Count of outstanding messages for this friend.
    */
   unsigned int pending_count;
-  
+
+  /**
+   * In case not 0, then amount of time for which this friend is congested.
+   */
+  struct GNUNET_TIME_Absolute congestion_timestamp;
+
   /**
    * Head of pending messages to be sent to this friend.
    */
@@ -566,7 +523,7 @@ struct FriendInfo
    * Tail of pending messages to be sent to this friend.
    */
   struct P2PPendingMessage *tail;
+
   /**
    * Core handle for sending messages to this friend.
    */
@@ -574,104 +531,138 @@ struct FriendInfo
 
 };
 
-
 /**
- * Entry in finger_peermap.
+ * An individual trail to reach to a finger.
  */
-struct FingerInfo
+struct Trail // "node" "element" "relay"
 {
   /**
-   * Finger identity.
-   */
-  struct GNUNET_PeerIdentity finger_identity;
-  
+    * Pointer to next item in the list
+    */
+  struct Trail *next;
+
   /**
-   * Index in finger peer map
+    * Pointer to prev item in the list
+    */
+  struct Trail *prev;
+
+  /**
+   * An element in this trail.
    */
-  unsigned int finger_map_index;
-  
+  struct GNUNET_PeerIdentity peer;
+};
+
+/**
+ * List of all trails to reach a particular finger.
+ */
+struct TrailList // "trail": list of "elements"
+{
   /**
-   * Total number of entries in trail from (me,finger] 
+   * Head of trail.
    */
-  unsigned int trail_length;
-  
+  struct Trail *trail_head;
+
   /**
-   * Head of trail to reach this finger.
+   * Tail of trail.
    */
-  struct TrailPeerList *head;
-  
+  struct Trail *trail_tail;
+
   /**
-   * Tail of trail to reach this finger.
+   * Unique identifier of this trail.
    */
-  struct TrailPeerList *tail;
-  
-};
+  struct GNUNET_HashCode trail_id;
 
-enum current_destination_type
-{
-  FRIEND,
-  FINGER,
-  VALUE,
-  MY_ID
+  /**
+   * Length of trail pointed
+   */
+  unsigned int trail_length;
+
+  /**
+   * Number of trails that the first friend of this trail is a part of.
+   */
+  unsigned int first_friend_trail_count; // remove this, duplicate variable!
+                                         // include a pointer to Friend or function that calculates it
 };
 
 /**
- * FIXME: Think of a better name. 
- * Data structure passed to sorting algorithm in find_successor.
+ * An entry in finger_hashmap.
  */
-struct Sorting_List
+struct FingerInfo
 {
   /**
-   * 64 bit value of peer identity
+   * Finger identity.
+   */
+  struct GNUNET_PeerIdentity finger_identity;
+
+  /**
+   * Index in finger peer map
    */
-  uint64_t peer_id;
-  
+  uint32_t finger_map_index;
+
   /**
-   * Type : MY_ID, FINGER, FINGER, Value 
+   * Number of trails setup so far for this finger.
    */
-  enum current_destination_type type;
-  
+  uint32_t trails_count;
+
   /**
-   * Pointer to original data structure linked to peer id.
+   * Array of trails.
    */
-  void *data;
+  struct TrailList trail_list[MAXIMUM_TRAILS_PER_FINGER]; // OK!
 };
 
-
 /**
- * FIXME: Think of better comments.
- * An entry in Failed_Trail_List
+ * Data structure to keep track of closest peer seen so far in find_successor()
  */
-struct FailedTrail
+struct Closest_Peer
 {
   /**
-   * Source peer which was trying to setup up the trail to @a destination_finger_value
+   * 64 bit value of the peer
    */
-  struct GNUNET_PeerIdentity source_peer;
-  
+  uint64_t value;
+
   /**
-   * Value to which we were trying to find the closest successor.
+   * Trail id to reach to peer.
    */
-  uint64_t destination_finger_value;
-  
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * Peer which has crossed the threshold limit on its routing table size.
+   * First hop, NULL in case of friend and my_identity
    */
-  struct GNUNET_PeerIdentity congested_peer;
-  
-};
+  struct GNUNET_PeerIdentity next_hop;
 
+  /**
+   * Next destination. In case of friend and my_identity , it is same as next_hop
+   * In case of finger it is finger identity.
+   */
+  struct GNUNET_PeerIdentity next_destination;
+};
 
 /**
- * Task that sends FIND FINGER TRAIL requests.
+ * Data structure to store the trail chosen to reach to finger.
  */
-static GNUNET_SCHEDULER_TaskIdentifier find_finger_trail_task;
+struct Correct_Trail
+{
+  /**
+   * First friend in the trail to reach finger.
+   */
+  struct FriendInfo friend;
+
+  /**
+   * Identifier of this trail.
+   */
+  struct GNUNET_HashCode trail_id;
+
+  /**
+   * Total number of peers in this trail.
+   */
+  unsigned int trail_length;
+};
 
 /**
- * 
- * Task that periodically verifies my successor. 
+ * Task that sends FIND FINGER TRAIL requests. This task is started when we have
+ * get our first friend.
  */
-static GNUNET_SCHEDULER_TaskIdentifier verify_successor;
+static GNUNET_SCHEDULER_TaskIdentifier find_finger_trail_task;
 
 /**
  * Identity of this peer.
@@ -679,19 +670,14 @@ static GNUNET_SCHEDULER_TaskIdentifier verify_successor;
 static struct GNUNET_PeerIdentity my_identity;
 
 /**
- * Hash map of all the friends of a peer
+ * Peer map of all the friends of a peer
  */
 static struct GNUNET_CONTAINER_MultiPeerMap *friend_peermap;
 
 /**
  * Hash map of all the fingers of a peer
  */
-static struct GNUNET_CONTAINER_MultiPeerMap *finger_peermap;
-
-/**
- * Hash maps of all the trail which failed due to a congested peer. 
- */
-static struct GNUNET_CONTAINER_MultiPeerMap *failed_trail_list;
+static struct GNUNET_CONTAINER_MultiHashMap32 *finger_hashmap;
 
 /**
  * Handle to CORE.
@@ -699,25 +685,13 @@ static struct GNUNET_CONTAINER_MultiPeerMap *failed_trail_list;
 static struct GNUNET_CORE_Handle *core_api;
 
 /**
- * Finger map index for predecessor entry in finger peermap. 
- */
-#define PREDECESSOR_FINGER_ID 64
-
-/**
- * The current finger index that we have found trail to.
+ * The current finger index that we have want to find trail to. We start the
+ * search with value = 0, i.e. successor peer and then go to PREDCESSOR_FINGER_ID
+ * and decrement it. For any index 63 <= index < 0, if finger is same as successor,
+ * we reset this index to 0.
  */
-static unsigned int current_finger_index;
+static unsigned int current_search_finger_index;
 
-/**
- * Iterate over trail and search your index location in the array. 
- * @param trail Trail which contains list of peers.
- * @return Index in the array.
- */
-static int
-search_my_location (struct GNUNET_PeerIdentity *trail)
-{
-  return 0;
-}
 
 /**
  * Called when core is ready to send a message we asked for
@@ -736,13 +710,13 @@ core_transmit_notify (void *cls, size_t size, void *buf)
   struct P2PPendingMessage *pending;
   size_t off;
   size_t msize;
-  
+
   peer->th = NULL;
   while ((NULL != (pending = peer->head)) &&
          (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
   {
     peer->pending_count--;
-    GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);  
+    GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
     GNUNET_free (pending);
   }
   if (NULL == pending)
@@ -786,11 +760,13 @@ core_transmit_notify (void *cls, size_t size, void *buf)
                                            &core_transmit_notify, peer);
     GNUNET_break (NULL != peer->th);
   }
+
   return off;
 }
 
 
 /**
+ * FIXME: assertion fails at the end of this function. also in core_api.c at 1299.
  * Transmit all messages in the friend's message queue.
  *
  * @param peer message queue to process
@@ -799,18 +775,17 @@ static void
 process_friend_queue (struct FriendInfo *peer)
 {
   struct P2PPendingMessage *pending;
-  
+
   if (NULL == (pending = peer->head))
     return;
   if (NULL != peer->th)
     return;
-  
+
   GNUNET_STATISTICS_update (GDS_stats,
                             gettext_noop
                             ("# Bytes of bandwidth requested from core"),
                             ntohs (pending->msg->size), GNUNET_NO);
-  
-  /* FIXME: Are we correctly initializing importance and pending. */
+
   peer->th =
       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
                                          pending->importance,
@@ -823,75 +798,69 @@ process_friend_queue (struct FriendInfo *peer)
 
 
 /**
- * FIXME: In this function using const, does it affect only here right? not in 
- * the struct P2PTrailSetupMessage as their fields are not defined as const. 
- * Also, I changed current_destination and current_source from const to not, 
- * because when we make a call from handle_dht_p2p_trail_setup, then we are 
- * passing struct for current_destination and not current_source, as we are writing
- * to these variables and we can not decalre them as const. 
- * Construct a trail message and forward it to a friend. 
- * @param source_peer Peer which wants to set up the trail to one of its finger.
- * @param destination_finger Peer identity closest to this value will be 
- *                           @a source_peer's finger.
- * @param current_destination Finger of the @a current_source, for which among 
- *                            its friends, its own identity and all fingers, this
- *                            finger is the closest to the @a destination_finger
- * @param current_source Peer for which @a current_destination is its finger.
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_length Numbers of peers in the trail found so far.
- * @param trail_peer_list Peers this request has traversed so far  
- * @param finger_map_index Index in finger peer map
+ * Construct a trail setup message and forward it to target_friend
+ * @param source_peer Source peer which wants to setup the trail
+ * @param ultimate_destination_finger Peer identity closest to this value will
+ *                                    be finger to @a source_peer
+ * @param next_destination Peer which should get the packet. I can be same as
+ *                         target_friend or different.
+ * @param target_friend Friend to which message is forwarded now.
+ * @param trail_length Total number of peers in trail setup so far.
+ * @param trail_peer_list Trail setup so far
+ * @param finger_map_index Index in finger map for which we are looking for finger.
+ * @param trail_id Unique identifier for the trail we are trying to setup.
+ * @param intermediate_trail_id Trail id of any intermediate trail we may have to
+ *                              traverse during trail setup. If not used then set to
+ *                              0.
  */
 void
-GDS_NEIGHBOURS_send_trail_setup (const struct GNUNET_PeerIdentity *source_peer,
-                                 uint64_t destination_finger,
-                                 struct GNUNET_PeerIdentity *current_destination,
-                                 struct GNUNET_PeerIdentity *current_source,
+GDS_NEIGHBOURS_send_trail_setup (const struct GNUNET_PeerIdentity source_peer,
+                                 uint64_t ultimate_destination_finger,
+                                 struct GNUNET_PeerIdentity next_destination,
                                  struct FriendInfo *target_friend,
                                  unsigned int trail_length,
                                  const struct GNUNET_PeerIdentity *trail_peer_list,
-                                 unsigned int finger_map_index)
+                                 unsigned int finger_map_index,
+                                 struct GNUNET_HashCode new_trail_id,
+                                 struct GNUNET_HashCode *intermediate_trail_id)
 {
   struct P2PPendingMessage *pending;
   struct PeerTrailSetupMessage *tsm;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerTrailSetupMessage) + 
+
+  msize = sizeof (struct PeerTrailSetupMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
-    /* SUPU: Its important to have such statistics as you need to keep track of
-     the packets lost due to full queue. */
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  tsm = (struct PeerTrailSetupMessage *) &pending[1]; 
+  tsm = (struct PeerTrailSetupMessage *) &pending[1];
   pending->msg = &tsm->header;
   tsm->header.size = htons (msize);
   tsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP);
-  /* FIXME: understand where you need to use memcpy or direct assignment. */
-  memcpy (&(tsm->destination_finger), &destination_finger, sizeof (uint64_t));
-  memcpy (&(tsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsm->current_destination), current_destination, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsm->current_source), current_source, sizeof (struct GNUNET_PeerIdentity));
-  tsm->trail_length = htonl (trail_length); 
+  tsm->ultimate_destination_finger = GNUNET_htonll (ultimate_destination_finger);
+  tsm->source_peer = source_peer;
+  tsm->next_destination = next_destination;
+  tsm->trail_length = htonl (trail_length);
   tsm->finger_map_index = htonl (finger_map_index);
-  
-  /* SUPU: here i guess its okay to have it as NULL as it is added at the end of 
-   the struct but in case of current_destination and current_source, it is part
-   of the struct. thats why the confusion. */
-  if (trail_peer_list != NULL)
+  tsm->new_trail_id = new_trail_id;
+  if (NULL == intermediate_trail_id)
+    memset (&tsm->intermediate_trail_id, 0, sizeof (tsm->intermediate_trail_id));
+  else
+    tsm->intermediate_trail_id = *intermediate_trail_id;
+  if (trail_length > 0)
   {
     peer_list = (struct GNUNET_PeerIdentity *) &tsm[1];
     memcpy (peer_list, trail_peer_list, trail_length * sizeof(struct GNUNET_PeerIdentity));
@@ -900,61 +869,66 @@ GDS_NEIGHBOURS_send_trail_setup (const struct GNUNET_PeerIdentity *source_peer,
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
-  
 }
 
 
 /**
- * Construct a trail setup result message and forward it to a friend. 
+ * Construct a trail setup result message and forward it to target friend.
  * @param destination_peer Peer which will get the trail to one of its finger.
  * @param source_finger Peer to which the trail has been setup to.
  * @param target_friend Friend to which this message should be forwarded.
  * @param trail_length Numbers of peers in the trail.
  * @param trail_peer_list Peers which are part of the trail from source to destination.
- * @param finger_map_index Index in finger peer map 
+ * @param finger_map_index Index in finger peer map
+ * @param trail_id Unique identifier of the trail.
  */
 void
-GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity *destination_peer,
-                                        struct GNUNET_PeerIdentity *source_finger,
+GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity destination_peer,
+                                        struct GNUNET_PeerIdentity source_finger,
                                         struct FriendInfo *target_friend,
                                         unsigned int trail_length,
-                                        struct GNUNET_PeerIdentity *trail_peer_list,
-                                        unsigned int finger_map_index)
+                                        const struct GNUNET_PeerIdentity *trail_peer_list,
+                                        unsigned int finger_map_index,
+                                        struct GNUNET_HashCode trail_id)
 {
   struct P2PPendingMessage *pending;
   struct PeerTrailSetupResultMessage *tsrm;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerTrailSetupResultMessage) + 
+
+  msize = sizeof (struct PeerTrailSetupResultMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
 
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
-  pending->importance = 0;    
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  tsrm = (struct PeerTrailSetupResultMessage *) &pending[1]; 
+  tsrm = (struct PeerTrailSetupResultMessage *) &pending[1];
   pending->msg = &tsrm->header;
   tsrm->header.size = htons (msize);
   tsrm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT);
-  memcpy (&(tsrm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsrm->finger_identity), source_finger, sizeof (struct GNUNET_PeerIdentity));
+  tsrm->destination_peer = destination_peer;
+  tsrm->finger_identity = source_finger;
   tsrm->trail_length = htonl (trail_length);
   tsrm->finger_map_index = htonl (finger_map_index);
+  tsrm->trail_id = trail_id;
+
   peer_list = (struct GNUNET_PeerIdentity *) &tsrm[1];
-  memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+  if (trail_length > 0)
+  {
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
   /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
@@ -963,111 +937,245 @@ GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity *destination_
 
 
 /**
- * Construct a PeerVerifySuccessor message and send it to friend.
- * @param source_peer Peer which wants to verify its successor
- * @param successor Peer which is our current successor
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_peer_list Peer which are part of trail from source to destination
- * @param trail_length Number of peers in the trail list.
+ * Send trail rejection message to next_hop
+ * @param source_peer Source peer which is trying to setup the trail.
+ * @param finger_identity Peer closest to this value will be @a source_peer's finger
+ * @param congested_peer Peer which sent this message as it is congested.
+ * @param next_hop Peer to which we are forwarding this message.
+ * @param finger_map_index Index in finger peermap for which we are searching for finger.
+ * @param trail_peer_list Trails seen so far in trail setup before getting rejected
+ *                        by congested_peer
+ * @param trail_length Total number of peers in trail_peer_list
+ * @param trail_id Unique identifier of this trail.
+ * @param congestion_timeout Duration given by congested peer as an estimate of
+ *                           how long it may remain congested.
  */
-void GDS_NEIGHBOURS_send_verify_successor(struct GNUNET_PeerIdentity *source_peer,
-                                          struct GNUNET_PeerIdentity *successor,
-                                          struct FriendInfo *target_friend,
-                                          struct GNUNET_PeerIdentity *trail_peer_list,
-                                          unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_trail_rejection (struct GNUNET_PeerIdentity source_peer,
+                                     uint64_t finger_identity,
+                                     struct GNUNET_PeerIdentity congested_peer,
+                                     unsigned int finger_map_index,
+                                     struct GNUNET_PeerIdentity *trail_peer_list,
+                                     unsigned int trail_length,
+                                     struct GNUNET_HashCode trail_id,
+                                     struct FriendInfo *target_friend,
+                                     const struct GNUNET_TIME_Relative congestion_timeout)
 {
-  struct PeerVerifySuccessorMessage *vsm;
+  struct PeerTrailRejectionMessage *trm;
   struct P2PPendingMessage *pending;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerVerifySuccessorMessage) + 
+
+  msize = sizeof (struct PeerTrailRejectionMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  trm = (struct PeerTrailRejectionMessage *)&pending[1];
+  pending->msg = &trm->header;
+  trm->header.size = htons (msize);
+  trm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION);
+  trm->source_peer = source_peer;
+  trm->congested_peer = congested_peer;
+  trm->congestion_time = congestion_timeout;
+  trm->finger_map_index = htonl (finger_map_index);
+  trm->trail_id = trail_id;
+
+  peer_list = (struct GNUNET_PeerIdentity *) &trm[1];
+  if (trail_length > 0)
+  {
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
+  /* Send the message to chosen friend. */
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
+}
+
+
+/**
+ * Construct a verify successor message and forward it to target_friend.
+ * @param source_peer Peer which wants to verify its successor.
+ * @param successor Peer which is @a source_peer's current successor.
+ * @param trail_id Identifier of trail to reach successor.
+ * @param trail Trail to reach from source_peer to successor
+ * @param trail_length Total number of peers in @a trail.
+ * @param target_friend Message send to this friend.
+ */
+void
+GDS_NEIGHBOURS_send_verify_successor_message (struct GNUNET_PeerIdentity source_peer,
+                                              struct GNUNET_PeerIdentity successor,
+                                              const struct GNUNET_HashCode trail_id,
+                                              struct GNUNET_PeerIdentity *trail,
+                                              unsigned int trail_length,
+                                              struct FriendInfo *target_friend)
+{
+  struct PeerVerifySuccessorMessage *vsm;
+  struct P2PPendingMessage *pending;
+  struct GNUNET_PeerIdentity *peer_list;
+  size_t msize;
+
+  msize = sizeof (struct PeerVerifySuccessorMessage);
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  {
+    GNUNET_break (0);
+    return;
+  }
+
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
+  {
+    GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
+                               1, GNUNET_NO);
+  }
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
   vsm = (struct PeerVerifySuccessorMessage *) &pending[1];
   pending->msg = &vsm->header;
   vsm->header.size = htons (msize);
   vsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR);
-  memcpy (&(vsm->successor), successor, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
+  vsm->source_peer = source_peer;
+  vsm->successor = successor;
+  vsm->trail_id = trail_id;
   vsm->trail_length = htonl (trail_length);
-  peer_list = (struct GNUNET_PeerIdentity *) &vsm[1];
-  memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
+  if (trail_length > 0)
+  {
+    peer_list = (struct GNUNET_PeerIdentity *) &vsm[1];
+    memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
+
   /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
-  
 }
 
 
 /**
- * Construct a PeerVerifySuccessorResult message and send it to friend.
- * @param destination_peer Peer which sent verify successor message
- * @param source_successor Peer to which verify successor message was sent.
- * @param my_predecessor source_successor's predecessor.
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_peer_list Peers which are part of trail from source to destination
- * @param trail_length Number of peers in the trail list.
+ * Construct a trail teardown message and send it to target_friend
+ * @param source_peer Source of the trail.
+ * @param destination_peer Destination of the trail.
+ * @param trail_id Unique identifier of the trail.
+ * @param trail_direction Direction of trail.
+ * @param target_friend Friend to get this message.
+ */
+void
+GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_PeerIdentity source_peer,
+                                    struct GNUNET_PeerIdentity destination_peer,
+                                    struct GNUNET_HashCode trail_id,
+                                    enum GDS_ROUTING_trail_direction trail_direction,
+                                    struct FriendInfo *target_friend)
+{
+  struct PeerTrailTearDownMessage *ttdm;
+  struct P2PPendingMessage *pending;
+  size_t msize;
+
+  msize = sizeof (struct PeerTrailTearDownMessage);
+
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  {
+    GNUNET_break (0);
+    return;
+  }
+
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
+  {
+    GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
+                               1, GNUNET_NO);
+  }
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;    /* FIXME */
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  ttdm = (struct PeerTrailTearDownMessage *) &pending[1];
+  pending->msg = &ttdm->header;
+  ttdm->header.size = htons (msize);
+  ttdm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN);
+  ttdm->source_peer = source_peer;
+  ttdm->destination_peer = destination_peer;
+  ttdm->TRAIL_ID = trail_id;
+  ttdm->trail_direction = htonl (trail_direction);
+
+  /* Send the message to chosen friend. */
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
+}
+
+
+/**
+ * Construct a verify successor message and send it to target_friend
+ * @param destination_peer
+ * @param source_successor
+ * @param succ_predecessor
+ * @param trail_id
+ * @param trail
+ * @param trail_length
+ * @param target_friend
  */
-void GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity *destination_peer,
-                                                  struct GNUNET_PeerIdentity *source_successor,
-                                                  struct GNUNET_PeerIdentity *my_predecessor,
-                                                  struct FriendInfo *target_friend,
-                                                  struct GNUNET_PeerIdentity *trail_peer_list,
-                                                  unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity destination_peer,
+                                             struct GNUNET_PeerIdentity source_successor,
+                                             struct GNUNET_PeerIdentity succ_predecessor,
+                                             struct GNUNET_HashCode trail_id,
+                                             const struct GNUNET_PeerIdentity *trail,
+                                             unsigned int trail_length,
+                                             enum GDS_ROUTING_trail_direction trail_direction,
+                                             struct FriendInfo *target_friend)
 {
   struct PeerVerifySuccessorResultMessage *vsmr;
   struct P2PPendingMessage *pending;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerVerifySuccessorResultMessage) + 
+
+  msize = sizeof (struct PeerVerifySuccessorResultMessage) +
           (trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
 
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
   vsmr = (struct PeerVerifySuccessorResultMessage *) &pending[1];
   pending->msg = &vsmr->header;
   vsmr->header.size = htons (msize);
   vsmr->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT);
-  memcpy (&(vsmr->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsmr->source_successor), source_successor, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsmr->my_predecessor), my_predecessor, sizeof (struct GNUNET_PeerIdentity));
-  vsmr->trail_length = htonl (trail_length);  
-  peer_list = (struct GNUNET_PeerIdentity *) &vsmr[1];
-  memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+  vsmr->destination_peer = destination_peer;
+  vsmr->my_predecessor = succ_predecessor;
+  vsmr->source_successor = source_successor;
+  vsmr->trail_direction = htonl (trail_direction);
+
+  if (trail_length > 0)
+  {
+    peer_list = (struct GNUNET_PeerIdentity *) &vsmr[1];
+    memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
+
    /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
@@ -1076,54 +1184,59 @@ void GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity *de
 
 
 /**
- * Construct a PeerNotifyNewSuccessor message and send it to friend.
- * @param source_peer Peer which is sending notify message to its new successor.
- * @param destination_peer Peer which is the new destination.
- * @param target_friend Next friend to pass this message to. 
- * @param peer_list List of peers in the trail to reach to destination_peer.
- * @param trail_length Total number of peers in peer list 
+ * Construct a notify new successor message and send it to target_friend
+ * @param source_peer
+ * @param new_successor
+ * @param new_successor_trail
+ * @param new_successor_trail_length
+ * @param new_succesor_trail_id
  */
-void 
-GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity *source_peer,
-                                          struct GNUNET_PeerIdentity *destination_peer,
-                                          struct FriendInfo *target_friend,
-                                          struct GNUNET_PeerIdentity *trail_peer_list,
-                                          unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity source_peer,
+                                          struct GNUNET_PeerIdentity new_successor,
+                                          struct GNUNET_PeerIdentity *new_successor_trail,
+                                          unsigned int new_successor_trail_length,
+                                          struct GNUNET_HashCode new_succesor_trail_id,
+                                          struct FriendInfo *target_friend)
 {
   struct PeerNotifyNewSuccessorMessage *nsm;
   struct P2PPendingMessage *pending;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerNotifyNewSuccessorMessage) + 
-          (trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
+  msize = sizeof (struct PeerNotifyNewSuccessorMessage) +
+          (new_successor_trail_length * sizeof(struct GNUNET_PeerIdentity));
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
   nsm = (struct PeerNotifyNewSuccessorMessage *) &pending[1];
   pending->msg = &nsm->header;
   nsm->header.size = htons (msize);
   nsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR);
-  memcpy (&(nsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(nsm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  nsm->trail_length = htonl (trail_length);
-  
-  peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
-  memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+  nsm->source_peer = source_peer;
+  nsm->destination_peer = new_successor;
+  nsm->trail_length = htonl (new_successor_trail_length);
+  nsm->trail_id = new_succesor_trail_id;
+  if (new_successor_trail_length > 0)
+  {
+    peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
+    memcpy (peer_list, new_successor_trail,
+            new_successor_trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
+
    /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
@@ -1131,1860 +1244,2273 @@ GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity *source_pee
 }
 
 
-/** 
- * FIXME: Optimizaiton Once the basic code is running. Add the optimization
- * where you check if the threshold on number of links that should go through
- * a particular friend has crossed. If yes then again choose a different
- * friend. Important that the new friend chosen should be different. How to 
- * ensure this? This is an important optimization as without this one x-vine
- * is actually not a sybil tolerant DHT.
- * Randomly choose one of your friends from the friends_peer map
- * @return Friend
+/**
+ * Construct an add_trail message and send it to target_friend
+ * @param source_peer Source of the trail.
+ * @param destination_peer Destination of the trail.
+ * @param trail_id Unique identifer of the trail
+ * @param trail Trail from @a source_peer to @a destination_peer
+ * @param trail_length Total number of peers in @a trail.
+ * @param target_friend Next peer to get this message.
  */
-static struct FriendInfo *
-select_random_friend (struct GNUNET_PeerIdentity *congested_peer)
-{  
-  unsigned int current_size;
-  unsigned int *index; 
-  unsigned int j = 0;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *friend;
-  
-  current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
-  index = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
-  iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
-  if (GNUNET_CONTAINER_multipeermap_size (friend_peermap) == 0)
+void
+GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
+                               struct GNUNET_PeerIdentity destination_peer,
+                               struct GNUNET_HashCode trail_id,
+                               struct GNUNET_PeerIdentity *trail,
+                               unsigned int trail_length,
+                               struct FriendInfo *target_friend)
+{
+  struct PeerAddTrailMessage *adm;
+  struct GNUNET_PeerIdentity *peer_list;
+  struct P2PPendingMessage *pending;
+  size_t msize;
+
+  msize = sizeof (struct PeerAddTrailMessage) +
+          (trail_length * sizeof(struct GNUNET_PeerIdentity));
+
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
-    /* FIXME: It may happen that there is not friend in friend peermap but
-     as this task has already been started it failed.*/
-    GNUNET_break(0);
-    return NULL;
+    GNUNET_break (0);
+    return;
   }
-  while(j < (*index))
+
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,NULL,NULL))
-    {
-      j++;
-    }
-    else 
-      return NULL;
-  }  
-
-  if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,&key_ret,(const void **)&friend))
-  {
-    /* TODO: Here you have chosen a random friend. Now you should check the size
-     of its routing table size, and if its more than threshold, then check which
-     of the entries has trail length greater than trail length threshold. we
-     should without checking the routing table size also we should check the
-     trail with trail length greater than threshold. then 
-     you should try to find a new route through this new node that has joined in
-     only for those finger entries whose trail length is greater than threshold. 
-     But I don't want the new node to wait for this process to get over. so
-     should i declare a function which will be called after some interval.*/
-    return friend;
+    GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
+                               1, GNUNET_NO);
   }
-  else
-    return NULL;
-}
 
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;    /* FIXME */
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  adm = (struct PeerAddTrailMessage *) &pending[1];
+  pending->msg = &adm->header;
+  adm->header.size = htons (msize);
+  adm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL);
+  adm->source_peer = source_peer;
+  adm->destination_peer = destination_peer;
+  adm->trail_length = htonl (trail_length);
+  adm->trail_id = trail_id;
 
-/**
- * FIMXE: pass current_finger_index as argument.
- * Compute finger_identity to which we want to setup the trail
- * @return finger_identity 
- */
-static uint64_t 
-compute_finger_identity()
-{
-  uint64_t my_id64 ;
+  if (trail_length > 0)
+  {
+    peer_list = (struct GNUNET_PeerIdentity *)&adm[1];
+    memcpy (peer_list, trail, sizeof (struct GNUNET_PeerIdentity) * trail_length);
+  }
+
+  /* Send the message to chosen friend. */
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
 
-  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
-  my_id64 = GNUNET_ntohll (my_id64);
-  /*FIXME: Do we need a mod finger = ((my_id + pow(2, finger_index)) mod (pow (2, MAX_FINGERS))*/
-  return (my_id64 + (unsigned long) pow (2, current_finger_index));
 }
 
 
 /**
- * Compute immediate predecessor identity in the network.
- * @return peer identity of immediate predecessor.
+ * Merge into "teardown", add source and "last/new_first" in message struct.
+ * Construct a trail compression message and send it to target_friend.
+ * @param source_peer Source of the trail.
+ * @param destination_finger Destination of trail.
+ * @param trail_id Unique identifier of trail.
+ * @param first_friend First hop in compressed trail to reach from source to finger
+ * @param target_friend Next friend to get this message.
  */
-static uint64_t 
-compute_predecessor_identity()
+void
+GDS_NEIGHBOURS_send_trail_compression (struct GNUNET_PeerIdentity source_peer,
+                                       struct GNUNET_PeerIdentity destination_peer,
+                                       struct GNUNET_HashCode trail_id,
+                                       struct GNUNET_PeerIdentity first_friend,
+                                       struct FriendInfo *target_friend)
 {
-  uint64_t my_id64;
-
-  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
-  my_id64 = GNUNET_ntohll (my_id64);
-  return (my_id64 -1);
-}
+  struct P2PPendingMessage *pending;
+  struct PeerTrailCompressionMessage *tcm;
+  size_t msize;
 
+  msize = sizeof (struct PeerTrailCompressionMessage);
 
-/**
- * Periodically ping your successor to ask its current predecessor
- * 
- * @param cls closure for this task
- * @param tc the context under which the task is running
- */
-static void
-send_verify_successor_message (void *cls,
-                               const struct GNUNET_SCHEDULER_TaskContext *tc )
-{
-  struct GNUNET_TIME_Relative next_send_time;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_PeerIdentity *peer_list;
-  struct FingerInfo *finger;
-  unsigned int finger_index;
-  unsigned int i;
-  int flag = 0;
-  
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (finger_iter, &key_ret,
-                                                                 (const void **)&finger)) 
-    {
-      if (0 == finger->finger_map_index)
-      {
-        flag = 1;
-        break;
-      }
-    }
+    GNUNET_break (0);
+    return;
   }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  
-  if( flag == 0)
-    goto send_new_request;
-  
-  peer_list = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * finger->trail_length);
-  struct TrailPeerList *iterate;
-  iterate = finger->head;
-  i = 0;
-  while ( i < (finger->trail_length))
+
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
   {
-    memcpy (&peer_list[i], &(iterate->peer), sizeof (struct GNUNET_PeerIdentity));
-    iterate = iterate->next;
-    i++;
+    GNUNET_STATISTICS_update (GDS_stats,
+                              gettext_noop ("# P2P messages dropped due to full queue"),
+                                                     1, GNUNET_NO);
   }
-  next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-  memcpy (next_hop, &peer_list[0], sizeof (struct GNUNET_PeerIdentity));
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
 
-  GDS_NEIGHBOURS_send_verify_successor (&my_identity,
-                                        &(finger->finger_identity),
-                                        target_friend,
-                                        peer_list,
-                                        finger->trail_length);
-  
-  
-  /* FIXME: Understand what this function is actually doing here. */
-  send_new_request:
-  next_send_time.rel_value_us =
-      DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
-      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
-                                DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
-  verify_successor =
-      GNUNET_SCHEDULER_add_delayed (next_send_time, &send_verify_successor_message,
-                                    NULL);
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;    /* FIXME */
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  tcm = (struct PeerTrailCompressionMessage *) &pending[1];
+  pending->msg = &tcm->header;
+  tcm->header.size = htons (msize);
+  tcm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION);
+  tcm->source_peer = source_peer;
+  tcm->new_first_friend = first_friend;
+  tcm->trail_id = trail_id;
+  tcm->destination_peer = destination_peer;
+
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
+
 }
 
 
 /**
- * FIXME - the main logic of handling the finger map index has changed.
- * first we start with finger index = 64, that index is reserved for the
- * predecessor always. Then we start going backwards, finger_index = 63 to 0
- * and once its 0 we again go back to 64. now, when you start looking for the finger
- * then your successor is always the finger with lowest finger index. in finger_table_add
- * whenever you do an entry you check for predecessor , if the new finger identity
- * is greater than existing one, then that should be your predecessor. In case of 
- * other fingers also, if the new entry is smaller than existing one. If yes
- * then that is correct finger for that finger index. Also, the lowest finger index and
- * its corresponding finger identity is your successor.
- * 
- * Choose a random friend and start looking for the trail to reach to 
- * finger identity through this random friend. 
- *
- * @param cls closure for this task
- * @param tc the context under which the task is running
+ * Seach my location in trail.
+ * @param trail List of peers
+ * @return my_index if found
+ *         -1 if no entry found.
  */
-static void
-send_find_finger_trail_message (void *cls,
-                                const struct GNUNET_SCHEDULER_TaskContext *tc)
+static int
+search_my_index (const struct GNUNET_PeerIdentity *trail,
+                 int trail_length)
 {
-  struct FriendInfo *target_friend;
-  struct GNUNET_TIME_Relative next_send_time;
-  uint64_t finger_identity;
-  unsigned int finger_map_index;
-  
-  /* FIXME: understand how does this scheduling of processes take place? */
-  next_send_time.rel_value_us =
-      DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
-      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
-                                DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
-  /* FIXME: here we are just adding the process to the scheduling list. only
-   when this function is executed, it may get scheduled. */
-  find_finger_trail_task =
-      GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_finger_trail_message,
-                                    NULL);
-  target_friend = select_random_friend (NULL);
-  if (NULL == target_friend)
-  {
-     /* SUPU: Here we can get NULL in the case there is no friend in the peer map
-   or all of the friends have reached their threshold. The first case should ideally
-   never happen because in handle_core_disconnect we have already canceled the task
-   but it may happen if we already started the process and we reached here and 
-   we cancelled the next task. So, it can return NULL in that case also. Should
-   we handle both cases in same way or not? */
-    return;
-  }
-  
-  /* FIXME: start with current_finger_index = 64, */
-  if (PREDECESSOR_FINGER_ID == current_finger_index)
-  {
-    /* FIXME: Where do we set the value back to PREDECESSR_FINGER_ID? Only
-     when current_finger_index = 0, do we set it back to PREDECESSOR_FINGER_ID,
-     in finger_table_add? Or is there any other possible condition, where we 
-     may need to set it to PREDECESSOR_FINGER_ID*/
-    finger_identity = compute_predecessor_identity();  
-  }
-  else
+  int i;
+
+  for (i = 0; i < trail_length; i++)
   {
-    finger_identity = compute_finger_identity();
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &trail[i]))
+      return i;
   }
-  finger_map_index = current_finger_index;
-  
-  /* FIXME: verify if its correct to set current_destination and current_source
-   as my identity. */
-  GDS_NEIGHBOURS_send_trail_setup (&my_identity, finger_identity, &(target_friend->id),
-                                   &(target_friend->id), target_friend, 0, NULL, finger_map_index);
+
+  return -1;
 }
 
 
 /**
- * 
- * @param destination_peer
- * @param existing_trail
- * @param trail_length
- * @return 
+ * Iterate over the list of all the trails to reach Finger. In case the first
+ * friend to reach the finger has crossed the trail threshold or is congested,
+ * then don't select it. In case there multiple available good trails to reach
+ * to Finger, choose the one with shortest trail length.
+ * @param finger Finger
+ * @return struct Correct_Trail which contains the first friend , trail id
+ * and trail length. NULL in case none of the trails are free.
  */
-static struct GNUNET_PeerIdentity *
-invert_trail_list (struct GNUNET_PeerIdentity *destination_peer,
-                   struct GNUNET_PeerIdentity *existing_trail, 
-                   unsigned int trail_length)
+static struct Correct_Trail *
+select_trail_to_finger (struct FingerInfo *finger)
 {
+  struct FriendInfo *friend;
+  struct TrailList *iterator;
+  struct Correct_Trail *finger_trail;
   int i;
-  int j;
-  struct GNUNET_PeerIdentity *new_trail;
-  
-  j = 0;
-  new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * trail_length);
-  
-  if (trail_length > 1)
+
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                            &my_identity))
+    return NULL;
+
+  finger_trail = GNUNET_new (struct Correct_Trail);
+
+  for (i = 0; i < finger->trails_count; i++)
   {
-    i = trail_length - 2;
-    while (i >= 0 )
+    iterator = &finger->trail_list[i];
+    if (iterator->trail_length > 0)
+    {
+      friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                  &iterator->trail_head->peer);
+    }
+    else
+    {
+      friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                  &finger->finger_identity);
+    }
+
+    if ((friend->trails_count < TRAILS_THROUGH_FRIEND_THRESHOLD)||
+      ((0 == GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us)))
     {
-      memcpy( &new_trail[j], &existing_trail[i], sizeof (struct GNUNET_PeerIdentity));
-      i--;
-      j++;
+      if (iterator->trail_length == 0)
+      {
+        finger_trail->friend = *friend;
+        //finger_trail->trail_id = 0;
+        finger_trail->trail_length = 0;
+        return finger_trail;
+      }
+
+      if (finger_trail->trail_length > iterator->trail_length)
+      {
+        finger_trail->friend = *friend;
+        finger_trail->trail_id = iterator->trail_id;
+        finger_trail->trail_length = iterator->trail_length;
+      }
     }
   }
-  memcpy (&new_trail[j], destination_peer, sizeof(struct GNUNET_PeerIdentity));
-  return new_trail;
+
+  return finger_trail;
 }
 
 
-#if 0
 /**
- * 
- * @param existing_finger
- * @param new_finger
- * @return 
+ * Select closest finger to value.
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value to be compare
+ * @return Closest peer
  */
-static int
-compare_finger_identity (struct GNUNET_PeerIdentity *existing_finger,
-                         struct GNUNET_PeerIdentity *new_finger)
+static struct GNUNET_PeerIdentity *
+select_closest_finger (struct GNUNET_PeerIdentity *peer1,
+                       struct GNUNET_PeerIdentity *peer2,
+                       uint64_t value)
 {
-  int ret;
-  ret = (existing_finger > new_finger) ? 1 : 
-          (existing_finger == new_finger) ? 0 : -1;
-  return ret;
-}
+#if 0
+  uint64_t peer1_value;
+  uint64_t peer2_value;
+
+  memcpy (&peer1_value, peer1, sizeof (uint64_t));
+  memcpy (&peer2_value, peer2, sizeof (uint64_t));
+
+  if ((peer1_value <= value) && (value <= peer2_value))
+    return peer2;
+  else if ((peer2_value <= value) && (value <= peer1_value))
+    return peer1;
+  else if ((peer1_value <= peer2_value) && (peer2_value <= value))
+    return peer1;
+  else if ((peer2_value <= peer1_value) && (peer1_value <= value))
+    return peer2;
+  else if ((value <= peer1_value) && (peer1_value <= peer2_value))
+    return peer1;
+  else /*if ((value <= peer2_value) && (peer2_value <= peer1_value))*/
+    return peer2;
 #endif
-
-/**
- * FIXME: Not sure of the logic to find the correct predecessor
- * I think logic of this code is wrong everything else seems to be correct. 
- * Given two finger identities, find the closest predecessor. 
- * @param existing_predecessor
- * @param new_predecessor
- * @return 
- */
-static int
-compare_predecessor(struct GNUNET_PeerIdentity *peer)
-{
-  /* FIXME: here you should first check if you already have an entry in the 
-   finger peer map for finger index = 64, if yes then compare it with peer
-   if not then just add the peer. */
-  return 0;
+  return NULL;
 }
 
 
-/*FIXME: Here you need to set the correct value of finger_map_index,
- * in case it is 0, then you set it back to 64, and in case it is x,
- * then you set it back to x-1. current_finger_index = ( current_finger_index - 1) % MAX_FINGERS
- * Add an entry in finger table. 
- * @param finger_identity Peer identity of finger
- * @param finger_trail Trail to reach the finger
- * @param trail_length Number of peers in the trail. 
- * @param finger_map_index Index in finger peer map.
+/**
+ * Select closest predecessor to value.
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value to be compare
+ * @return Closest peer
  */
-static
-void finger_table_add (struct GNUNET_PeerIdentity *finger_identity,
-                       struct GNUNET_PeerIdentity *finger_trail,
-                       unsigned int trail_length,
-                       unsigned int finger_map_index)
+static struct GNUNET_PeerIdentity *
+select_closest_predecessor (struct GNUNET_PeerIdentity *peer1,
+                            struct GNUNET_PeerIdentity *peer2,
+                            uint64_t value)
 {
-  struct FingerInfo *new_finger_entry;
-  //struct GNUNET_PeerIdentity key_ret;
-  int i;
-  //struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  //struct FingerInfo *existing_finger;
-  //int finger_index;
-
-  /* SUPU Here we trying to check if we already have an entry. If yes then we
-   can keep two trails for redundant routing. if they are different then we
-   need to choose the closest one. and remove the other one. */
-#if 0
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap); 
+  #if 0
+  uint64_t peer1_value;
+  uint64_t peer2_value;
 
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (finger_iter, &key_ret,
-                                                                 (const void **)&existing_finger)) 
-    {
-      if ((finger_map_index == existing_finger->finger_map_index))
-      {
-        if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),finger_identity))
-        {
-          /* FIXME: Here you should check if the trail is same. If yes then don't add the entry. it
-           seems to be very suboptimal. */
-          if ((existing_finger->trail_length) == trail_length)
-          {
-            struct TrailPeerList *iterate;
-            iterate = existing_finger->head;
-            int k;
-            k = 0;
-            while (k < trail_length)
-            {
-              if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(iterate->peer), &finger_trail[k]))
-              {
-                k++;
-                iterate = iterate->next;
-              }
-            }
-            if (k == trail_length)
-              return;
-            else
-              goto add_new_entry;
-          }
-          goto add_new_entry;
-        }
-        else
-        {
-          int ret;
-          if (finger_map_index == 1)
-          {
-            ret = compare_predecessor (&(existing_finger->finger_identity),
-                                       finger_identity);
-            goto add_new_entry;
-          }
-          else
-          {
-            ret = compare_finger_identity (&(existing_finger->finger_identity),
-                                          finger_identity);
-          }
-          if (ret > 0)
-          {
-            GNUNET_assert (GNUNET_YES ==
-                       GNUNET_CONTAINER_multipeermap_remove (finger_peermap,
-                                                             &(existing_finger->finger_identity),
-                                                             existing_finger));
-            goto add_new_entry;
-          }
-          else
-          {
-            return;
-          }
-        }
-      }
-    }
-  }
+  memcpy (&peer1_value, peer1, sizeof (uint64_t));
+  memcpy (&peer2_value, peer2, sizeof (uint64_t));
 
-  add_new_entry:
 #endif
-  new_finger_entry = GNUNET_malloc (sizeof (struct FingerInfo));
-  memcpy (&(new_finger_entry->finger_identity), finger_identity, sizeof (struct GNUNET_PeerIdentity));
-  new_finger_entry->finger_map_index = finger_map_index;
-  
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, finger_identity))
-  {
-    /* I am the finger */
-    new_finger_entry->trail_length = 0;
-  }
-  else
-  {
-    i = 0;
-    while (i < trail_length)
-    {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
-    
-      memcpy (&(element->peer), &finger_trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(new_finger_entry->head, new_finger_entry->tail, element);
-      i++;
-    }
-    new_finger_entry->trail_length = trail_length;
-  }
-  
-  /* FIXME: Here we are keeping multiple hashmap option so that there are
-   multiple routes to reach to same finger, redundant routing.
-   * Also same peers could be our fingers for different finger map index
-   * Should we handle the case where we have same fingers at the different
-   * finger index but with different trail to reach.  */
-  GNUNET_assert (GNUNET_OK ==
-                 GNUNET_CONTAINER_multipeermap_put (finger_peermap,
-                                                    &(new_finger_entry->finger_identity),
-                                                    new_finger_entry,
-                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 
-  
-  if (1 == GNUNET_CONTAINER_multipeermap_size (finger_peermap)
-      && (new_finger_entry->finger_map_index!= 1))
-  {
-    verify_successor = GNUNET_SCHEDULER_add_now (&send_verify_successor_message, NULL);
-  }
+  return NULL;
 }
-  
 
-/**
- * Compare two peer identities.
- * @param p1 Peer identity
- * @param p2 Peer identity
- * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2. 
- */
-  static int
-compare_peer_id (const void *p1, const void *p2)
-{
-  struct Sorting_List *p11;
-  struct Sorting_List *p22;
-  int ret;
-  p11 = GNUNET_malloc (sizeof (struct Sorting_List));
-  p22 = GNUNET_malloc (sizeof (struct Sorting_List));
-  p11 = (struct Sorting_List *)p1;
-  p22 = (struct Sorting_List *)p2;
-  ret = ( (p11->peer_id) > (p22->peer_id) ) ? 1 : 
-          ( (p11->peer_id) == (p22->peer_id) ) ? 0 : -1;
-  return ret;
-}
 
-  
 /**
- * Return the successor of value in all_known_peers.
- * @param all_known_peers list of all the peers
- * @param value value we have to search in the all_known_peers.
- * @return 
+ * Select the closest peer among two peers (which should not be same)
+ * with respect to value and finger_map_index
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value relative to which we find the closest
+ * @param finger_map_index Index in finger map. If equal to PREDECESSOR_FINGER_ID,
+ *                         then we use different logic than other
+ *                         finger_map_index
+ * @return Closest peer among two peers.
  */
-static struct Sorting_List *
-find_closest_successor(struct Sorting_List *all_known_peers, uint64_t value,
-                       unsigned int size)
+static struct GNUNET_PeerIdentity *
+select_closest_peer (struct GNUNET_PeerIdentity *peer1,
+                     struct GNUNET_PeerIdentity *peer2,
+                     uint64_t value,
+                     unsigned int finger_map_index)
 {
-  int first;
-  int last;
-  int middle;
-  
-  first = 0;
-  last = size - 1;
-  middle = (first + last)/2;
-  
-  while(first <= last)
-  {
-    if(all_known_peers[middle].peer_id < value)
-    {
-      first = middle + 1; 
-    }
-    else if(all_known_peers[middle].peer_id == value)
-    {
-      if(middle == (size -1))
-      {
-        return &all_known_peers[0];
-      }
-      else
-      {
-        return &all_known_peers[middle+1];
-      }
-    }
-    else
-    {
-       last = middle - 1;
-    }
-  
-    middle = (first + last)/2;  
-  }
-  return NULL;
+  struct GNUNET_PeerIdentity *closest_peer;
+
+  if (PREDECESSOR_FINGER_ID == finger_map_index)
+    closest_peer = select_closest_predecessor (peer1, peer2, value);
+  else
+    closest_peer = select_closest_finger (peer1, peer2, value);
+
+  return closest_peer;
 }
 
 
 /**
- * here you should set the current source instead of destination type. 
- * Find closest successor for the value.
- * @param value Value for which we are looking for successor
- * FIXME: pass the correct value for current_destination 
- * @param[out] current_destination set to the end of the finger to traverse next 
- * @param type Next destination type
- * @return Peer identity of next hop, NULL if we are the 
- *   ultimate destination 
+ * Find the successor for destination_finger_value among my_identity, all my
+ * friend and all my fingers. Don't consider friends or fingers
+ * which are congested or have crossed the threshold.
+ * @param destination_finger_value Peer closest to this value will be the next successor.
+ * @param next_destination [out] Updated to friend identity in case a friend is
+ *                               successor, updated to first friend to reach to finger
+ *                               in case finger is the destination.
+ * @param new_intermediate_trail_id [out] In case we finger is the @a next_destination,
+ *                                then we updated the field with trail id to reach
+ *                                to that finger.
+ * @param finger_map_index Index in finger peermap for which we are
+ *                         looking for a finger, to discern between
+ *                         IS_PREDECESSOR or not.
+ * @return
  */
 static struct GNUNET_PeerIdentity *
-find_successor (uint64_t value, struct GNUNET_PeerIdentity *current_destination,
-               struct GNUNET_PeerIdentity *current_source)
+find_successor (uint64_t destination_finger_value,
+                struct GNUNET_PeerIdentity *next_destination,
+                struct GNUNET_HashCode *new_intermediate_trail_id,
+                unsigned int finger_map_index)
 {
+  struct Closest_Peer *successor;
+  struct GNUNET_PeerIdentity *next_hop;
   struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
+  struct GNUNET_CONTAINER_MultiHashMap32Iterator *finger_iter;
+  struct GNUNET_PeerIdentity *closest_peer;
+  struct Correct_Trail *finger_trail;
   struct FriendInfo *friend;
   struct FingerInfo *finger;
-  unsigned int finger_index;
-  unsigned int friend_index;
-  struct Sorting_List *successor;
-  unsigned int size;
-  int j;
-  
-  /* 2 is added in size for my_identity and value which will part of all_known_peers. */
-  size = GNUNET_CONTAINER_multipeermap_size (friend_peermap)+
-         GNUNET_CONTAINER_multipeermap_size (finger_peermap)+
-         2;
-  
-  struct Sorting_List all_known_peers[size];
-  
-  int k;
-  for (k = 0; k < size; k++)
-    all_known_peers[k].peer_id = 0;
-  
-  /* Copy your identity at 0th index in all_known_peers. */
-  j = 0;
-  memcpy (&(all_known_peers[j].peer_id), &my_identity, sizeof (uint64_t));
-  all_known_peers[j].type = MY_ID;
-  all_known_peers[j].data = 0;
-  j++;
-  
-  /* Copy value */
-  all_known_peers[j].peer_id = value;
-  all_known_peers[j].type = VALUE;
-  all_known_peers[j].data = 0;
-  j++;
-  
-  /* Iterate over friend peer map and copy all the elements into array. */
-  friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap); 
-  for (friend_index = 0; friend_index < GNUNET_CONTAINER_multipeermap_size (friend_peermap); friend_index++)
+  int i;
+
+  successor = GNUNET_new (struct Closest_Peer);
+  memcpy (&successor->value, &my_identity, sizeof (uint64_t));
+  //successor->trail_id = 0; /* FIXME:Default value for trail id */
+  successor->next_hop = my_identity;
+  successor->next_destination = my_identity;
+
+  friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+  for (i= 0; i < GNUNET_CONTAINER_multipeermap_size (friend_peermap); i++)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(friend_iter,&key_ret,(const void **)&friend)) 
+    GNUNET_assert (GNUNET_YES ==
+      GNUNET_CONTAINER_multipeermap_iterator_next (friend_iter, NULL,
+                                                  (const void **)&friend));
+    if ((friend->trails_count > TRAILS_THROUGH_FRIEND_THRESHOLD)||
+        (0 != GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us))
+      continue;
+
+    closest_peer = select_closest_peer (&my_identity, &friend->id,
+                                        destination_finger_value,
+                                        finger_map_index);
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer, &friend->id))
     {
-      memcpy (&(all_known_peers[j].peer_id), &(friend->id), sizeof (uint64_t));
-      all_known_peers[j].type = FRIEND;
-      all_known_peers[j].data = friend;
-      j++;
+      memcpy (&successor->value, &friend->id, sizeof (uint64_t));
+      //successor->trail_id = 0;
+      successor->next_hop = friend->id;
+      successor->next_destination = friend->id;
     }
   }
-  
-  /* Iterate over finger map and copy all the entries into all_known_peers array. */
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
+
+  finger_iter = GNUNET_CONTAINER_multihashmap32_iterator_create (finger_hashmap);
+  for (i = 0; i < GNUNET_CONTAINER_multihashmap32_size (finger_hashmap); i++)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(finger_iter,&key_ret,(const void **)&finger)) 
-    {
-      memcpy (&(all_known_peers[j].peer_id), &(finger->finger_identity), sizeof (uint64_t));
-      all_known_peers[j].type = FINGER;
-      all_known_peers[j].data = finger;
-      j++;
+    GNUNET_assert (GNUNET_YES ==
+      GNUNET_CONTAINER_multihashmap32_iterator_next (finger_iter, NULL,
+                                                     (void *)&finger));
+   finger_trail = select_trail_to_finger (finger);
+   if (NULL == finger_trail)
+     continue;
+
+   closest_peer = select_closest_peer (&my_identity,
+                                       &finger->finger_identity,
+                                       destination_finger_value,
+                                       finger_map_index);
+   if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer,
+                                             &finger->finger_identity))
+   {
+      memcpy (&successor->value, &finger->finger_identity, sizeof (uint64_t));
+      successor->trail_id = finger_trail->trail_id;
+      successor->next_hop = finger_trail->friend.id;
+      successor->next_destination = finger->finger_identity;
     }
   }
-  
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (friend_iter);   
-  
-  qsort (&all_known_peers, size, sizeof (struct Sorting_List), &compare_peer_id);
-  
-  /* search value in all_known_peers array. */
-  successor = find_closest_successor (all_known_peers, value, size);
-  
-  if (successor->type == MY_ID)
-  {
-    return NULL;
-  }
-  else if (successor->type == FRIEND)
-  {
-    struct FriendInfo *target_friend;
-    target_friend = (struct FriendInfo *)successor->data;
-    memcpy (current_destination, &(target_friend->id), sizeof (struct GNUNET_PeerIdentity));
-    return current_destination;
-  }
-  else if (successor->type == FINGER)
-  {
-    struct GNUNET_PeerIdentity *next_hop;
-    struct FingerInfo *finger;
-    struct TrailPeerList *iterator;
-    iterator = GNUNET_malloc (sizeof (struct TrailPeerList));
-    finger = successor->data;
-    iterator = finger->head;
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    memcpy (next_hop, &(iterator->peer), sizeof (struct GNUNET_PeerIdentity));
-    memcpy (current_destination, &(finger->finger_identity), sizeof (struct GNUNET_PeerIdentity));
-    memcpy (current_source, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-    return next_hop;
-  }
-  else
-  {
-    GNUNET_assert (0);
-    return NULL;
-  }
-}
 
+  next_destination = &successor->next_destination;
+  new_intermediate_trail_id = &successor->trail_id;
+  next_hop = &successor->next_hop;
 
-/** FIXME: by default I keep current_source, and destination as my own id.
- * in case we find a finger then we update current_source in the 
- * find_successor message. 
- * Construct a Put message and send it to target_peer. 
- * @param key Key for the content  
- * @param data Content to store
- * @param data_size Size of content @a data in bytes
+  return next_hop;
+}
+
+/**
+ * Construct a Put message and send it to target_peer.
+ * @param key Key for the content
  * @param block_type Type of the block
  * @param options Routing options
  * @param desired_replication_level Desired replication count
- * @param expiration_time When does the content expire
- * @param current_destination 
- * @param current_source 
+ * @param current_destination Next current destination which will get this message.
+ * @param current_source Source for @a current_destination
  * @param target_peer Peer to which this message will be forwarded.
  * @param hop_count Number of hops traversed so far.
  * @param put_path_length Total number of peers in @a put_path
- * @param put_path Number of peers traversed so far 
+ * @param put_path Number of peers traversed so far
+ * @param expiration_time When does the content expire
+ * @param data Content to store
+ * @param data_size Size of content @a data in bytes
  */
 void
 GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
-                         const void *data, size_t data_size,
                          enum GNUNET_BLOCK_Type block_type,
                          enum GNUNET_DHT_RouteOption options,
                          uint32_t desired_replication_level,
-                         struct GNUNET_TIME_Absolute expiration_time,
-                         struct GNUNET_PeerIdentity *current_destination,
-                         struct GNUNET_PeerIdentity *current_source,
+                         struct GNUNET_PeerIdentity current_destination,
+                         struct GNUNET_PeerIdentity current_source,
                          struct GNUNET_PeerIdentity *target_peer,
                          uint32_t hop_count,
                          uint32_t put_path_length,
-                         struct GNUNET_PeerIdentity *put_path)
+                         struct GNUNET_PeerIdentity *put_path,
+                         struct GNUNET_TIME_Absolute expiration_time,
+                         const void *data, size_t data_size)
 {
-  struct PeerPutMessage *ppm;
-  struct P2PPendingMessage *pending;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *pp;
-  size_t msize;
-  
-  msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
-          sizeof (struct PeerPutMessage);
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
-  {
-    put_path_length = 0;
-    msize = data_size + sizeof (struct PeerPutMessage);
-  }
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
-  {
-    GNUNET_break (0);
-    return;
-  }
-  
-  /* This is the first call made from clients file. So, we should search for the
-     target_friend. */
-  if (NULL == target_peer)
-  {
-    uint64_t key_value;
-    struct GNUNET_PeerIdentity *next_hop;
-    
-    memcpy (&key_value, key, sizeof (uint64_t));
-    next_hop = find_successor (key_value, current_destination, current_source);
-    if (NULL == next_hop) /* I am the destination do datacache_put */
-    {
-      GDS_DATACACHE_handle_put (expiration_time, key, put_path_length, put_path,
-                                block_type, data_size, data);
-      return;
-    }
-    else
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);   
-  }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
-  pending->timeout = expiration_time;
-  ppm = (struct PeerPutMessage *) &pending[1];
-  pending->msg = &ppm->header;
-  ppm->header.size = htons (msize);
-  ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
-  ppm->options = htonl (options);
-  ppm->block_type = htonl (block_type);
-  ppm->hop_count = htonl (hop_count + 1);
-  ppm->desired_replication_level = htonl (desired_replication_level);
-  ppm->put_path_length = htonl (put_path_length);
-  ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
-  ppm->key = *key;
-  ppm->current_destination = *current_destination;
-  ppm->current_source = *current_source;
-  pp = (struct GNUNET_PeerIdentity *) &ppm[1];
-  if (put_path_length != 0)
-  {
-    memcpy (pp, put_path,
-            sizeof (struct GNUNET_PeerIdentity) * put_path_length);
-  }
-  memcpy (&pp[put_path_length], data, data_size);
-  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
-  target_friend->pending_count++;
-  process_friend_queue (target_friend);
-}
-
 
+}
 
-/** FIXME: by default I keep current_source, and destination as my own id.
- * in case we find a finger then we update current_source in the 
- * find_successor message. 
- * Construct a Get message and send it to target_peer. 
- * @param key Key for the content  
+/**
+ * Construct a Get message and send it to target_peer.
+ * @param key Key for the content
  * @param block_type Type of the block
  * @param options Routing options
  * @param desired_replication_level Desired replication count
- * @param expiration_time When does the content expire
- * @param current_destination 
- * @param current_source 
+ * @param current_destination Next current destination which will get this message.
+ * @param current_source Source for @a current_destination
  * @param target_peer Peer to which this message will be forwarded.
  * @param hop_count Number of hops traversed so far.
- * @param put_path_length Total number of peers in @a put_path
- * @param put_path Number of peers traversed so far 
+ * @param data Content to store
+ * @param data_size Size of content @a data in bytes
+ * @param get_path_length Total number of peers in @a get_path
+ * @param get_path Number of peers traversed so far
  */
 void
 GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
                          enum GNUNET_BLOCK_Type block_type,
                          enum GNUNET_DHT_RouteOption options,
                          uint32_t desired_replication_level,
-                         struct GNUNET_PeerIdentity *current_destination,
-                         struct GNUNET_PeerIdentity *current_source,
+                         struct GNUNET_PeerIdentity current_destination,
+                         struct GNUNET_PeerIdentity current_source,
                          struct GNUNET_PeerIdentity *target_peer,
                          uint32_t hop_count,
                          uint32_t get_path_length,
                          struct GNUNET_PeerIdentity *get_path)
 {
-  struct PeerGetMessage *pgm;
-  struct P2PPendingMessage *pending;
+
+}
+
+
+/**
+ * Send the get result to requesting client.
+ * @param key Key of the requested data.
+ * @param type Block type
+ * @param target_peer Next peer to forward the message to.
+ * @param source_peer Peer which has the data for the key.
+ * @param put_path_length Number of peers in @a put_path
+ * @param put_path Path taken to put the data at its stored location.
+ * @param get_path_length Number of peers in @a get_path
+ * @param get_path Path taken to reach to the location of the key.
+ * @param expiration When will this result expire?
+ * @param data Payload to store
+ * @param data_size Size of the @a data
+ */
+void
+GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
+                                enum GNUNET_BLOCK_Type type,
+                                struct GNUNET_PeerIdentity *target_peer,
+                                struct GNUNET_PeerIdentity *source_peer,
+                                unsigned int put_path_length,
+                                const struct GNUNET_PeerIdentity *put_path,
+                                unsigned int get_path_length,
+                                struct GNUNET_PeerIdentity *get_path,
+                                struct GNUNET_TIME_Absolute expiration,
+                                const void *data, size_t data_size)
+{
+
+}
+
+
+/**
+ * Randomly choose one of your friends (which is not congested and have not crossed
+ * trail threshold) from the friends_peer map
+ * @return Friend Randomly chosen friend.
+ *         NULL in case friend peermap is empty, or all the friends are either
+ *              congested or have crossed trail threshold.
+ */
+static struct FriendInfo *
+select_random_friend ()
+{
+  unsigned int current_size;
+  uint32_t index;
+  unsigned int j = 0;
+  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
+  struct GNUNET_PeerIdentity key_ret;
+  struct FriendInfo *friend;
+
+  current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
+  if (0 == current_size)
+    return NULL;
+
+  index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
+  iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+
+  for (j = 0; j < index ; j++)
+    GNUNET_assert (GNUNET_YES ==
+                   GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL));
+  do
+  {
+    if (j == current_size)
+    {
+      j = 0;
+      GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
+      iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+
+    }
+    GNUNET_assert (GNUNET_YES ==
+                GNUNET_CONTAINER_multipeermap_iterator_next (iter,
+                                                             &key_ret,
+                                                             (const void **)&friend));
+
+
+    if ((TRAILS_THROUGH_FRIEND_THRESHOLD > friend->trails_count) &&
+        (0 == GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us))
+    {
+      break;
+    }
+    friend = NULL;
+    j++;
+  } while (j != index);
+
+  GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
+  return friend;
+}
+
+
+/**
+ * FIXME: pass current_search_finger_index as parameter
+ * Compute finger_identity to which we want to setup the trail
+ * @return finger_identity
+ */
+static uint64_t
+compute_finger_identity()
+{
+  uint64_t my_id64;
+
+  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  my_id64 = GNUNET_ntohll (my_id64);
+  return (my_id64 + (unsigned long) pow (2, current_search_finger_index));
+}
+
+
+/**
+ * Compute immediate predecessor identity in the network.
+ * @return peer identity of immediate predecessor.
+ */
+static uint64_t
+compute_predecessor_identity()
+{
+  uint64_t my_id64;
+
+  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  my_id64 = GNUNET_ntohll (my_id64);
+  return (my_id64 -1);
+}
+
+
+/*
+ * Choose a random friend and start looking for the trail to reach to
+ * finger identity through this random friend.
+ *
+ * @param cls closure for this task
+ * @param tc the context under which the task is running
+ */
+static void
+send_find_finger_trail_message (void *cls,
+                                const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
   struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *gp;
-  size_t msize;
-  
-  msize = sizeof (struct PeerGetMessage) + 
-          (get_path_length * sizeof (struct GNUNET_PeerIdentity));
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  struct GNUNET_TIME_Relative next_send_time;
+  struct GNUNET_HashCode trail_id;
+  unsigned int finger_map_index;
+  uint64_t finger_identity;
+
+  next_send_time.rel_value_us =
+      DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
+      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
+  find_finger_trail_task =
+      GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_finger_trail_message,
+                                    NULL);
+
+  target_friend = select_random_friend ();
+  if (NULL == target_friend)
   {
-    GNUNET_break (0);
     return;
   }
-  
-  if (NULL == target_peer)
+
+  if (PREDECESSOR_FINGER_ID == current_search_finger_index)
   {
-    /* This is the first call from client file, we need to search for next_hop*/
-    struct GNUNET_PeerIdentity *next_hop;
-    uint64_t key_value;
-    
-    memcpy (&key_value, key, sizeof (struct GNUNET_PeerIdentity));
-    next_hop = find_successor (key_value, current_destination, current_source);
-    if (NULL == next_hop) /* I am the destination do datacache_put */
+    finger_identity = compute_predecessor_identity();
+  }
+  else
+  {
+    finger_identity = compute_finger_identity();
+  }
+
+  finger_map_index = current_search_finger_index;
+
+  GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
+                              &trail_id, sizeof (trail_id));
+  GDS_NEIGHBOURS_send_trail_setup (my_identity, finger_identity,
+                                   target_friend->id, target_friend, 0, NULL,
+                                   finger_map_index, trail_id, NULL);
+}
+
+
+/**
+ * In case there are already maximum number of possible trails to reach to a
+ * finger, then check if the new trail's length is lesser than any of the
+ * existing trails.
+ * If yes then replace that old trail by new trail.
+ *
+ * Note: Here we are taking length as a parameter to choose the best possible
+ * trail, but there could be other parameters also like:
+ * 1. duration of existence of a trail - older the better.
+ * 2. if the new trail is completely disjoint than the
+ *    other trails, then may be choosing it is better.
+ *
+ * @param existing_finger
+ * @param new_finger_trail
+ * @param new_finger_trail_length
+ * @param new_finger_trail_id
+ */
+static void
+select_and_replace_trail (struct FingerInfo *existing_finger,
+                          struct GNUNET_PeerIdentity *new_trail,
+                          unsigned int new_trail_length,
+                          struct GNUNET_HashCode new_trail_id)
+{
+  struct TrailList *trail_list_iterator;
+  unsigned int largest_trail_length;
+  unsigned int largest_trail_index;
+  struct Trail *trail_element;
+  unsigned int i;
+
+  largest_trail_length = new_trail_length;
+  largest_trail_index = MAXIMUM_TRAILS_PER_FINGER + 1;
+
+  GNUNET_assert (MAXIMUM_TRAILS_PER_FINGER == existing_finger->trails_count);
+
+  for (i = 0; i < existing_finger->trails_count; i++)
+  {
+    trail_list_iterator = &existing_finger->trail_list[i];
+    if (trail_list_iterator->trail_length > largest_trail_length)
     {
-      GDS_DATACACHE_handle_get (key,block_type, NULL, 0, 
-                                NULL, 0, 1, &my_identity, NULL,&my_identity);
+      largest_trail_length = trail_list_iterator->trail_length;
+      largest_trail_index = i;
     }
-    else
+  }
+
+  if (largest_trail_index == (MAXIMUM_TRAILS_PER_FINGER + 1))
+  {
+    // tear down new trail: it's not better than the existing ones
+    return;
+  }
+
+  /* Send trail teardown message across the replaced trail. */
+  struct TrailList *replace_trail = &existing_finger->trail_list[largest_trail_index];
+  struct FriendInfo *target_friend =
+      GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                         &replace_trail->trail_head->peer);
+
+  GDS_NEIGHBOURS_send_trail_teardown (my_identity,
+                                      existing_finger->finger_identity,
+                                      replace_trail->trail_id,
+                                      GDS_ROUTING_SRC_TO_DEST, target_friend);
+  /* Free the trail. */
+  while (NULL != (trail_element = replace_trail->trail_head))
+  {
+    GNUNET_CONTAINER_DLL_remove (replace_trail->trail_head,
+                                 replace_trail->trail_tail, trail_element);
+    GNUNET_free (trail_element);
+  }
+
+  /* Add new trial at that location. */
+  i = 0;
+  while (i < new_trail_length)
+  {
+    struct Trail *element = GNUNET_new (struct Trail);
+    element->peer = new_trail[i];
+
+    GNUNET_CONTAINER_DLL_insert_tail (replace_trail->trail_head,
+                                      replace_trail->trail_tail,
+                                      element);
+  }
+}
+
+
+/**
+ * Check if the new trail to reach to finger is unique or do we already have
+ * such a trail present for finger.
+ * @param existing_finger Finger identity
+ * @param new_trail New trail to reach @a existing_finger
+ * @param trail_length Total number of peers in new_trail.
+ * @return #GNUNET_YES if the new trail is unique
+ *         #GNUNET_NO if same trail is already present.
+ */
+static int
+is_new_trail_unique (struct FingerInfo *existing_finger,
+                     struct GNUNET_PeerIdentity *new_trail,
+                     unsigned int trail_length)
+{
+  struct TrailList *trail_list_iterator;
+  struct Trail *trail_element;
+  int i;
+  int j;
+  int trail_unique = GNUNET_NO;
+
+  for (i = 0; i < existing_finger->trails_count; i++)
+  {
+    trail_list_iterator = &existing_finger->trail_list[i];
+    if (trail_list_iterator->trail_length != trail_length)
+      continue;
+    trail_element = trail_list_iterator->trail_head;
+    for (j = 0; j < trail_list_iterator->trail_length; j++)
     {
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (&new_trail[j],
+                                                &trail_element->peer))
+      {
+        trail_unique = GNUNET_YES;
+        break;
+      }
     }
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
-  pending->importance = 0;    /* FIXME */
-  pgm = (struct PeerGetMessage *) &pending[1];
-  pending->msg = &pgm->header;
-  pgm->header.size = htons (msize);
-  pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
-  pgm->get_path_length = htonl (get_path_length);
-  pgm->key = *key;
-  pgm->current_destination = *current_destination;
-  pgm->current_source = *current_source;
-  pgm->hop_count = htonl (hop_count + 1);
-  
-  gp = (struct GNUNET_PeerIdentity *) &pgm[1];
-  memcpy (gp, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
-  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
-  target_friend->pending_count++;
-  process_friend_queue (target_friend);
+  return trail_unique;
 }
 
 
 /**
- * Send the get result to requesting client.
- * @param expiration When will this result expire?
- * @param key Key of the requested data.
- * @param put_path_length Number of peers in @a put_path
- * @param put_path Path taken to put the data at its stored location.
- * @param type Block type
- * @param data_size Size of the @a data 
- * @param data Payload to store
- * @param get_path Path taken to reach to the location of the key.
- * @param get_path_length Number of peers in @a get_path
- * @param next_hop Next peer to forward the message to. 
- * @param source_peer Peer which has the data for the key.
+ * Add a new trail to existing finger.
+ * @param existing_finger
+ * @param new_finger_trail
+ * @param new_finger_trail_length
+ * @param new_finger_trail_id
  */
-void 
-GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
-                                const struct GNUNET_HashCode *key,
-                                unsigned int put_path_length,
-                                const struct GNUNET_PeerIdentity *put_path,
-                                enum GNUNET_BLOCK_Type type, size_t data_size,
-                                const void *data,
-                                struct GNUNET_PeerIdentity *get_path,
-                                unsigned int get_path_length,
-                                struct GNUNET_PeerIdentity *next_hop,
-                                struct GNUNET_PeerIdentity *source_peer)
+static void
+add_new_trail (struct FingerInfo *existing_finger,
+               struct GNUNET_PeerIdentity *new_trail,
+               unsigned int new_trail_length,
+               struct GNUNET_HashCode new_trail_id)
 {
-  struct PeerGetResultMessage *get_result;
-  struct GNUNET_PeerIdentity *get_result_path;
-  struct GNUNET_PeerIdentity *pp;
-  struct P2PPendingMessage *pending;
-  struct FriendInfo *target_friend;
-  int current_path_index;
-  size_t msize;
-  
-  msize = get_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
-          sizeof (struct PeerPutMessage);
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  struct TrailList *trail_list_iterator;
+  struct FriendInfo *first_friend;
+  int i;
+
+  if (GNUNET_NO == is_new_trail_unique (existing_finger, new_trail,
+                                        new_trail_length))
   {
-    GNUNET_break (0);
     return;
   }
-  
-  current_path_index = search_my_location(get_path);
-  if (0 == current_path_index)
+
+  // FIXME checking trail_head is NOT a valid way to verify an open slot
+  for (i = 0; existing_finger->trail_list[i].trail_head != NULL; i++)
+    GNUNET_assert (i < MAXIMUM_TRAILS_PER_FINGER);
+
+  trail_list_iterator = &existing_finger->trail_list[i];
+
+  if (new_trail_length > 0)
+    first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                      &new_trail[0]);
+  else
+    first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                      &(existing_finger->finger_identity));
+  first_friend->trails_count++;
+  trail_list_iterator->first_friend_trail_count = first_friend->trails_count;
+  trail_list_iterator->trail_length = new_trail_length;
+
+  for (i = 0; i < new_trail_length; i++)
   {
-    FPRINTF (stderr,_("\nSUPU %s, %s, %d"),__FILE__, __func__,__LINE__);
-    GDS_CLIENTS_handle_reply (expiration, key, get_path_length, get_path, put_path_length,
-                              put_path, type, data_size, data);
+    struct Trail *element;
+    element = GNUNET_new (struct Trail);
+
+    element->peer = new_trail[i];
+    GNUNET_CONTAINER_DLL_insert_tail (trail_list_iterator->trail_head,
+                                      trail_list_iterator->trail_tail,
+                                      element);
+  }
+  existing_finger->trails_count++;
+}
+
+
+/**
+ * Send trail teardown message on all trails associated with finger.
+ * @param finger_to_be_removed
+ */
+static void
+send_trail_teardown (struct FingerInfo *finger)
+{
+  struct TrailList *trail_list_iterator;
+  struct FriendInfo *target_friend;
+  int i;
+
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity, &my_identity)
+     || (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                    &finger->finger_identity)))
     return;
+
+  for (i = 0; i < finger->trails_count; i++)
+  {
+    trail_list_iterator = &finger->trail_list[i];
+    if (trail_list_iterator->trail_length > 0)
+    {
+      target_friend =
+              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                 &trail_list_iterator->trail_head->peer);
+      // check target_friend
+      GDS_NEIGHBOURS_send_trail_teardown (my_identity, finger->finger_identity,
+                                          trail_list_iterator->trail_id,
+                                          GDS_ROUTING_SRC_TO_DEST,
+                                          target_friend);
+    }
   }
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
-  pending->importance = 0;   
-  get_result = (struct PeerGetResultMessage *)&pending[1];
-  pending->msg = &get_result->header;
-  get_result->header.size = htons (msize);
-  get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT);
-  get_result->key = *key;
-  memcpy (&(get_result->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  get_result->expiration_time = expiration;
-  
-  get_result_path = (struct GNUNET_PeerIdentity *)&get_result[1];
-  memcpy (get_result_path, get_path,
-          sizeof (struct GNUNET_PeerIdentity) * get_path_length);
-  memcpy (&get_result_path[get_path_length], data, data_size);
-  /* FIXME: Is this correct? */
-  pp = (struct GNUNET_PeerIdentity *)&get_result_path[1];
-  memcpy (pp, put_path,sizeof (struct GNUNET_PeerIdentity) * put_path_length);
-  
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
-  target_friend->pending_count++;
-  process_friend_queue (target_friend);
 }
 
 
 /**
- * Send tral rejection message
- * @param source_peer Source peer which wants to set up the trail.
- * @param finger_identity Finger identity to which it want to setup the trail.
- * @param congested_peer Peer which has send trail rejection message
- * @param next_hop Peer to which this message should be forwarded.
- * @param finger_map_index
- * @param trail_peer_list
- * @param trail_length
+ * Decrement the trail count of the first friend to reach the finger
+ * In case finger is the friend, then decrement its trail count.
+ * @param finger
  */
-void
-GDS_NEIGHBOURS_send_trail_rejection_message(struct GNUNET_PeerIdentity *source_peer,
-                                            uint64_t finger_identity,
-                                            struct GNUNET_PeerIdentity *congested_peer,
-                                            const struct GNUNET_PeerIdentity *next_hop,
-                                            unsigned int finger_map_index,
-                                            struct GNUNET_PeerIdentity *trail_peer_list,
-                                            unsigned int trail_length)
+static void
+decrement_friend_trail_count (struct FingerInfo *finger)
 {
-  struct PeerTrailRejectionMessage *trail_rejection;
-  struct GNUNET_PeerIdentity *trail_list;
-  struct P2PPendingMessage *pending;
+  struct TrailList *trail_list_iterator;
   struct FriendInfo *target_friend;
-  size_t msize;
-  
-  msize =  sizeof (struct PeerTrailRejectionMessage);
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
-  pending->importance = 0;    /* FIXME */
-  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  trail_rejection = (struct PeerTrailRejectionMessage *) &pending[1]; 
-  pending->msg = &trail_rejection->header;
-  trail_rejection->header.size = htons (msize);
-  trail_rejection->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP);
-  memcpy (&(trail_rejection->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_rejection->congested_peer), congested_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_rejection->finger_identity), &finger_identity, sizeof (uint64_t));
-  trail_rejection->finger_map_index = htonl(finger_map_index);
-  trail_rejection->trail_length = htonl (trail_length);
-  
-  trail_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
-  memcpy (trail_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
-  target_friend->pending_count++;
-  process_friend_queue (target_friend);
+  int i = 0;
+
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                            &my_identity))
+    return;
+
+  for (i = 0; i < finger->trails_count; i++)
+  {
+    trail_list_iterator = &finger->trail_list[i];
+    if (trail_list_iterator->trail_length > 0)
+      target_friend =
+              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                 &trail_list_iterator->trail_head->peer);
+    else
+     target_friend =
+              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                 &finger->finger_identity);
+
+    // check target_friend for NULL
+    target_friend->trails_count--;
+    trail_list_iterator->first_friend_trail_count--;
+  }
+  return;
 }
 
 
 /**
- * 
- * @param cls
- * @param peer
- * @param message
- * @return 
+ * Free finger and its trail.
+ * @param finger Finger to be freed.
  */
-static int 
-handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
-                    const struct GNUNET_MessageHeader *message)
+static void
+free_finger (struct FingerInfo *finger)
 {
-  struct PeerPutMessage *put;
-  struct GNUNET_PeerIdentity *put_path;
-  struct GNUNET_HashCode test_key;
-  enum GNUNET_DHT_RouteOption options;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
-  struct GNUNET_PeerIdentity *next_hop;
-  void *payload;
-  size_t msize;
-  uint32_t putlen;
-  size_t payload_size;
-  uint64_t key_value;
-  
-  msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerPutMessage))
+  struct TrailList *trail_list_iterator;
+  struct Trail *trail_element;
+  unsigned int i;
+
+  for (i = 0; i < finger->trails_count; i++)
   {
-    GNUNET_break_op (0);
+    trail_list_iterator = &finger->trail_list[i];
+    while (NULL != (trail_element = trail_list_iterator->trail_head))
+    {
+      GNUNET_CONTAINER_DLL_remove (trail_list_iterator->trail_head,
+                                   trail_list_iterator->trail_tail,
+                                   trail_element);
+      GNUNET_free (trail_element);
+    }
+  }
+  GNUNET_free (finger);
+}
+
+
+/**
+ * FIXME: merge into finger_table_add
+ * FIXME: leave as simple a check
+ * Check if new finger is closer than existing_finger. If both new finger and
+ * existing finger are same then we may add a new trail (if there is space)
+ * or choose the best trail among existing trails and new trails.
+ * @param existing_finger Finger present in finger_peermap at @a finger_map_index
+ *                        or NULL if none
+ * @param new_finger_identity Peer identity of new finger.
+ * FIXME: all the following params *should* not be necessary
+ * @param new_finger_trail Trail to reach from source to new_finger.
+ * @param new_finger_trail_length Total number of peers in @a new_finger_trail.
+ * @param trail_id Unique identifier of trail.
+ * @param finger_map_index Index in finger map.
+ * @return #GNUNET_YES if the new finger is closest.
+ *         #GNUNET_NO either new_finger and existing_finger are same, or
+ *                    existing_finger is closest.
+ */
+static int
+is_new_finger_closest (struct FingerInfo *existing_finger,
+                       struct GNUNET_PeerIdentity new_finger_identity,
+                       struct GNUNET_PeerIdentity *new_finger_trail,
+                       unsigned int new_finger_trail_length,
+                       struct GNUNET_HashCode new_finger_trail_id,
+                       unsigned int finger_map_index)
+{
+  struct GNUNET_PeerIdentity *closest_peer;
+  uint64_t finger_identity_value;
+  uint64_t my_id64;
+
+  if (NULL == existing_finger)
     return GNUNET_YES;
+
+  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
+                                            &new_finger_identity))
+  {
+    if (PREDECESSOR_FINGER_ID == finger_map_index)
+      finger_identity_value = my_id64 - 1;
+    else
+      finger_identity_value = my_id64 + (unsigned long) pow (2, finger_map_index);
+    closest_peer = select_closest_peer (&existing_finger->finger_identity,
+                                        &new_finger_identity,
+                                        finger_identity_value, finger_map_index);
+
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&new_finger_identity, closest_peer))
+    {
+      GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
+                                                           &new_finger_identity));
+
+      send_trail_teardown (existing_finger);
+      decrement_friend_trail_count (existing_finger);
+      free_finger (existing_finger);
+      return GNUNET_YES;
+    }
   }
-  
-  put = (struct PeerPutMessage *) message;
-  putlen = ntohl (put->put_path_length);
-   
-  if ((msize <
-       sizeof (struct PeerPutMessage) +
-       putlen * sizeof (struct GNUNET_PeerIdentity)) ||
-      (putlen >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  else
   {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
+                                              &my_identity))
+    {
+      return GNUNET_NO;
+    }
+    if (NULL ==
+        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                            &(existing_finger->finger_identity)))
+    {
+      if (existing_finger->trails_count < MAXIMUM_TRAILS_PER_FINGER)
+        add_new_trail (existing_finger, new_finger_trail,
+                        new_finger_trail_length, new_finger_trail_id);
+      else
+        select_and_replace_trail (existing_finger, new_finger_trail,
+                                  new_finger_trail_length, new_finger_trail_id);
+    }
   }
-  
-  current_destination = put->current_destination;
-  current_source = put->current_source;
-  put_path = (struct GNUNET_PeerIdentity *) &put[1];
-  payload = &put_path[putlen];
-  options = ntohl (put->options);
-  payload_size = msize - (sizeof (struct PeerPutMessage) + 
-                          putlen * sizeof (struct GNUNET_PeerIdentity));
-  
-  switch (GNUNET_BLOCK_get_key (GDS_block_context, ntohl (put->block_type),
-                                payload, payload_size, &test_key))
+  return GNUNET_NO;
+}
+
+
+/**
+ * Add a new entry in finger hashmap at finger_map_index
+ * @param finger_identity Peer Identity of new finger
+ * @param finger_trail Trail to reach from me to finger (excluding both end points).
+ * @param finger_trail_length Total number of peers in @a finger_trail.
+ * @param trail_id Unique identifier of the trail.
+ * @param finger_map_index Index in finger hashmap.
+ * @return #GNUNET_OK if new entry is added
+ *         #GNUNET_NO -- FIXME: need to check what value does hahsmap put
+ *                       returns on failure.
+ */
+static int
+add_new_entry (struct GNUNET_PeerIdentity finger_identity,
+               struct GNUNET_PeerIdentity *finger_trail,
+               unsigned int finger_trail_length,
+               struct GNUNET_HashCode trail_id,
+               unsigned int finger_map_index)
+{
+  struct FingerInfo *new_entry;
+  struct FriendInfo *first_trail_hop;
+  struct TrailList *first_trail;
+  int i = 0;
+
+  new_entry = GNUNET_new (struct FingerInfo);
+  new_entry->finger_identity = finger_identity;
+  new_entry->finger_map_index = finger_map_index;
+  new_entry->trails_count = 1;
+
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
   {
-    case GNUNET_YES:
-      if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
+    if (finger_trail_length > 0)
+    {
+      first_trail_hop = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                           &finger_trail[0]);
+    }
+    else
+    {
+      first_trail_hop = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                           &finger_identity);
+    }
+
+    first_trail_hop->trails_count++;
+    first_trail = &new_entry->trail_list[0];
+    first_trail->first_friend_trail_count = first_trail_hop->trails_count;
+
+    while (i < finger_trail_length)
+    {
+      struct Trail *element = GNUNET_new (struct Trail);
+
+      element->next = NULL;
+      element->prev = NULL;
+      element->peer = finger_trail[i];
+      GNUNET_CONTAINER_DLL_insert_tail (first_trail->trail_head,
+                                        first_trail->trail_tail,
+                                        element);
+      i++;
+    }
+  }
+
+  return GNUNET_CONTAINER_multihashmap32_put (finger_hashmap,
+                                              new_entry->finger_map_index,
+                                              new_entry,
+                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
+}
+
+
+/**
+ * Scan the trail to check if there is any other friend in the trail other than
+ * first hop. If yes then shortcut the trail, send trail compression message to
+ * peers which are no longer part of trail and send back the updated trail
+ * and trail_length to calling function.
+ * @param finger_identity Finger whose trail we will scan.
+ * @param finger_trail [in, out] Trail to reach from source to finger,
+ * @param finger_trail_length  Total number of peers in original finger_trail.
+ * @param finger_trail_id Unique identifier of the finger trail.
+ * @return updated trail length in case we shortcut the trail, else original
+ *         trail length.
+ */
+static int
+scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
+                         struct GNUNET_PeerIdentity *trail,
+                         unsigned int trail_length,
+                         struct GNUNET_HashCode trail_id)
+{
+  struct FriendInfo *target_friend;
+  int i;
+
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
+  {
+    return 0;
+  }
+
+  if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_identity))
+  {
+    if (trail_length > 0)
+    {
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                       &trail[0]);
+      GDS_NEIGHBOURS_send_trail_compression (my_identity, finger_identity,
+                                           trail_id, finger_identity,
+                                           target_friend);
+      trail = NULL;
+    }
+    return 0;
+  }
+
+  for (i = trail_length - 1; i > 0; i--)
+  {
+    if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &trail[i]))
+    {
+      struct FriendInfo *target_friend;
+      int j = 0;
+
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                         &trail[0]);
+      GDS_NEIGHBOURS_send_trail_compression (my_identity, finger_identity,
+                                             trail_id, trail[i],
+                                             target_friend);
+
+      // FIXME WARNING WARNING WARNING rewrite!!! consider directly creating a
+      // struct TrailList (current) // struct Trial (after renaming).
+
+      /* Copy the trail from index i to index trail_length -1 and change
+       trail length and return */
+      while (i < trail_length)
       {
-        char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
-        GNUNET_break_op (0);
-        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
-                    "PUT with key `%s' for block with key %s\n",
-                     put_s, GNUNET_h2s_full (&test_key));
-        GNUNET_free (put_s);
-        return GNUNET_YES;
+        memcpy (&trail[j], &trail[i], sizeof(struct GNUNET_PeerIdentity));
+        j++;
+        i++;
       }
-    break;
-    case GNUNET_NO:
-      GNUNET_break_op (0);
-      return GNUNET_YES;
-    case GNUNET_SYSERR:
-      /* cannot verify, good luck */
+      trail_length = j+1;
       break;
+    }
   }
-  
-   if (ntohl (put->block_type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
-  {
-    switch (GNUNET_BLOCK_evaluate (GDS_block_context,
-                                   ntohl (put->block_type),
-                                   NULL,    /* query */
-                                   NULL, 0, /* bloom filer */
-                                   NULL, 0, /* xquery */
-                                   payload, payload_size))
+  return trail_length;
+}
+
+
+/**
+ * Send verify successor message to your successor on all trails to reach
+ * the successor.
+ * @param successor My current successor
+ */
+static void
+send_verify_successor_message (struct FingerInfo *successor)
+{
+  struct TrailList *trail_list_iterator;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity next_hop;
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity *trail;
+  unsigned int trail_length;
+  int i;
+  int j;
+
+  for (i = 0; i < MAXIMUM_TRAILS_PER_FINGER; i++)
+  {
+    trail_list_iterator = &successor->trail_list[i];
+
+//      FIXME check if this entry in the trail list is valid!
+//     if (NULL == trail_list_iterator->SOMETHING)
+//       continue;
+
+    if (trail_list_iterator->trail_length > 0)
     {
-    case GNUNET_BLOCK_EVALUATION_OK_MORE:
-    case GNUNET_BLOCK_EVALUATION_OK_LAST:
-      break;
+      struct Trail *element;
+
+      trail_length = trail_list_iterator->trail_length;
+      trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity)
+                             * trail_length);
+      element = trail_list_iterator->trail_head;
+      for (j = 0; j < trail_length; j++, element = element->next)
+        trail[j] = element->peer;
+      next_hop = trail_list_iterator->trail_head->peer;
+    }
+    else
+    {
+      trail = NULL;
+      trail_length = 0;
+      next_hop = successor->finger_identity;
+    }
+    trail_id = trail_list_iterator->trail_id;
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+    // check friend for NULL
+    GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
+                                                  successor->finger_identity,
+                                                  trail_id, trail, trail_length,
+                                                  target_friend);
+    GNUNET_free_non_null (trail);
+  }
+}
 
-    case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
-    case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
-    case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
-    case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
-    case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
-    case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
-    default:
-      GNUNET_break_op (0);
-      return GNUNET_OK;
+
+/**
+ * Check if there is already an entry in finger peermap for given finger map index.
+ * If yes, then select the closest finger. If new and existing finger are same,
+ * the check if you can store more trails. If yes then add trail, else keep the best
+ * trails to reach to the finger. If the new finger is closest, add it.
+ * Then, update current_search_finger_index.
+ * @param new_finger_identity Peer Identity of new finger
+ * @param new_finger_trail Trail to reach the new finger
+ * @param new_finger_length Total number of peers in @a new_finger_trail.
+ * @param finger_map_index Index in finger peermap.
+ * @param new_finger_trail_id Unique identifier of @new_finger_trail.
+ * @return #GNUNET_YES if the new entry is added
+ *         #GNUNET_NO if new entry is not added, either it was discarded or
+ *                    it was same as existing finger at finger map index.
+ */
+static int
+finger_table_add (struct GNUNET_PeerIdentity new_finger_identity, // "finger_id"
+                  struct GNUNET_PeerIdentity *new_finger_trail, // "trail"
+                  unsigned int new_finger_trail_length,
+                  unsigned int finger_map_index,
+                  struct GNUNET_HashCode new_finger_trail_id)
+{
+  struct FingerInfo *existing_finger;
+  struct FingerInfo *successor;
+  unsigned int new_entry_added = GNUNET_NO;
+  int new_finger_updated_trail_length; // new_finger_trail_length
+
+  new_finger_updated_trail_length =
+       scan_and_compress_trail (new_finger_identity, new_finger_trail,
+                                new_finger_trail_length, new_finger_trail_id);
+
+  existing_finger = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
+                                                         finger_map_index);
+
+  if  (GNUNET_YES == is_new_finger_closest (existing_finger,
+                                            new_finger_identity,
+                                            new_finger_trail,
+                                            new_finger_updated_trail_length,
+                                            new_finger_trail_id, finger_map_index))
+  {
+    // send_destroy_existing_finger ...
+    // free_exisiting_finger ...
+    GNUNET_assert (GNUNET_YES == add_new_entry (new_finger_identity,
+                                                new_finger_trail,
+                                                new_finger_updated_trail_length,
+                                                new_finger_trail_id,
+                                                finger_map_index));
+    new_entry_added = GNUNET_YES;
+  }
+//   else if if_new_finger_equal () {
+//
+//   }
+//   else // existing finger is closest
+//   {
+//
+//   }
+
+  // FIXME move block to "update_succesor"
+  {
+    successor = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap, 0);
+    // WARNING FIXME check that current_search_finger_index does not go out of bounds
+    if (0 == finger_map_index)
+    {
+      current_search_finger_index = PREDECESSOR_FINGER_ID;
+
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &new_finger_identity))
+      {
+        send_verify_successor_message (successor);
+      }
     }
+    else if (0 == GNUNET_CRYPTO_cmp_peer_identity (&new_finger_identity,
+                                                  &(successor->finger_identity)))
+    {
+      current_search_finger_index = 0;
+    }
+    else
+      current_search_finger_index = current_search_finger_index - 1;
   }
-  
-   struct GNUNET_PeerIdentity pp[putlen + 1];
-  /* extend 'put path' by sender */
-  /* FIXME: Check what are we doing here? */
-  if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
+
+  return new_entry_added;
+}
+
+
+/**
+ * Core handler for P2P put messages.
+ * @param cls closure
+ * @param peer sender of the request
+ * @param message message
+ * @return #GNUNET_OK to keep the connection open,
+ *         #GNUNET_SYSERR to close it (signal serious error)
+ */
+static int
+handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
+                    const struct GNUNET_MessageHeader *message)
+{
+  return GNUNET_OK;
+}
+
+
+/**
+ * Core handler for p2p get requests.
+ *
+ * @param cls closure
+ * @param peer sender of the request
+ * @param message message
+ * @return #GNUNET_OK to keep the connection open,
+ *         #GNUNET_SYSERR to close it (signal serious error)
+ */
+static int
+handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
+                    const struct GNUNET_MessageHeader *message)
+{
+  return GNUNET_OK;
+}
+
+
+/**
+ * Core handler for get result
+ * @param cls closure
+ * @param peer sender of the request
+ * @param message message
+ * @return #GNUNET_OK to keep the connection open,
+ *         #GNUNET_SYSERR to close it (signal serious error)
+ */
+static int
+handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
+                           const struct GNUNET_MessageHeader *message)
+{
+  return GNUNET_OK;
+}
+
+
+/* Core handle for PeerTrailSetupMessage.
+ * @param cls closure
+ * @param message message
+ * @param peer peer identity this notification is about
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ */
+static int
+handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
+                            const struct GNUNET_MessageHeader *message)
+{
+  struct PeerTrailSetupMessage *trail_setup;
+  struct GNUNET_PeerIdentity *trail_peer_list;
+  struct GNUNET_PeerIdentity next_destination; // "local_best_known_destination"
+  struct GNUNET_PeerIdentity *current_destination;
+  struct GNUNET_PeerIdentity *next_hop;
+  struct GNUNET_PeerIdentity next_peer;
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity source;
+  uint64_t ultimate_destination_finger_value;
+  struct GNUNET_HashCode new_intermediate_trail_id;
+  //struct GNUNET_HashCode *intermediate_trail_id;
+  struct GNUNET_HashCode new_trail_id;
+  unsigned int finger_map_index;
+  uint32_t trail_length;
+  size_t msize;
+
+  msize = ntohs (message->size);
+  /* There are PeerId's appended to the end of the message! */
+  if (msize < sizeof (struct PeerTrailSetupMessage))
   {
-    memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
-    pp[putlen] = *peer;
-    putlen++;
+    GNUNET_break_op (0);
+    return GNUNET_YES;
   }
-  else
-    putlen = 0;
-  
-  memcpy (&key_value, &(put->key), sizeof (uint64_t));
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
+
+  trail_setup = (struct PeerTrailSetupMessage *) message;
+  trail_length = ntohl (trail_setup->trail_length); // (msize - sizeof (msg)) / sizeof(PI)
+  // if ((msize - sizeof (msg)) % sizeof(PI) != 0)
+  if ((msize != sizeof (struct PeerTrailSetupMessage) +
+       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
+       (trail_length >
+        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
   {
-     next_hop = GDS_ROUTING_search (&current_source, &current_destination, peer);
-     if (next_hop == NULL)
-     {
-       /* refer to handle_dht_p2p_trail_setup. */
-     }
+    GNUNET_break_op (0);
+    return GNUNET_OK;
+  }
+
+  trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_setup[1];
+  current_destination = &trail_setup->next_destination;
+  new_trail_id = trail_setup->new_trail_id;
+  ultimate_destination_finger_value = GNUNET_ntohll (trail_setup->ultimate_destination_finger);
+  source = trail_setup->source_peer;
+  finger_map_index = ntohl (trail_setup->finger_map_index);
+  //intermediate_trail_id = &trail_setup->intermediate_trail_id;
+  
+  if (GNUNET_YES == GDS_ROUTING_threshold_reached())
+  {
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+    GDS_NEIGHBOURS_send_trail_rejection (source, ultimate_destination_finger_value,
+                                         my_identity, finger_map_index,
+                                         trail_peer_list, trail_length,
+                                         new_trail_id, target_friend,
+                                         CONGESTION_TIMEOUT);
+    return GNUNET_OK;
+  }
+
+  next_hop = find_successor (ultimate_destination_finger_value, &next_destination,
+                             &new_intermediate_trail_id, finger_map_index);
+
+  /* Are we just a part of a trail towards a finger? */
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity(&my_identity, current_destination)))
+  {
+//    struct GNUNET_PeerIdentity *closest_peer;
+//     struct GNUNET_PeerIdentity *peer1 =
+//         GDS_ROUTING_get_next_hop (intermediate_trail_id,
+//                                   GDS_ROUTING_SRC_TO_DEST);
+    /* Is next_destination better than the original best_known_dest? */
+    // BIG FIXME START
+//     if (0 != GNUNET_CRYPTO_cmp_peer_identity (next_destination,
+//                                               current_destination))
+//     {
+//        closest_peer = select_closest_peer (peer1, next_hop,
+//                                            ultimate_destination_finger_value,
+//                                            finger_map_index);
+//     }
+//     if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer1, closest_peer) ||
+//         (0 == GNUNET_CRYPTO_cmp_peer_identity (peer1, next_hop)))
+//     {
+//       next_hop = peer1;
+//       next_destination = *current_destination;
+//       new_intermediate_trail_id = intermediate_trail_id;
+//     }
+    // BIG FIXME END
+  }
+
+  GNUNET_assert (NULL != next_hop);
+  /* Am I the final destination? */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))
+  {
+    if (0 == trail_length)
+      memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
+    else
+      memcpy (&next_peer, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
+    GDS_NEIGHBOURS_send_trail_setup_result (source,
+                                            my_identity,
+                                            target_friend, trail_length,
+                                            trail_peer_list,
+                                            finger_map_index, new_trail_id);
   }
   else
   {
-    next_hop = find_successor (key_value, &current_destination, &current_source); 
-  }
-  
-  if (NULL == next_hop) /* I am the final destination */
-  {
-    GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
-                              &(put->key),putlen, pp, ntohl (put->block_type), 
-                              payload_size, payload);
-     return GNUNET_YES;
+    struct GNUNET_PeerIdentity peer_list[trail_length + 1];
+
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+    peer_list[trail_length] = my_identity;
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+    GDS_NEIGHBOURS_send_trail_setup (source,
+                                     ultimate_destination_finger_value,
+                                     next_destination,
+                                     target_friend, trail_length + 1, peer_list,
+                                     finger_map_index, new_trail_id,
+                                     &new_intermediate_trail_id);
   }
-  else
-  {
-    GDS_CLIENTS_process_put (options,
-                              ntohl (put->block_type),
-                              ntohl (put->hop_count),
-                              ntohl (put->desired_replication_level),
-                              putlen, pp,
-                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
-                              &put->key,
-                              payload,
-                              payload_size);
-    
-    GDS_NEIGHBOURS_send_put (&put->key, payload, payload_size, 
-                             ntohl (put->block_type),ntohl (put->options),
-                             ntohl (put->desired_replication_level),
-                             GNUNET_TIME_absolute_ntoh (put->expiration_time),
-                             &current_destination, &current_source, next_hop,
-                             ntohl (put->hop_count), putlen, pp);
-     return GNUNET_YES;
-  }
-  return GNUNET_SYSERR;
+  return GNUNET_OK;
 }
 
 
 /**
- * Core handler for p2p get requests.
- *
- * @param cls closure
- * @param peer sender of the request
+ * Core handle for p2p trail construction result messages.
+ * @param closure
  * @param message message
- * @return #GNUNET_OK to keep the connection open,
- *         #GNUNET_SYSERR to close it (signal serious error)
+ * @param peer peer identity this notification is about
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
-                    const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
+                                  const struct GNUNET_MessageHeader *message)
 {
-  struct PeerGetMessage *get;
-  struct GNUNET_PeerIdentity *get_path;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
-  struct GNUNET_PeerIdentity *next_hop;
-  uint32_t get_length;
-  uint64_t key_value;
+  struct PeerTrailSetupResultMessage *trail_result;
+  struct GNUNET_PeerIdentity *trail_peer_list;
+  struct GNUNET_PeerIdentity destination_peer;
+  struct GNUNET_PeerIdentity finger_identity;
+  uint32_t trail_length;
+  uint32_t finger_map_index;
+  struct GNUNET_HashCode trail_id;
   size_t msize;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerGetMessage))
+  if (msize < sizeof (struct PeerTrailSetupResultMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  get = (struct PeerGetMessage *)message;
-  get_length = ntohl (get->get_path_length);
-  get_path = (struct GNUNET_PeerIdentity *)&get[1];
-  current_destination = get->current_destination;
-  current_source = get->current_source;
-  
-  if ((msize <
-       sizeof (struct PeerGetMessage) +
-       get_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (get_length >
+
+  trail_result = (struct PeerTrailSetupResultMessage *) message;
+
+  // calculate trail_length with message size, check for % 0
+  trail_length = ntohl (trail_result->trail_length);
+  if ((msize !=
+       sizeof (struct PeerTrailSetupResultMessage) +
+       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
+       (trail_length >
         GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
   {
     GNUNET_break_op (0);
-    return GNUNET_YES; 
+    return GNUNET_YES;
   }
-  
-  /* Add sender to get path */
-  struct GNUNET_PeerIdentity gp[get_length + 1];
-  memcpy (gp, get_path, get_length * sizeof (struct GNUNET_PeerIdentity));
-  gp[get_length + 1] = *peer;
-  get_length = get_length + 1;
-  
-  memcpy (&key_value, &(get->key), sizeof (uint64_t));
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
+
+  finger_map_index = htonl (trail_result->finger_map_index);
+  destination_peer = trail_result->destination_peer;
+  finger_identity = trail_result->finger_identity;
+  trail_id = trail_result->trail_id;
+  trail_peer_list = (struct GNUNET_PeerIdentity *) &trail_result[1];
+
+  // FIXME: check that trail_peer_list[my_index + 1] == peer or
+  // my_index == trail_length - 1 AND finger_identity == peer
+
+  /* Am I the one who initiated the query? */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&destination_peer,
+                                             &my_identity)))
   {
-     next_hop = GDS_ROUTING_search (&current_source, &current_destination, peer);
-     if (next_hop == NULL)
-     {
-       /* refer to handle_dht_p2p_trail_setup. */
-     }
+    finger_table_add (finger_identity, trail_peer_list,
+                      trail_length,
+                      finger_map_index, trail_id);
+    return GNUNET_YES;
   }
-  else
+
+  struct GNUNET_PeerIdentity next_hop;
+  struct FriendInfo *target_friend;
+  int my_index;
+
+  my_index = search_my_index(trail_peer_list, trail_length);
+  if (-1 == my_index)
   {
-    next_hop = find_successor (key_value, &current_destination, &current_source); 
+    GNUNET_break_op(0);
+    return GNUNET_SYSERR;
   }
-  
-  if (NULL == next_hop)
-  {
-    /* FIXME: Try to make this code also short and remove useless variables. */
-    struct GNUNET_PeerIdentity final_get_path[get_length+1];
-    memcpy (final_get_path, gp, get_length * sizeof (struct GNUNET_PeerIdentity));
-    memcpy (&final_get_path[get_length+1], &my_identity, sizeof (struct GNUNET_PeerIdentity));
-    get_length = get_length + 1;
-    struct GNUNET_PeerIdentity *next_hop;
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    memcpy (next_hop, &final_get_path[get_length-2], sizeof (struct GNUNET_PeerIdentity));
-    GDS_DATACACHE_handle_get (&(get->key),(get->block_type), NULL, 0, NULL, 0,
-                              get_length, final_get_path,next_hop, &my_identity);
 
-    return GNUNET_YES;
-  }
+
+  if (my_index == 0)
+    next_hop = trail_result->destination_peer;
   else
+    next_hop = trail_peer_list[my_index - 1];
+
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->destination_peer),
+                                               &(trail_result->finger_identity))))
   {
-    GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options, 
-                             get->desired_replication_level,&current_destination,
-                             &current_source, next_hop, 0,
-                             get_length, gp);
+    GDS_ROUTING_add (trail_id, next_hop, *peer);
   }
-  return GNUNET_SYSERR;
+
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+  GDS_NEIGHBOURS_send_trail_setup_result (destination_peer, finger_identity,
+                                          target_friend, trail_length, trail_peer_list,
+                                          finger_map_index, trail_id);
+  return GNUNET_OK;
 }
 
 
+/**
+ * Invert the trail.
+ * @param trail Trail to be inverted
+ * @param trail_length Total number of peers in the trail.
+ * @return Updated trail
+ */
+static struct GNUNET_PeerIdentity *
+invert_trail (struct GNUNET_PeerIdentity *trail,
+              unsigned int trail_length)
+{
+  int i;
+  int j;
+  struct GNUNET_PeerIdentity *inverted_trail;
+
+  inverted_trail = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity) *
+                                  trail_length);
+  i = 0;
+  j = trail_length - 1;
+  while (i < trail_length)
+  {
+    inverted_trail[i] = trail[j];
+    i++;
+    j--;
+  }
+  return inverted_trail;
+}
+
 
 /**
- * Core handler for get result
- * @param cls closure
- * @param peer sender of the request
- * @param message message
- * @return #GNUNET_OK to keep the connection open,
- *         #GNUNET_SYSERR to close it (signal serious error)
+ * Check if the new finger can be our predecessor. If yes then update predecessor
+ *
+ * @param new_finger
+ * @param new_finger_trail
+ * @param new_finger_trail_length
+ * @return
  */
 static int
-handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
-                           const struct GNUNET_MessageHeader *message)
+is_new_entry_correct_predecessor (struct FingerInfo *my_predecessor,
+                                struct GNUNET_PeerIdentity new_finger,
+                                struct GNUNET_PeerIdentity *new_finger_trail,
+                                unsigned int new_finger_trail_length)
 {
-  /* If you are the source, go back to the client file and there search for
-   the requesting client and send back the result. */
-  struct PeerGetResultMessage *get_result;
-  struct GNUNET_PeerIdentity *get_path;
-  struct GNUNET_PeerIdentity *put_path;
-  void *payload;
-  size_t payload_size;
-  size_t msize;
-  unsigned int getlen;
-  unsigned int putlen;
-  int current_path_index;
-  
-  msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerGetResultMessage))
-  {
-    GNUNET_break_op (0);
+  struct GNUNET_PeerIdentity *updated_trail;
+  struct GNUNET_HashCode new_trail_id;
+
+  updated_trail =  invert_trail (new_finger_trail, new_finger_trail_length);
+  if (GNUNET_YES == is_new_finger_closest (my_predecessor, new_finger,
+                                           new_finger_trail,
+                                           new_finger_trail_length,
+                                           new_trail_id, PREDECESSOR_FINGER_ID))
+  {
+    add_new_entry (new_finger, updated_trail, new_finger_trail_length,
+                   new_trail_id, PREDECESSOR_FINGER_ID);
+    /* FIXME: check where you send add trail message */
     return GNUNET_YES;
   }
-  
-  get_result = (struct PeerGetResultMessage *)message;
-  getlen = ntohl (get_result->get_path_length);
-  putlen = ntohl (get_result->put_path_length);
-  
-  if ((msize <
-       sizeof (struct PeerGetResultMessage) +
-       getlen * sizeof (struct GNUNET_PeerIdentity) + 
-       putlen * sizeof (struct GNUNET_PeerIdentity)) ||
-      (getlen >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity) ||
-      (putlen >
-         GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity))))
+  return GNUNET_NO;
+}
+
+/**
+ * In case the source peer of verify successor message is not my successor,
+ * then construct a trail from source peer to my current predecessor.
+ * @param my_predecessor my current predecessor.
+ * @param current_trail Trail from source to me.
+ * @param current_trail_length Total number of peers in @a current_trail
+ * @param new_trail_length [out] Total number of peers in updated trail.
+ * @return Updated trail from source peer to my_predecessor.
+ */
+static struct GNUNET_PeerIdentity *
+trail_source_to_my_predecessor (struct FingerInfo *my_predecessor,
+                                struct GNUNET_PeerIdentity *current_trail,
+                                unsigned int current_trail_length,
+                                unsigned int *new_trail_length)
+{
+  struct GNUNET_PeerIdentity *new_trail;
+  struct TrailList *trail_list_iterator;
+  struct Trail *trail_iterator;
+  unsigned int i;
+  unsigned int j;
+  unsigned int shortest_trail_length = 0;
+  unsigned int trail_index = 0;
+
+  for (i = 0; i < my_predecessor->trails_count; i++)
   {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
+    trail_list_iterator = &my_predecessor->trail_list[i];
+    if (trail_list_iterator->trail_length > shortest_trail_length)
+      continue;
+    shortest_trail_length = trail_list_iterator->trail_length;
+    trail_index = i;
   }
-  
-  get_path = (struct GNUNET_PeerIdentity *) &get_result[1];
-  payload = &get_path[getlen];
-  payload_size = msize - (sizeof (struct PeerGetResultMessage) + 
-                          getlen * sizeof (struct GNUNET_PeerIdentity));
-  /* FIXME: Check if its correct or not. */
-  if (putlen > 0)
-    put_path = &get_path[1];
-  
-  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &(get_path[0]))))
+
+  *new_trail_length = current_trail_length + shortest_trail_length + 1;
+  new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) *
+                             *new_trail_length);
+  memcpy (new_trail, current_trail,
+         current_trail_length * sizeof (struct GNUNET_PeerIdentity));
+  new_trail[current_trail_length + 1] = my_identity;
+
+  i = 0;
+  j = current_trail_length + 1;
+  trail_list_iterator = &my_predecessor->trail_list[trail_index];
+  trail_iterator = trail_list_iterator->trail_head;
+  while ( i < shortest_trail_length)
   {
-    //GDS_CLIENTS_process_get_result();
-    GDS_CLIENTS_handle_reply (get_result->expiration_time, &(get_result->key), 
-                              getlen, get_path, putlen,
-                              put_path, get_result->type, payload_size, payload);
-    return GNUNET_YES;
+    new_trail[j] = trail_iterator->peer;
+    j++;
+    i++;
+    trail_iterator = trail_iterator->next;
   }
-  else
-  {
-    struct GNUNET_PeerIdentity *next_hop;
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    current_path_index = search_my_location (get_path);
-    /* FIXME: First check if you are adding yourself to the get path or not.
-     if yes then don't check if current_path_index == 0, if not then check 
-     and next_hop == source_peer. */
-    memcpy (next_hop, &get_path[current_path_index - 1], sizeof (struct GNUNET_PeerIdentity));
-  
-    GDS_NEIGHBOURS_send_get_result (get_result->expiration_time, &(get_result->key),
-                                     putlen, put_path,
-                                     get_result->type, payload_size,payload,
-                                     get_path, getlen,
-                                     next_hop, &(get_result->source_peer));
-    return GNUNET_YES;
-  }  
-  return GNUNET_SYSERR;
+
+  *new_trail_length = j;
+  return new_trail;
 }
 
 
-/** 
- * Handle a PeerTrailSetupMessage. 
+/**
+ * Core handle for p2p verify successor messages.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_trail_setup(void *cls, const struct GNUNET_PeerIdentity *peer,
-                           const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
+                                const struct GNUNET_MessageHeader *message)
 {
-  const struct PeerTrailSetupMessage *trail_setup;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
-  struct GNUNET_PeerIdentity source;
+  struct PeerVerifySuccessorMessage *vsm;
+  struct GNUNET_PeerIdentity successor;
+  struct GNUNET_PeerIdentity source_peer;
   struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_PeerIdentity next_peer;
-  struct GNUNET_PeerIdentity *trail_peer_list;
   struct FriendInfo *target_friend;
-  uint64_t destination_finger_value;
-  uint32_t trail_length;
-  uint32_t finger_map_index;
+  struct GNUNET_HashCode trail_id;
+  struct FingerInfo *my_predecessor;
+  struct GNUNET_PeerIdentity *trail;
+  struct GNUNET_PeerIdentity *new_trail;
+  unsigned int trail_length;
+  unsigned int new_trail_length;
   size_t msize;
 
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailSetupMessage))
+  if (msize != sizeof (struct PeerVerifySuccessorMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  trail_setup = (const struct PeerTrailSetupMessage *) message; 
-  trail_length = ntohl (trail_setup->trail_length); 
-  
-  if ((msize < sizeof (struct PeerTrailSetupMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+
+  vsm = (struct PeerVerifySuccessorMessage *) message;
+  trail_length = ntohl (vsm->trail_length);
+  if ((msize != sizeof (struct PeerVerifySuccessorMessage) +
+               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
+      (trail_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
   {
     GNUNET_break_op (0);
-    return GNUNET_YES; 
+    return GNUNET_YES;
   }
-  
-  trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_setup[1];
-  current_destination = trail_setup->current_destination;
-  current_source = trail_setup->current_source;
-  source = trail_setup->source_peer;
-  finger_map_index = ntohl (trail_setup->finger_map_index);
-  destination_finger_value = ntohl (trail_setup->destination_finger);
+  trail = (struct GNUNET_PeerIdentity *)&vsm[1];
+  source_peer = vsm->source_peer;
+  successor = vsm->successor;
+  trail_id = vsm->trail_id;
 
-  /* Check if you are part of the trail or current destination, and accordingly
-   * find the next peer to send the message to. */
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
+  if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&successor, &my_identity)))
   {
-    next_hop = GDS_ROUTING_search (&current_source, &current_destination, peer);
-    /* OPTIMIZATION: do find_successor also and get a better path if possible. */
-    if (next_hop == NULL)
+    next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
+    if (NULL == next_hop)
     {
-      /* FIXME next_hop to NULL, 
-       * 1. statistics update, drop the message. 
-         2. complain to sender with new message: trail lost */
-        return GNUNET_OK;
+      GNUNET_break (0);
+      return GNUNET_SYSERR;
     }
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+    GDS_NEIGHBOURS_send_verify_successor_message (source_peer, successor,
+                                                  trail_id, trail, trail_length,
+                                                  target_friend);
+    return GNUNET_OK;
   }
-  else
-  {
-    next_hop = find_successor (destination_finger_value, &current_destination, &current_source); 
-  }
-  
-  /* Now add yourself to the trail. */
-  struct GNUNET_PeerIdentity peer_list[trail_length + 1];
-  memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  peer_list[trail_length] = my_identity;
-  trail_length++;
-  
-  /* Check next_hop type and make the judgment what to do next. */
-  if (NULL == next_hop) /* This means I am the final destination */
+
+  my_predecessor = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
+                                                        PREDECESSOR_FINGER_ID);
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+  if (GNUNET_NO == is_new_entry_correct_predecessor (my_predecessor, source_peer,
+                                                     trail, trail_length))
   {
-    if (trail_length == 1)
+    if (0 != GNUNET_CRYPTO_cmp_peer_identity (&source_peer,
+                                              &my_predecessor->finger_identity))
     {
-      memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
-    }
-    else
-    {
-      memcpy (&next_peer, &trail_peer_list[trail_length-2], sizeof (struct GNUNET_PeerIdentity));
+      new_trail = trail_source_to_my_predecessor (my_predecessor, trail,
+                                                  trail_length, &new_trail_length);
     }
-     
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
-   
-    /* FIXME: URGENT change it to handle the change in current_finger_index. 
-       compare  to your own predecessor */
-    if (compare_predecessor (&source) /* ! HAVE A PREDECESSOR || (source_peer closer than existing PREDECESOR) */)
-    {
-      struct GNUNET_PeerIdentity *new_trail_list;
-      new_trail_list = invert_trail_list (&source, peer_list, trail_length);
-      finger_table_add (&source, new_trail_list, trail_length, PREDECESSOR_FINGER_ID);
-    }
-    
-    GDS_NEIGHBOURS_send_trail_setup_result (&source,
-                                            &(my_identity),
-                                            target_friend, trail_length,
-                                            peer_list,
-                                            finger_map_index);
-  
-    return GNUNET_YES;
   }
   else
   {
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GDS_NEIGHBOURS_send_trail_setup (&source,
-                                     destination_finger_value,
-                                     &current_destination, &current_source,
-                                     target_friend, trail_length, peer_list, 
-                                     finger_map_index);
-    return GNUNET_YES;
-  }
-  return GNUNET_SYSERR;
+    my_predecessor = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
+                                                          PREDECESSOR_FINGER_ID);
+    GDS_NEIGHBOURS_send_add_trail (my_predecessor->finger_identity,
+                                   source_peer, trail_id,
+                                   trail, trail_length,
+                                   target_friend);
+    new_trail_length = trail_length;
+    new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) *
+                               new_trail_length);
+    memcpy (new_trail, trail, sizeof (struct GNUNET_PeerIdentity) *
+                              trail_length);
+  }
+
+  GDS_NEIGHBOURS_send_verify_successor_result (source_peer, my_identity,
+                                               my_predecessor->finger_identity,
+                                               trail_id, new_trail,
+                                               new_trail_length,
+                                               GDS_ROUTING_DEST_TO_SRC,
+                                               target_friend);
+  return GNUNET_OK;
 }
 
 
 /**
- * Core handle for p2p trail construction result messages.
+ * FIXME: I will keep the logic to remove the old trail to reach from me to
+ * my old successor here and move adding a new trail from me to new successor to notify
+ * new successor. And in case if the new successor also take it as predecessor
+ * then call add_trail.
+ * Core handle for p2p verify successor result messages.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
- * @return GNUNET_OK on success, GNUNET_SYSERR on error
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                  const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_verify_successor_result(void *cls, const struct GNUNET_PeerIdentity *peer,
+                                       const struct GNUNET_MessageHeader *message)
 {
-  struct PeerTrailSetupResultMessage *trail_result;
-  struct GNUNET_PeerIdentity *trail_peer_list;
+  struct PeerVerifySuccessorResultMessage *vsrm;
+  enum GDS_ROUTING_trail_direction trail_direction;
+  struct GNUNET_HashCode trail_id;
+  unsigned int new_trail_length;
+  struct GNUNET_PeerIdentity *new_trail;
+  struct GNUNET_PeerIdentity destination_peer;
+  struct GNUNET_PeerIdentity my_new_successor;
+  struct GNUNET_PeerIdentity old_successor;
   struct GNUNET_PeerIdentity *next_hop;
   struct FriendInfo *target_friend;
-  unsigned int current_trail_index;
-  unsigned int finger_map_index;
-  unsigned int trail_length;
   size_t msize;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailSetupResultMessage))
+  if (msize != sizeof (struct PeerVerifySuccessorResultMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  trail_result = (struct PeerTrailSetupResultMessage *) message; 
-  trail_length = ntohl (trail_result->trail_length); 
-  
-  if ((msize <
-       sizeof (struct PeerTrailSetupResultMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  vsrm = (struct PeerVerifySuccessorResultMessage *) message;
+  new_trail_length = ntohl (vsrm->trail_length);
+  trail_direction = ntohl (vsrm->trail_direction);
+  trail_id = vsrm->trail_id;
+
+  if ((msize !=
+       sizeof (struct PeerVerifySuccessorResultMessage) +
+       new_trail_length *
+       sizeof (struct GNUNET_PeerIdentity)) ||
+       (new_trail_length >
+       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  finger_map_index = ntohl (trail_result->finger_map_index);
 
-  trail_peer_list = (struct GNUNET_PeerIdentity *) &trail_result[1];
-  
-  if ( 0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->destination_peer),
-                                              &my_identity)))
-  {
-      finger_table_add (&(trail_result->finger_identity), trail_peer_list, trail_length, 
-                       finger_map_index);
-     
-      return GNUNET_YES;
+  new_trail = (struct GNUNET_PeerIdentity *) &vsrm[1];
+  destination_peer = vsrm->destination_peer;
+  my_new_successor = vsrm->my_predecessor;
+  old_successor = vsrm->source_successor;
 
-  }
-  else
+  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&destination_peer, &my_identity)))
   {
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    current_trail_index = search_my_location (trail_peer_list);
-    current_trail_index = current_trail_index - 1; 
-    if (current_trail_index == 0)
+    struct GNUNET_HashCode new_finger_trail_id;
+    /* FIXME: generate a new trail id. */
+    if (GNUNET_YES == finger_table_add (my_new_successor,
+                                        new_trail,
+                                        new_trail_length,
+                                        PREDECESSOR_FINGER_ID, new_finger_trail_id))
     {
-      memcpy (next_hop, &(trail_result->destination_peer),sizeof (struct GNUNET_PeerIdentity));
-    }
-    else
-    {   
-      memcpy (next_hop, &(trail_peer_list[current_trail_index-1]),sizeof (struct GNUNET_PeerIdentity));
-    }
-    
-    /* If trail length  = 2, it means that destination and source peer are friends
-     Then don't add an entry. */
-    if (trail_length != 2)
-      GDS_ROUTING_add (&(trail_result->destination_peer), &(trail_result->finger_identity),
-                     peer, next_hop);   
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GNUNET_free (next_hop);
-      
-    GDS_NEIGHBOURS_send_trail_setup_result (&(trail_result->destination_peer),
-                                            &(trail_result->finger_identity),
-                                            target_friend, trail_length,
-                                            trail_peer_list,
-                                            finger_map_index);
-      return GNUNET_YES;
+      if (new_trail_length > 0)
+        target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                           &new_trail[0]);
+      else
+        target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                           peer);
+      GDS_NEIGHBOURS_send_trail_teardown (my_identity, old_successor, trail_id,
+                                          GDS_ROUTING_SRC_TO_DEST, target_friend);
+      GDS_NEIGHBOURS_send_notify_new_successor (my_identity, my_new_successor,
+                                                new_trail,
+                                                new_trail_length,
+                                                new_finger_trail_id, target_friend);
     }
-  
-  return GNUNET_SYSERR;
+    return GNUNET_OK;
+  }
+
+  GNUNET_assert (NULL != (next_hop =
+                         GDS_ROUTING_get_next_hop (trail_id, trail_direction)));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+  GDS_NEIGHBOURS_send_verify_successor_result (destination_peer,
+                                               vsrm->source_successor,
+                                               my_new_successor, trail_id,
+                                               new_trail,
+                                               new_trail_length,
+                                               trail_direction, target_friend);
+  return GNUNET_OK;
 }
 
 
-/**
- * FIXME: Use flag in the case finger peer map does not contain predcessor
- * then its NULL. Ideally it should never happen. 
- * Get my current predecessor from the finger peer map
- * @return Current predecessor.
- */
-static struct FingerInfo *
-get_predecessor()
-{
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
-  unsigned int finger_index;
-  struct FingerInfo *my_predecessor;
-  /* Iterate over finger peer map and extract your predecessor. */
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
+/*
+ * Core handle for p2p notify new successor messages.
+ * @param cls closure
+ * @param message message
+ * @param peer peer identity this notification is about
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ */
+static int
+handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
+                                    const struct GNUNET_MessageHeader *message)
+{
+  struct PeerNotifyNewSuccessorMessage *nsm;
+  struct GNUNET_PeerIdentity *trail;
+  struct GNUNET_PeerIdentity source;
+  struct GNUNET_PeerIdentity destination;
+  struct FriendInfo *target_friend;
+  struct GNUNET_HashCode trail_id;
+  unsigned int my_index;
+  struct GNUNET_PeerIdentity next_hop;
+  size_t msize;
+  uint32_t trail_length;
+
+  msize = ntohs (message->size);
+  if (msize != sizeof (struct PeerNotifyNewSuccessorMessage))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_YES;
+  }
+
+  nsm = (struct PeerNotifyNewSuccessorMessage *) message;
+  trail_length = ntohl (nsm->trail_length);
+
+  if ((msize < sizeof (struct PeerNotifyNewSuccessorMessage) +
+               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
+      (trail_length >
+       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_YES;
+  }
+
+  trail = (struct GNUNET_PeerIdentity *) &nsm[1];
+  source  = nsm->source_peer;
+  destination = nsm->destination_peer;
+  trail_id = nsm->trail_id;
+
+  if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &destination))
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next 
-                       (finger_iter,&key_ret,(const void **)&my_predecessor)) 
+    struct GNUNET_HashCode new_trail_id;
+    struct FingerInfo *my_predecessor;
+
+    my_predecessor =
+            GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
+                                                 PREDECESSOR_FINGER_ID);
+    /* FIXME: get new_trail_id*/
+
+    if (GNUNET_YES == is_new_entry_correct_predecessor (my_predecessor,
+                                                        source, trail,
+                                                        trail_length))
     {
-      if(1 == my_predecessor->finger_map_index)
-      {
-        break;
-      }
+
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                         peer);
+      GDS_NEIGHBOURS_send_add_trail (my_identity, source, new_trail_id,
+                                     trail, trail_length, target_friend);
+      return GNUNET_OK;
     }
   }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  return my_predecessor;
+
+  my_index = search_my_index (trail, trail_length);
+  if (GNUNET_SYSERR == my_index)
+  {
+    GNUNET_break_op (0);
+    return GNUNET_SYSERR;
+  }
+  if (trail_length == my_index)
+    next_hop = destination;
+  else
+    next_hop = trail[my_index + 1];
+  GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, next_hop));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+  GDS_NEIGHBOURS_send_notify_new_successor (source, destination, trail,
+                                            trail_length,
+                                            trail_id, target_friend);
+  return GNUNET_OK;
 }
 
 
 /**
- * Core handle for p2p verify successor messages.
+ * FIXME: Here you should keep the trail id with you.
+ * Core handler for P2P trail rejection message
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
- * @return GNUNET_OK on success, GNUNET_SYSERR on error
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer,
+                               const struct GNUNET_MessageHeader *message)
 {
-  struct PeerVerifySuccessorMessage *vsm;
+  struct PeerTrailRejectionMessage *trail_rejection;
+  unsigned int trail_length;
   struct GNUNET_PeerIdentity *trail_peer_list;
   struct FriendInfo *target_friend;
+  struct GNUNET_TIME_Relative congestion_timeout;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity next_destination;
+  struct GNUNET_HashCode new_intermediate_trail_id;
+  struct GNUNET_PeerIdentity next_peer;
+  struct GNUNET_PeerIdentity source;
   struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_PeerIdentity *source_peer;
-  unsigned int trail_length;
+  uint64_t ultimate_destination_finger_value;
+  unsigned int finger_map_index;
   size_t msize;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerVerifySuccessorMessage))
+  if (msize != sizeof (struct PeerTrailRejectionMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  vsm = (struct PeerVerifySuccessorMessage *) message;
-  trail_length = ntohl (vsm->trail_length);
-  
-  if ((msize < sizeof (struct PeerVerifySuccessorMessage) +
+
+  trail_rejection = (struct PeerTrailRejectionMessage *) message;
+  trail_length = ntohl (trail_rejection->trail_length);
+
+  if ((msize != sizeof (struct PeerTrailRejectionMessage) +
                trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-     (trail_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+      (trail_length >
+       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  trail_peer_list = (struct GNUNET_PeerIdentity *) &vsm[1];
-  source_peer = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-  memcpy (source_peer, &(vsm->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  
-  next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-  
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(vsm->successor),&my_identity)))
+
+  trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
+  finger_map_index = ntohl (trail_rejection->finger_map_index);
+  congestion_timeout = trail_rejection->congestion_time;
+  source = trail_rejection->source_peer;
+  trail_id = trail_rejection->trail_id;
+  ultimate_destination_finger_value =
+  trail_rejection->ultimate_destination_finger_identity_value;
+
+  /* First set the congestion time of the friend that sent you this message. */
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+  target_friend->congestion_timestamp = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
+                                                                 congestion_timeout);
+
+  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &source)))
   {
-    struct FingerInfo *my_predecessor;
+    return GNUNET_OK;
+  }
+
+  /* If I am congested then pass this message to peer before me in trail. */
+  if(GNUNET_YES == GDS_ROUTING_threshold_reached())
+  {
+    struct GNUNET_PeerIdentity *new_trail;
+    unsigned int new_trail_length;
+
     if (trail_length == 1)
-      memcpy (next_hop, source_peer, sizeof (struct GNUNET_PeerIdentity));
-    else
     {
-      int current_trail_index;
-      current_trail_index = search_my_location (trail_peer_list);
-      memcpy (next_hop, &trail_peer_list[current_trail_index-1], sizeof (struct GNUNET_PeerIdentity));
+      new_trail = NULL;
+      new_trail_length = 0;
+      next_hop = &source;
     }
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GNUNET_free (next_hop);
-    
-    my_predecessor = get_predecessor();
-    if (0 == (GNUNET_CRYPTO_cmp_peer_identity (source_peer,
-                                               &(my_predecessor->finger_identity))))
+    else
     {
-      GDS_NEIGHBOURS_send_verify_successor_result (source_peer,
-                                                   &(my_identity),
-                                                   &(my_predecessor->finger_identity),
-                                                   target_friend,
-                                                   trail_peer_list,
-                                                   trail_length);
+      next_hop = &trail_peer_list[trail_length - 2];
+      /* Remove myself from the trail. */
+      new_trail_length = trail_length -1;
+      new_trail = GNUNET_malloc (new_trail_length * sizeof (struct GNUNET_PeerIdentity));
+      memcpy (new_trail, trail_peer_list, new_trail_length * sizeof (struct GNUNET_PeerIdentity));
     }
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+    GDS_NEIGHBOURS_send_trail_rejection (source,
+                                         ultimate_destination_finger_value,
+                                         my_identity, finger_map_index,
+                                         new_trail,new_trail_length,trail_id,
+                                         target_friend, CONGESTION_TIMEOUT);
+    return GNUNET_YES;
+  }
+
+  /* Look for next_hop to pass the trail setup message */
+  next_hop = find_successor (ultimate_destination_finger_value,
+                             &next_destination,
+                             &new_intermediate_trail_id,
+                             finger_map_index);
+
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))/* This means I am the final destination */
+  {
+    if (0 == trail_length)
+      next_peer = source;
     else
-    {
-      struct GNUNET_PeerIdentity *new_successor_trail;
-      int new_trail_length;
-      int i;
-      
-      new_trail_length = trail_length + my_predecessor->trail_length;
-      new_successor_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * new_trail_length);
-      memcpy (new_successor_trail, trail_peer_list, (trail_length) * sizeof (struct GNUNET_PeerIdentity));
-      struct TrailPeerList *iterator;
-      iterator = GNUNET_malloc (sizeof (struct TrailPeerList));
-      iterator = my_predecessor->head; 
-      i = trail_length;
-      while (i < new_trail_length)
-      {
-        memcpy (&new_successor_trail[i], &(iterator->peer), sizeof (struct GNUNET_PeerIdentity));
-        iterator = iterator->next;
-        i++;
-      }
-      GDS_NEIGHBOURS_send_verify_successor_result (source_peer,
-                                                   &(my_identity),
-                                                   &(my_predecessor->finger_identity),
-                                                   target_friend,
-                                                   new_successor_trail,
-                                                   new_trail_length); 
-    }      
-   
+      next_peer = trail_peer_list[trail_length-1];
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
+    GDS_NEIGHBOURS_send_trail_setup_result (source,
+                                            my_identity,
+                                            target_friend, trail_length,
+                                            trail_peer_list,
+                                            finger_map_index, trail_id);
   }
   else
   {
-    unsigned int current_trail_index;
-    current_trail_index = search_my_location (trail_peer_list);
-    memcpy (next_hop, &trail_peer_list[current_trail_index], sizeof (struct GNUNET_PeerIdentity));
+    struct GNUNET_PeerIdentity peer_list[trail_length + 1];
+
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+    peer_list[trail_length] = my_identity;
+
     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GNUNET_free (next_hop);
-        
-    GDS_NEIGHBOURS_send_verify_successor (source_peer, &(vsm->successor),target_friend,
-                                          trail_peer_list, trail_length); 
+    GDS_NEIGHBOURS_send_trail_setup (source,
+                                     ultimate_destination_finger_value,
+                                     next_destination,
+                                     target_friend, trail_length + 1, peer_list,
+                                     finger_map_index, trail_id,
+                                     &new_intermediate_trail_id);
   }
-  return GNUNET_YES;
+  return GNUNET_OK;
 }
 
 
-/**
- * Core handle for p2p verify successor result messages.
+/*
+ * Core handle for p2p trail tear down messages.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
- * @return GNUNET_OK on success, GNUNET_SYSERR on error
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_verify_successor_result(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                       const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_trail_compression (void *cls, const struct GNUNET_PeerIdentity *peer,
+                               const struct GNUNET_MessageHeader *message)
 {
-  struct PeerVerifySuccessorResultMessage *vsrm;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *trail_peer_list;
+  struct PeerTrailCompressionMessage *trail_compression;
   struct GNUNET_PeerIdentity *next_hop;
-  unsigned int trail_length;
-  unsigned int current_trail_index;
+  struct GNUNET_HashCode trail_id;
+  struct FriendInfo *target_friend;
   size_t msize;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerVerifySuccessorResultMessage))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  
-  vsrm = (struct PeerVerifySuccessorResultMessage *) message;
-  trail_length = ntohl (vsrm->trail_length); 
-  
-  if ((msize <
-       sizeof (struct PeerVerifySuccessorResultMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  if (msize != sizeof (struct PeerTrailCompressionMessage))
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
+    return GNUNET_OK;
   }
-  
-  trail_peer_list = (struct GNUNET_PeerIdentity *) &vsrm[1];
 
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(vsrm->destination_peer), &(my_identity))))
+  trail_compression = (struct PeerTrailCompressionMessage *) message;
+  trail_id = trail_compression->trail_id;
+
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_compression->new_first_friend),
+                                             &my_identity)))
   {
-    if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&(vsrm->my_predecessor), &(my_identity))))
-    {
-      finger_table_add (&(vsrm->my_predecessor), trail_peer_list, trail_length, 0);
-      next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-      memcpy (next_hop, &trail_peer_list[0], sizeof (struct GNUNET_PeerIdentity));
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-      GNUNET_free (next_hop);
-      
-      GDS_NEIGHBOURS_send_notify_new_successor (&my_identity, &(vsrm->my_predecessor),
-                                                target_friend, trail_peer_list,
-                                                trail_length);
-    }
+     if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_compression->destination_peer),
+                                               &my_identity)))
+     {
+       GDS_ROUTING_update_trail_prev_hop (trail_id,
+                                          trail_compression->source_peer);
+     }
+     return GNUNET_OK;
   }
-  else
+
+  next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
+  if (NULL == next_hop)
   {
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    current_trail_index = search_my_location (trail_peer_list);
-    if (current_trail_index == 1)
-      memcpy (next_hop, &(vsrm->destination_peer), sizeof (struct GNUNET_PeerIdentity));
-    else
-      memcpy (next_hop, &trail_peer_list[current_trail_index-1], sizeof (struct GNUNET_PeerIdentity));
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GNUNET_free (next_hop);
-    
-    GDS_NEIGHBOURS_send_verify_successor_result (&(vsrm->destination_peer),
-                                                 &(vsrm->source_successor),
-                                                 &(vsrm->my_predecessor),
-                                                 target_friend,
-                                                 trail_peer_list,
-                                                 trail_length); 
+    GNUNET_break (0); /*FIXME: How to handle this case.  */
+    return GNUNET_OK;
   }
-  return GNUNET_YES;
+  GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+  GDS_NEIGHBOURS_send_trail_compression (trail_compression->source_peer,
+                                         trail_compression->destination_peer,
+                                         trail_id,
+                                         trail_compression->new_first_friend,
+                                         target_friend);
+  return GNUNET_OK;
 }
 
 
 /**
- * Core handle for p2p notify new successor messages.
+ * Core handler for trail teardown message.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
- * @return GNUNET_OK on success, GNUNET_SYSERR on error
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                    const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_trail_teardown (void *cls, const struct GNUNET_PeerIdentity *peer,
+                               const struct GNUNET_MessageHeader *message)
 {
-  struct PeerNotifyNewSuccessorMessage *nsm;
-  struct GNUNET_PeerIdentity *trail_peer_list;
-  unsigned int current_trail_index;
+  struct PeerTrailTearDownMessage *trail_teardown;
+  struct GNUNET_HashCode trail_id;
+  enum GDS_ROUTING_trail_direction trail_direction;
   size_t msize;
-  unsigned int trail_length;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerNotifyNewSuccessorMessage))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  
-  nsm = (struct PeerNotifyNewSuccessorMessage *) message;
-  trail_length = ntohl (nsm->trail_length);
-  
-  if ((msize < sizeof (struct PeerNotifyNewSuccessorMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  if (msize != sizeof (struct PeerTrailTearDownMessage))
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  
-  trail_peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
-  
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(nsm->destination_peer), &my_identity)))
-  {
-    struct GNUNET_PeerIdentity *new_trail;
-    new_trail = invert_trail_list (&(nsm->source_peer), trail_peer_list, trail_length);
-    finger_table_add (&(nsm->source_peer), new_trail, trail_length, 1); 
-    return GNUNET_YES;
+    return GNUNET_OK;
   }
-  else
+
+  trail_teardown = (struct PeerTrailTearDownMessage *) message;
+  trail_direction = ntohl (trail_teardown->trail_direction);
+  trail_id = trail_teardown->TRAIL_ID;
+
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
+                                            &trail_teardown->destination_peer))
   {
-    struct FriendInfo *target_friend;
     struct GNUNET_PeerIdentity *next_hop;
-    
-    target_friend = GNUNET_malloc (sizeof (struct FriendInfo));
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    
-    current_trail_index = search_my_location (trail_peer_list);
-    memcpy (next_hop, &trail_peer_list[current_trail_index+1], sizeof (struct GNUNET_PeerIdentity));
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GNUNET_free (next_hop);
-    
-    GDS_NEIGHBOURS_send_notify_new_successor (&(nsm->source_peer), 
-                                              &(nsm->destination_peer),
-                                              target_friend, trail_peer_list,
-                                              trail_length);
+    struct FriendInfo *target_friend;
+
+    next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
+    if (NULL == next_hop)
+    {
+      GNUNET_break (0);
+      return GNUNET_SYSERR;
+    }
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                       next_hop);
+    GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
+    GDS_NEIGHBOURS_send_trail_teardown (trail_teardown->source_peer,
+                                        trail_teardown->destination_peer,
+                                        trail_id, trail_direction,
+                                        target_friend);
   }
-  return GNUNET_YES;
+  return GNUNET_OK;
 }
 
 
 /**
- * FIXME: Does it matter if the packet was going to a finger or friend?
- * Core handle for p2p trail rejection messages.
+ * Fixme: this function is called only in case in notify new successor, the new
+ * successor wants to add the source of the peer as its predecessor. Identify
+ * if there is any other use case where it is required and if yes then adapt the
+ * code for it.
+ * Core handle for p2p add trail message.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
- * @return GNUNET_OK on success, GNUNET_SYSERR on error
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
-static
-int handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                   const struct GNUNET_MessageHeader *message)
+static int
+handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
+                          const struct GNUNET_MessageHeader *message)
 {
-  struct PeerTrailRejectionMessage *trail_rejection;
-  struct FailedTrail *trail_fail;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *trail_peer_list;
-  unsigned int finger_map_index;
+  struct PeerAddTrailMessage *add_trail;
+  struct GNUNET_PeerIdentity *trail;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity destination_peer;
+  struct GNUNET_PeerIdentity source_peer;
+  struct GNUNET_PeerIdentity next_hop;
+  unsigned int trail_length;
+  unsigned int my_index;
   size_t msize;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailRejectionMessage))
+  if (msize != sizeof (struct PeerAddTrailMessage))
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
+    return GNUNET_OK;
   }
-  
-  trail_rejection = (struct PeerTrailRejectionMessage *) message;
-  trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
-  finger_map_index = ntohl (trail_rejection->finger_map_index);
-  trail_fail = GNUNET_malloc (sizeof (struct FailedTrail));
-  memcpy (&(trail_fail->source_peer), &(trail_rejection->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_fail->congested_peer), &(trail_rejection->congested_peer), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_fail->destination_finger_value), &(trail_rejection->finger_identity), sizeof (uint64_t));
-  
-  GNUNET_assert (GNUNET_OK ==
-  GNUNET_CONTAINER_multipeermap_put (failed_trail_list, &(trail_fail->source_peer),
-                                     trail_fail, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
-   
-  /* FIXME: Is it okay if I pass the struct as parameter. */
-  target_friend = select_random_friend (&(trail_fail->congested_peer));
-  
-  if(NULL != target_friend)
-  { 
-    GDS_NEIGHBOURS_send_trail_setup (&(trail_fail->source_peer), 
-                                     trail_fail->destination_finger_value,
-                                     &(target_friend->id),
-                                     NULL, target_friend, ntohl (trail_rejection->trail_length),
-                                     trail_peer_list, 
-                                     finger_map_index);
-    return GNUNET_YES;
+
+  add_trail = (struct PeerAddTrailMessage *) message;
+  trail_length = ntohl (add_trail->trail_length);
+
+  if ((msize < sizeof (struct PeerAddTrailMessage) +
+               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
+      (trail_length >
+       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_OK;
+  }
+
+  trail = (struct GNUNET_PeerIdentity *)&add_trail[1];
+  destination_peer = add_trail->destination_peer;
+  source_peer = add_trail->source_peer;
+  trail_id = add_trail->trail_id;
+
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
+                                            &destination_peer))
+  {
+    struct FriendInfo *target_friend;
+
+    my_index = search_my_index (trail, trail_length);
+    if (GNUNET_SYSERR == my_index)
+    {
+      GNUNET_break_op (0);
+      return GNUNET_SYSERR;
+    }
+
+    if (0 == my_index)
+      next_hop = source_peer;
+    else
+      next_hop = trail[trail_length - 1];
+
+    GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, next_hop, *peer));
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+    GDS_NEIGHBOURS_send_add_trail (source_peer, destination_peer, trail_id,
+                                   trail, trail_length, target_friend);
   }
-  return GNUNET_SYSERR;
+  return GNUNET_OK;
 }
 
-#if 0
+
 /**
- * 
- * @param cls
- * @param key
- * @param value
- * @return 
+ *FIXME; call send_trail_teardown_message on all the trails of the finger that
+ * you remove. Also you don't need to decerement friend trail count as that
+ * friend is removed. But you can not send trail teardown message as the friend
+ * is disconnected. then you don't have any next_hop. and in case there are
+ * multiple trails. and friend is the first trail then you remove only the trail.
+ * Iterate over finger_hashmap, and remove entries if finger is the disconnected
+ * peer or if disconnected peer is the first friend in the trail to reach the
+ * finger.
+ * @param cls closure
+ * @param key current public key
+ * @param value value in the hash map
+ * @return #GNUNET_YES if we should continue to
+ *         iterate,
+ *         #GNUNET_NO if not.
  */
 static int
 remove_matching_finger (void *cls,
-          const struct GNUNET_PeerIdentity *key,
-          void *value)
+                        uint32_t key,
+                        void *value)
 {
   struct FingerInfo *remove_finger = value;
   const struct GNUNET_PeerIdentity *disconnected_peer = cls;
-  
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->head->peer, disconnected_peer))
+  struct TrailList *trail_list;
+  int i;
+
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->finger_identity,
+                                            disconnected_peer))
   {
     GNUNET_assert (GNUNET_YES ==
-                   GNUNET_CONTAINER_multipeermap_remove (finger_peermap,
-                                                         key, 
+                   GNUNET_CONTAINER_multihashmap32_remove (finger_hashmap,
+                                                         key,
                                                          remove_finger));
-        /* FIXME: free_finger(remove_finger); Call this function at finger_table_add,
-         *when you replace an existing entry */
+    free_finger (remove_finger);
+    return GNUNET_YES;
+  }
+
+  for (i = 0; i< remove_finger->trails_count; i++)
+  {
+    trail_list = &remove_finger->trail_list[i];
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&trail_list->trail_head->peer,
+                                                disconnected_peer))
+    {
+      GNUNET_assert (GNUNET_YES ==
+                     GNUNET_CONTAINER_multihashmap32_remove (finger_hashmap,
+                                                           key,
+                                                           remove_finger));
+       free_finger (remove_finger);
+    }
   }
+
   return GNUNET_YES;
 }
-#endif
+
 
 /**
  * Method called whenever a peer disconnects.
@@ -2996,41 +3522,33 @@ static void
 handle_core_disconnect (void *cls,
                                          const struct GNUNET_PeerIdentity *peer)
 {
-#if 0
   struct FriendInfo *remove_friend;
-  //struct FingerInfo *remove_finger;
- // struct GNUNET_PeerIdentity key_ret;
-  //struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  //struct TrailPeerList *iterator;
-  //struct GNUNET_PeerIdentity *finger_identity;
-  //int finger_index;
-  
-  /* Check for self message. */
+
   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
     return;
-  
-   /* Search for peer to remove in your friend_peermap. */
+
   remove_friend =
       GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
-  
+
   if (NULL == remove_friend)
   {
     GNUNET_break (0);
     return;
   }
-  //FPRINTF (stderr,_("\nSUPU %s, %s, %d"),__FILE__, __func__,__LINE__);
 
-  GNUNET_CONTAINER_multipeermap_iterate (finger_peermap,
-                                         &remove_matching_finger, peer);  
-  /* Remove the friend from friend_peermap. */
+  GNUNET_assert (GNUNET_SYSERR !=
+                 GNUNET_CONTAINER_multihashmap32_iterate (finger_hashmap,
+                                                          &remove_matching_finger,
+                                                          (void *)peer));
+  GDS_ROUTING_remove_trail_by_peer (peer);
   GNUNET_assert (GNUNET_YES ==
                  GNUNET_CONTAINER_multipeermap_remove (friend_peermap,
                                                        peer,
                                                        remove_friend));
-  
+
   if (0 != GNUNET_CONTAINER_multipeermap_size (friend_peermap))
     return;
-  
+
   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
   {
       GNUNET_SCHEDULER_cancel (find_finger_trail_task);
@@ -3038,16 +3556,6 @@ handle_core_disconnect (void *cls,
   }
   else
     GNUNET_break (0);
-    
-  if (GNUNET_SCHEDULER_NO_TASK != verify_successor)
-  {
-      GNUNET_SCHEDULER_cancel (verify_successor);
-      verify_successor = GNUNET_SCHEDULER_NO_TASK;
-  }
-  /* FIXME: garbage collect routing table, and notify the failed trails about
-   trail lost.
-   */
-#endif
 }
 
 
@@ -3065,24 +3573,22 @@ handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
   /* Check for connect to self message */
   if (0 == memcmp (&my_identity, peer_identity, sizeof (struct GNUNET_PeerIdentity)))
     return;
-  
+
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to %s\n", GNUNET_i2s (peer_identity));
-  
+
   /* If peer already exists in our friend_peermap, then exit. */
   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (friend_peermap, peer_identity))
   {
     GNUNET_break (0);
     return;
   }
-  /* FIXME: Use statistics at places where you think such a conditions are very
-   rare. Then use statistics to make sure that it is indeed rare but if not
-   rare then hanlde it differently.*/
+
   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
                             GNUNET_NO);
 
   friend = GNUNET_new (struct FriendInfo);
   friend->id = *peer_identity;
-  
+
   GNUNET_assert (GNUNET_OK ==
                  GNUNET_CONTAINER_multipeermap_put (friend_peermap,
                                                     peer_identity, friend,
@@ -3105,13 +3611,6 @@ core_init (void *cls,
            const struct GNUNET_PeerIdentity *identity)
 {
   my_identity = *identity;
-  
-  /* SUPU TEST CODE */
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
-              _("\nSUPU %s, %s, %d,my_identity = %s"),
-              __FILE__, __func__, __LINE__, GNUNET_i2s (&my_identity));
-  /* SUPU TEST CODE ENDS */
-
 }
 
 
@@ -3120,96 +3619,73 @@ core_init (void *cls,
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 int
-GDS_NEIGHBOURS_init()
+GDS_NEIGHBOURS_init (void)
 {
   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
-    {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT, 0},   
+    {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT, 0},
     {&handle_dht_p2p_trail_setup, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP, 0},
     {&handle_dht_p2p_trail_setup_result, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT, 0},
     {&handle_dht_p2p_verify_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR, 0},
     {&handle_dht_p2p_verify_successor_result, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT, 0},
     {&handle_dht_p2p_notify_new_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR, 0},
     {&handle_dht_p2p_trail_rejection, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION, 0},
+    {&handle_dht_p2p_trail_compression, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION, 0},
+    {&handle_dht_p2p_trail_teardown, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN, 0},
+    {&handle_dht_p2p_add_trail, GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL, 0},
     {NULL, 0, 0}
   };
-  
+
   core_api =
     GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
                          &handle_core_disconnect, NULL, GNUNET_NO, NULL,
                          GNUNET_NO, core_handlers);
   if (NULL == core_api)
     return GNUNET_SYSERR;
-  
-  /* Initialize the current index in the finger map. */
-  current_finger_index = PREDECESSOR_FINGER_ID;
-  
+
   friend_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
-  finger_peermap = GNUNET_CONTAINER_multipeermap_create (MAX_FINGERS * 4/3, GNUNET_NO);
-  /* FIXME: Not sure if this value is correct for this data structure. also 
-   * not sure if we actually need any such data structure. Once done with other functions,
-   * will revisit this part.  */
-  failed_trail_list = GNUNET_CONTAINER_multipeermap_create (LINK_THRESHOLD * 4/3, GNUNET_NO);
+  finger_hashmap = GNUNET_CONTAINER_multihashmap32_create (MAX_FINGERS * 4/3);
+
   return GNUNET_OK;
 }
 
-
 /**
  * Shutdown neighbours subsystem.
  */
 void
-GDS_NEIGHBOURS_done ()
+GDS_NEIGHBOURS_done (void)
 {
   if (NULL == core_api)
     return;
-  
+
   GNUNET_CORE_disconnect (core_api);
   core_api = NULL;
-  
+
   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (friend_peermap));
   GNUNET_CONTAINER_multipeermap_destroy (friend_peermap);
   friend_peermap = NULL;
-  
-  GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (finger_peermap));
-  GNUNET_CONTAINER_multipeermap_destroy (finger_peermap);
-  finger_peermap = NULL;
 
-  /* FIXME: Here I have added GNUNET_break(0) as ideally if friend_peermap 
-   is already zero, then we really don't need to cancel it again. If this 
-   condition happens it mean we might have missed some corner case. */
+  GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (finger_hashmap));
+  GNUNET_CONTAINER_multihashmap32_destroy (finger_hashmap);
+  finger_hashmap = NULL;
+
   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
   {
     GNUNET_break (0);
     GNUNET_SCHEDULER_cancel (find_finger_trail_task);
     find_finger_trail_task = GNUNET_SCHEDULER_NO_TASK;
   }
-  
-  /* FIXME: when do you cancel verify successor irrespective of this part
-   of code. If no where else, then there should not be GNUNET_break (0) as it
-   is right to call it here. Also, leave it here for time being and in case 
-   you always encounter this break, it means it is nor required. remove it then. */
-  if (GNUNET_SCHEDULER_NO_TASK != verify_successor)
-  {
-    GNUNET_break (0);
-    GNUNET_SCHEDULER_cancel (verify_successor);
-    verify_successor = GNUNET_SCHEDULER_NO_TASK;
-  }
 }
 
 
 /**
- * FIXME: I want to remove const but at the moment its giving error
- * in client file. 
  * Get my identity
  *
  * @return my identity
  */
-struct GNUNET_PeerIdentity *
+struct GNUNET_PeerIdentity
 GDS_NEIGHBOURS_get_my_id (void)
 {
-  return &my_identity;
+  return my_identity;
 }
-
-
-/* end of gnunet-service-xdht_neighbours.c */