Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / rps / gnunet-service-rps_peers.c
index c5a19d978adef1c6f44ffc3cc07b5f20f577a58b..e0b278bd00225d9cfc85281cedfe4360409cde47 100644 (file)
@@ -24,6 +24,7 @@
  * @author Julius Bünger
  */
 #include "platform.h"
+#include "gnunet_applications.h"
 #include "gnunet_util_lib.h"
 #include "gnunet_cadet_service.h"
 #include <inttypes.h>
 
 
 
-#define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
+#define LOG(kind, ...) GNUNET_log_from(kind,"rps-peers",__VA_ARGS__)
 
 
 /**
  * Set a peer flag of given peer context.
  */
-#define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
+#define set_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) |= (mask))
 
 /**
  * Get peer flag of given peer context.
  */
-#define check_peer_flag_set(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
+#define check_peer_flag_set(peer_ctx, mask)\
+  ((peer_ctx->peer_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
 
 /**
  * Unset flag of given peer context.
  */
-#define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
+#define unset_peer_flag(peer_ctx, mask) ((peer_ctx->peer_flags) &= ~(mask))
 
 /**
  * Set a channel flag of given channel context.
  */
-#define set_channel_flag(channel_flags, mask) ((*channel_flags) |= mask)
+#define set_channel_flag(channel_flags, mask) ((*channel_flags) |= (mask))
 
 /**
  * Get channel flag of given channel context.
  */
-#define check_channel_flag_set(channel_flags, mask) ((*channel_flags) & mask ? GNUNET_YES : GNUNET_NO)
+#define check_channel_flag_set(channel_flags, mask)\
+  ((*channel_flags) & (mask) ? GNUNET_YES : GNUNET_NO)
 
 /**
  * Unset flag of given channel context.
  */
-#define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= (~mask))
+#define unset_channel_flag(channel_flags, mask) ((*channel_flags) &= ~(mask))
 
 
 
@@ -161,7 +164,7 @@ struct PeerContext
    *
    * To be canceled on shutdown.
    */
-  struct GNUNET_CADET_TransmitHandle *transmit_handle;
+  struct PendingMessage *liveliness_check_pending;
 
   /**
    * Number of pending operations.
@@ -172,7 +175,7 @@ struct PeerContext
    * Identity of the peer
    */
   struct GNUNET_PeerIdentity peer_id;
-  
+
   /**
    * Flags indicating status of peer
    */
@@ -201,6 +204,37 @@ struct PeerContext
    */
 };
 
+/**
+ * @brief Closure to #valid_peer_iterator
+ */
+struct PeersIteratorCls
+{
+  /**
+   * Iterator function
+   */
+  PeersIterator iterator;
+
+  /**
+   * Closure to iterator
+   */
+  void *cls;
+};
+
+/**
+ * @brief Hashmap of valid peers.
+ */
+static struct GNUNET_CONTAINER_MultiPeerMap *valid_peers;
+
+/**
+ * @brief Maximum number of valid peers to keep.
+ * TODO read from config
+ */
+static uint32_t num_valid_peers_max = UINT32_MAX;
+
+/**
+ * @brief Filename of the file that stores the valid peers persistently.
+ */
+static char *filename_valid_peers;
 
 /**
  * Set of all peers to keep track of them.
@@ -218,7 +252,6 @@ static const struct GNUNET_PeerIdentity *own_identity;
 static struct GNUNET_CADET_Handle *cadet_handle;
 
 
-
 /**
  * @brief Get the #PeerContext associated with a peer
  *
@@ -239,6 +272,7 @@ get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
   return ctx;
 }
 
+
 /**
  * @brief Create a new #PeerContext and insert it into the peer map
  *
@@ -264,6 +298,7 @@ create_peer_ctx (const struct GNUNET_PeerIdentity *peer)
   return ctx;
 }
 
+
 /**
  * @brief Create or get a #PeerContext
  *
@@ -281,11 +316,152 @@ create_or_get_peer_ctx (const struct GNUNET_PeerIdentity *peer)
   return get_peer_ctx (peer);
 }
 
+
+/**
+ * @brief Check whether we have a connection to this @a peer
+ *
+ * Also sets the #Peers_ONLINE flag accordingly
+ *
+ * @param peer the peer in question
+ *
+ * @return #GNUNET_YES if we are connected
+ *         #GNUNET_NO  otherwise
+ */
+int
+Peers_check_connected (const struct GNUNET_PeerIdentity *peer)
+{
+  const struct PeerContext *peer_ctx;
+
+  /* If we don't know about this peer we don't know whether it's online */
+  if (GNUNET_NO == Peers_check_peer_known (peer))
+  {
+    return GNUNET_NO;
+  }
+  /* Get the context */
+  peer_ctx = get_peer_ctx (peer);
+  /* If we have no channel to this peer we don't know whether it's online */
+  if ( (NULL == peer_ctx->send_channel) &&
+       (NULL == peer_ctx->recv_channel) )
+  {
+    Peers_unset_peer_flag (peer, Peers_ONLINE);
+    return GNUNET_NO;
+  }
+  /* Otherwise (if we have a channel, we know that it's online */
+  Peers_set_peer_flag (peer, Peers_ONLINE);
+  return GNUNET_YES;
+}
+
+
+/**
+ * @brief The closure to #get_rand_peer_iterator.
+ */
+struct GetRandPeerIteratorCls
+{
+  /**
+   * @brief The index of the peer to return.
+   * Will be decreased until 0.
+   * Then current peer is returned.
+   */
+  uint32_t index;
+
+  /**
+   * @brief Pointer to peer to return.
+   */
+  const struct GNUNET_PeerIdentity *peer;
+};
+
+
+/**
+ * @brief Iterator function for #get_random_peer_from_peermap.
+ *
+ * Implements #GNUNET_CONTAINER_PeerMapIterator.
+ * Decreases the index until the index is null.
+ * Then returns the current peer.
+ *
+ * @param cls the #GetRandPeerIteratorCls containing index and peer
+ * @param peer current peer
+ * @param value unused
+ *
+ * @return  #GNUNET_YES if we should continue to
+ *          iterate,
+ *          #GNUNET_NO if not.
+ */
+static int
+get_rand_peer_iterator (void *cls,
+                        const struct GNUNET_PeerIdentity *peer,
+                        void *value)
+{
+  struct GetRandPeerIteratorCls *iterator_cls = cls;
+  if (0 >= iterator_cls->index)
+  {
+    iterator_cls->peer = peer;
+    return GNUNET_NO;
+  }
+  iterator_cls->index--;
+  return GNUNET_YES;
+}
+
+
+/**
+ * @brief Get a random peer from @a peer_map
+ *
+ * @param peer_map the peer_map to get the peer from
+ *
+ * @return a random peer
+ */
+static const struct GNUNET_PeerIdentity *
+get_random_peer_from_peermap (const struct
+                              GNUNET_CONTAINER_MultiPeerMap *peer_map)
+{
+  struct GetRandPeerIteratorCls *iterator_cls;
+  const struct GNUNET_PeerIdentity *ret;
+
+  iterator_cls = GNUNET_new (struct GetRandPeerIteratorCls);
+  iterator_cls->index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
+      GNUNET_CONTAINER_multipeermap_size (peer_map));
+  (void) GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
+                                                get_rand_peer_iterator,
+                                                iterator_cls);
+  ret = iterator_cls->peer;
+  GNUNET_free (iterator_cls);
+  return ret;
+}
+
+
+/**
+ * @brief Add a given @a peer to valid peers.
+ *
+ * If valid peers are already #num_valid_peers_max, delete a peer previously.
+ *
+ * @param peer the peer that is added to the valid peers.
+ *
+ * @return #GNUNET_YES if no other peer had to be removed
+ *         #GNUNET_NO  otherwise
+ */
+static int
+add_valid_peer (const struct GNUNET_PeerIdentity *peer)
+{
+  const struct GNUNET_PeerIdentity *rand_peer;
+  int ret;
+
+  ret = GNUNET_YES;
+  while (GNUNET_CONTAINER_multipeermap_size (valid_peers) >= num_valid_peers_max)
+  {
+    rand_peer = get_random_peer_from_peermap (valid_peers);
+    GNUNET_CONTAINER_multipeermap_remove_all (valid_peers, rand_peer);
+    ret = GNUNET_NO;
+  }
+  (void) GNUNET_CONTAINER_multipeermap_put (valid_peers, peer, NULL,
+      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
+  return ret;
+}
+
+
 /**
  * @brief Set the peer flag to living and
  *        call the pending operations on this peer.
  *
- * Also sets the #Peers_VALID flag
+ * Also adds peer to #valid_peers.
  *
  * @param peer_ctx the #PeerContext of the peer to set live
  */
@@ -295,19 +471,25 @@ set_peer_live (struct PeerContext *peer_ctx)
   struct GNUNET_PeerIdentity *peer;
   unsigned int i;
 
-  /* Cancle cadet transmit_handle if still scheduled */
-  if (NULL != peer_ctx->transmit_handle)
+  peer = &peer_ctx->peer_id;
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+      "Peer %s is live and valid, calling %i pending operations on it\n",
+      GNUNET_i2s (peer),
+      peer_ctx->num_pending_ops);
+
+  if (NULL != peer_ctx->liveliness_check_pending)
   {
-    GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
-    peer_ctx->transmit_handle = NULL;
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+         "Removing pending liveliness check for peer %s\n",
+         GNUNET_i2s (&peer_ctx->peer_id));
+    // TODO wait until cadet sets mq->cancel_impl
+    //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
+    GNUNET_free (peer_ctx->liveliness_check_pending);
+    peer_ctx->liveliness_check_pending = NULL;
   }
 
-  peer = &peer_ctx->peer_id;
-  set_peer_flag (peer_ctx, Peers_VALID);
-  // TODO LIVE/ONLINE
-  LOG (GNUNET_ERROR_TYPE_DEBUG,
-      "Peer %s is live and valid\n",
-      GNUNET_i2s (peer));
+  (void) add_valid_peer (peer);
+  set_peer_flag (peer_ctx, Peers_ONLINE);
 
   /* Call pending operations */
   for (i = 0; i < peer_ctx->num_pending_ops; i++)
@@ -317,6 +499,7 @@ set_peer_live (struct PeerContext *peer_ctx)
   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
 }
 
+
 /**
  * @brief Get the channel of a peer. If not existing, create.
  *
@@ -327,6 +510,7 @@ struct GNUNET_CADET_Channel *
 get_channel (const struct GNUNET_PeerIdentity *peer)
 {
   struct PeerContext *peer_ctx;
+  struct GNUNET_HashCode port;
 
   peer_ctx = get_peer_ctx (peer);
   if (NULL == peer_ctx->send_channel)
@@ -334,22 +518,27 @@ get_channel (const struct GNUNET_PeerIdentity *peer)
     LOG (GNUNET_ERROR_TYPE_DEBUG,
          "Trying to establish channel to peer %s\n",
          GNUNET_i2s (peer));
+    GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_RPS,
+                        strlen (GNUNET_APPLICATION_PORT_RPS),
+                        &port);
     peer_ctx->send_channel =
       GNUNET_CADET_channel_create (cadet_handle,
                                    peer_ctx->send_channel_flags, /* context */
                                    peer,
-                                   GNUNET_RPS_CADET_PORT,
+                                   &port,
                                    GNUNET_CADET_OPTION_RELIABLE);
   }
+  GNUNET_assert (NULL != peer_ctx->send_channel);
   return peer_ctx->send_channel;
 }
 
+
 /**
  * Get the message queue (#GNUNET_MQ_Handle) of a specific peer.
  *
  * If we already have a message queue open to this client,
  * simply return it, otherways create one.
- * 
+ *
  * @param peer the peer to get the mq to
  * @return the #GNUNET_MQ_Handle
  */
@@ -359,7 +548,6 @@ get_mq (const struct GNUNET_PeerIdentity *peer)
   struct PeerContext *peer_ctx;
 
   peer_ctx = get_peer_ctx (peer);
-  GNUNET_assert (NULL == peer_ctx->transmit_handle);
 
   if (NULL == peer_ctx->mq)
   {
@@ -369,52 +557,27 @@ get_mq (const struct GNUNET_PeerIdentity *peer)
   return peer_ctx->mq;
 }
 
+
 /**
- * @brief Callback that is called when a channel was effectively established.
+ * @brief This is called in response to the first message we sent as a
+ * liveliness check.
  *
- * This is an implementation of #GNUNET_CONNECTION_TransmitReadyNotify and
- * given to #GNUNET_CADET_notify_transmit_ready_cancel and called when the
- * channel was successfully established.
- *
- * This function type was originally ment to be called to provide the data to
- * be sent. This is called when the connection is ready to queue more data.
- * However we use it to get notified about the successful establishement of a
- * cadet channel.
- *
- * @a buf will be NULL and @a size zero if the
- * connection was closed for writing in the meantime.
- *
- * @param cls closure
- * @param size number of bytes available in @a buf
- * @param buf where the callee should write the message
- * @return number of bytes written to @a buf
+ * @param cls #PeerContext of peer with pending liveliness check
  */
-//TODO
-static size_t
-cadet_notify_transmit_ready_cb (void *cls, size_t size, void *buf)
+static void
+mq_liveliness_check_successful (void *cls)
 {
-  struct PeerContext *peer_ctx = (struct PeerContext *) cls;
-  // TODO make sure the context is not deleted or the establishing of the
-  //      channel is cancelled
+  struct PeerContext *peer_ctx = cls;
 
-  peer_ctx->transmit_handle = NULL;
-  LOG (GNUNET_ERROR_TYPE_DEBUG,
-       "Set ->transmit_handle = NULL for peer %s\n",
-       GNUNET_i2s (&peer_ctx->peer_id));
-
-  if ( (NULL != buf) &&
-       (0 != size) )
+  if (NULL != peer_ctx->liveliness_check_pending)
   {
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        "Liveliness check for peer %s was successfull\n",
+        GNUNET_i2s (&peer_ctx->peer_id));
+    GNUNET_free (peer_ctx->liveliness_check_pending);
+    peer_ctx->liveliness_check_pending = NULL;
     set_peer_live (peer_ctx);
   }
-  else
-  {
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Problems establishing a connection to peer %s in order to check liveliness\n",
-         GNUNET_i2s (&peer_ctx->peer_id));
-    // TODO reschedule? cleanup?
-  }
-  return 0;
 }
 
 /**
@@ -429,24 +592,19 @@ check_peer_live (struct PeerContext *peer_ctx)
        "Get informed about peer %s getting live\n",
        GNUNET_i2s (&peer_ctx->peer_id));
 
-  if (NULL == peer_ctx->transmit_handle &&
-      NULL == peer_ctx->send_channel)
-  {
-    (void) get_channel (&peer_ctx->peer_id);
-    peer_ctx->transmit_handle =
-        GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
-                                            GNUNET_NO,
-                                            GNUNET_TIME_UNIT_FOREVER_REL,
-                                            sizeof (struct GNUNET_MessageHeader),
-                                            cadet_notify_transmit_ready_cb,
-                                            peer_ctx);
-  }
-  else if (NULL != peer_ctx->transmit_handle)
-    LOG (GNUNET_ERROR_TYPE_DEBUG,
-         "Already waiting for notification\n");
-  else if (NULL != peer_ctx->send_channel)
-    LOG (GNUNET_ERROR_TYPE_DEBUG,
-         "Already have established channel to peer\n");
+  struct GNUNET_MQ_Handle *mq;
+  struct GNUNET_MQ_Envelope *ev;
+
+  ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_CHECK_LIVE);
+  peer_ctx->liveliness_check_pending = GNUNET_new (struct PendingMessage);
+  peer_ctx->liveliness_check_pending->ev = ev;
+  peer_ctx->liveliness_check_pending->peer_ctx = peer_ctx;
+  peer_ctx->liveliness_check_pending->type = "Check liveliness";
+  mq = get_mq (&peer_ctx->peer_id);
+  GNUNET_MQ_notify_sent (ev,
+                         mq_liveliness_check_successful,
+                         peer_ctx);
+  GNUNET_MQ_send (mq, ev);
 }
 
 /**
@@ -476,6 +634,7 @@ insert_pending_message (const struct GNUNET_PeerIdentity *peer,
   return pending_msg;
 }
 
+
 /**
  * @brief Remove a pending message from the respective DLL
  *
@@ -496,6 +655,7 @@ remove_pending_message (struct PendingMessage *pending_msg)
   GNUNET_free (pending_msg);
 }
 
+
 /**
  * @brief Check whether function of type #PeerOp was already scheduled
  *
@@ -522,6 +682,7 @@ check_operation_scheduled (const struct GNUNET_PeerIdentity *peer,
   return GNUNET_NO;
 }
 
+
 /**
  * Iterator over hash map entries. Deletes all contexts of peers.
  *
@@ -540,6 +701,7 @@ peermap_clear_iterator (void *cls,
   return GNUNET_YES;
 }
 
+
 /**
  * @brief This is called once a message is sent.
  *
@@ -558,21 +720,234 @@ mq_notify_sent_cb (void *cls)
 }
 
 
+/**
+ * @brief Iterator function for #store_valid_peers.
+ *
+ * Implements #GNUNET_CONTAINER_PeerMapIterator.
+ * Writes single peer to disk.
+ *
+ * @param cls the file handle to write to.
+ * @param peer current peer
+ * @param value unused
+ *
+ * @return  #GNUNET_YES if we should continue to
+ *          iterate,
+ *          #GNUNET_NO if not.
+ */
+static int
+store_peer_presistently_iterator (void *cls,
+                                  const struct GNUNET_PeerIdentity *peer,
+                                  void *value)
+{
+  const struct GNUNET_DISK_FileHandle *fh = cls;
+  char peer_string[128];
+  int size;
+  ssize_t ret;
+
+  if (NULL == peer)
+  {
+    return GNUNET_YES;
+  }
+  size = GNUNET_snprintf (peer_string,
+                          sizeof (peer_string),
+                          "%s\n",
+                          GNUNET_i2s_full (peer));
+  GNUNET_assert (53 == size);
+  ret = GNUNET_DISK_file_write (fh,
+                                peer_string,
+                                size);
+  GNUNET_assert (size == ret);
+  return GNUNET_YES;
+}
+
+
+/**
+ * @brief Store the peers currently in #valid_peers to disk.
+ */
+static void
+store_valid_peers ()
+{
+  struct GNUNET_DISK_FileHandle *fh;
+  uint32_t number_written_peers;
+  int ret;
+
+  if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
+  {
+    return;
+  }
+
+  ret = GNUNET_DISK_directory_create_for_file (filename_valid_peers);
+  if (GNUNET_SYSERR == ret)
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Not able to create directory for file `%s'\n",
+        filename_valid_peers);
+    GNUNET_break (0);
+  }
+  else if (GNUNET_NO == ret)
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Directory for file `%s' exists but is not writable for us\n",
+        filename_valid_peers);
+    GNUNET_break (0);
+  }
+  fh = GNUNET_DISK_file_open (filename_valid_peers,
+                              GNUNET_DISK_OPEN_WRITE |
+                                  GNUNET_DISK_OPEN_CREATE,
+                              GNUNET_DISK_PERM_USER_READ |
+                                  GNUNET_DISK_PERM_USER_WRITE);
+  if (NULL == fh)
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Not able to write valid peers to file `%s'\n",
+        filename_valid_peers);
+    return;
+  }
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+      "Writing %u valid peers to disk\n",
+      GNUNET_CONTAINER_multipeermap_size (valid_peers));
+  number_written_peers =
+    GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
+                                           store_peer_presistently_iterator,
+                                           fh);
+  GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
+  GNUNET_assert (number_written_peers ==
+      GNUNET_CONTAINER_multipeermap_size (valid_peers));
+}
+
+
+/**
+ * @brief Convert string representation of peer id to peer id.
+ *
+ * Counterpart to #GNUNET_i2s_full.
+ *
+ * @param string_repr The string representation of the peer id
+ *
+ * @return The peer id
+ */
+static const struct GNUNET_PeerIdentity *
+s2i_full (const char *string_repr)
+{
+  struct GNUNET_PeerIdentity *peer;
+  size_t len;
+  int ret;
+
+  peer = GNUNET_new (struct GNUNET_PeerIdentity);
+  len = strlen (string_repr);
+  if (52 > len)
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Not able to convert string representation of PeerID to PeerID\n"
+        "Sting representation: %s (len %u) - too short\n",
+        string_repr,
+        len);
+    GNUNET_break (0);
+  }
+  else if (52 < len)
+  {
+    len = 52;
+  }
+  ret = GNUNET_CRYPTO_eddsa_public_key_from_string (string_repr,
+                                                    len,
+                                                    &peer->public_key);
+  if (GNUNET_OK != ret)
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Not able to convert string representation of PeerID to PeerID\n"
+        "Sting representation: %s\n",
+        string_repr);
+    GNUNET_break (0);
+  }
+  return peer;
+}
+
+
+/**
+ * @brief Restore the peers on disk to #valid_peers.
+ */
+static void
+restore_valid_peers ()
+{
+  off_t file_size;
+  uint32_t num_peers;
+  struct GNUNET_DISK_FileHandle *fh;
+  char *buf;
+  ssize_t size_read;
+  char *iter_buf;
+  char *str_repr;
+  const struct GNUNET_PeerIdentity *peer;
+
+  if (0 == strncmp ("DISABLE", filename_valid_peers, 7))
+  {
+    return;
+  }
+
+  if (GNUNET_OK != GNUNET_DISK_file_test (filename_valid_peers))
+  {
+    return;
+  }
+  fh = GNUNET_DISK_file_open (filename_valid_peers,
+                              GNUNET_DISK_OPEN_READ,
+                              GNUNET_DISK_PERM_NONE);
+  GNUNET_assert (NULL != fh);
+  GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &file_size));
+  num_peers = file_size / 53;
+  buf = GNUNET_malloc (file_size);
+  size_read = GNUNET_DISK_file_read (fh, buf, file_size);
+  GNUNET_assert (size_read == file_size);
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+      "Restoring %" PRIu32 " peers from file `%s'\n",
+      num_peers,
+      filename_valid_peers);
+  for (iter_buf = buf; iter_buf < buf + file_size - 1; iter_buf += 53)
+  {
+    str_repr = GNUNET_strndup (iter_buf, 53);
+    peer = s2i_full (str_repr);
+    GNUNET_free (str_repr);
+    add_valid_peer (peer);
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        "Restored valid peer %s from disk\n",
+        GNUNET_i2s_full (peer));
+  }
+  iter_buf = NULL;
+  GNUNET_free (buf);
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+      "num_peers: %" PRIu32 ", _size (valid_peers): %u\n",
+      num_peers,
+      GNUNET_CONTAINER_multipeermap_size (valid_peers));
+  if (num_peers != GNUNET_CONTAINER_multipeermap_size (valid_peers))
+  {
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "Number of restored peers does not match file size. Have probably duplicates.\n");
+  }
+  GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh));
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+      "Restored %u valid peers from disk\n",
+      GNUNET_CONTAINER_multipeermap_size (valid_peers));
+}
+
+
 /**
  * @brief Initialise storage of peers
  *
+ * @param fn_valid_peers filename of the file used to store valid peer ids
  * @param cadet_h cadet handle
  * @param own_id own peer identity
  */
 void
-Peers_initialise (struct GNUNET_CADET_Handle *cadet_h,
+Peers_initialise (char* fn_valid_peers,
+                  struct GNUNET_CADET_Handle *cadet_h,
                   const struct GNUNET_PeerIdentity *own_id)
 {
+  filename_valid_peers = GNUNET_strdup (fn_valid_peers);
   cadet_handle = cadet_h;
   own_identity = own_id;
   peer_map = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
+  valid_peers = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
+  restore_valid_peers ();
 }
 
+
 /**
  * @brief Delete storage of peers that was created with #Peers_initialise ()
  */
@@ -588,8 +963,60 @@ Peers_terminate ()
         "Iteration destroying peers was aborted.\n");
   }
   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
+  store_valid_peers ();
+  GNUNET_free (filename_valid_peers);
+  GNUNET_CONTAINER_multipeermap_destroy (valid_peers);
+}
+
+
+/**
+ * Iterator over #valid_peers hash map entries.
+ *
+ * @param cls closure - unused
+ * @param peer current peer id
+ * @param value value in the hash map - unused
+ * @return #GNUNET_YES if we should continue to
+ *         iterate,
+ *         #GNUNET_NO if not.
+ */
+static int
+valid_peer_iterator (void *cls,
+                     const struct GNUNET_PeerIdentity *peer,
+                     void *value)
+{
+  struct PeersIteratorCls *it_cls = cls;
+
+  return it_cls->iterator (it_cls->cls,
+                           peer);
+}
+
+
+/**
+ * @brief Get all currently known, valid peer ids.
+ *
+ * @param it function to call on each peer id
+ * @param it_cls extra argument to @a it
+ * @return the number of key value pairs processed,
+ *         #GNUNET_SYSERR if it aborted iteration
+ */
+int
+Peers_get_valid_peers (PeersIterator iterator,
+                       void *it_cls)
+{
+  struct PeersIteratorCls *cls;
+  int ret;
+
+  cls = GNUNET_new (struct PeersIteratorCls);
+  cls->iterator = iterator;
+  cls->cls = it_cls;
+  ret = GNUNET_CONTAINER_multipeermap_iterate (valid_peers,
+                                               valid_peer_iterator,
+                                               cls);
+  GNUNET_free (cls);
+  return ret;
 }
 
+
 /**
  * @brief Add peer to known peers.
  *
@@ -599,7 +1026,8 @@ Peers_terminate ()
  * @param peer the new #GNUNET_PeerIdentity
  *
  * @return #GNUNET_YES if peer was inserted
- *         #GNUNET_NO  if peer was already known
+ *         #GNUNET_NO  otherwise (if peer was already known or
+ *                     peer was #own_identity)
  */
 int
 Peers_insert_peer (const struct GNUNET_PeerIdentity *peer)
@@ -615,56 +1043,56 @@ Peers_insert_peer (const struct GNUNET_PeerIdentity *peer)
 
 
 /**
- * @brief Add peer to known peers and check for liveliness.
+ * @brief Try connecting to a peer to see whether it is online
  *
- * This function is called on new peer_ids from 'external' sources
- * (client seed, cadet get_peers(), ...)
- *
- * @param peer the new #GNUNET_PeerIdentity
+ * If not known yet, insert into known peers
  *
- * @return #GNUNET_YES if peer was inserted
- *         #GNUNET_NO  if peer was already known
+ * @param peer the peer whose liveliness is to be checked
+ * @return #GNUNET_YES if peer had to be inserted
+ *         #GNUNET_NO  otherwise (if peer was already known or
+ *                     peer was #own_identity)
  */
 int
-Peers_insert_peer_check_liveliness (const struct GNUNET_PeerIdentity *peer)
+Peers_issue_peer_liveliness_check (const struct GNUNET_PeerIdentity *peer)
 {
   struct PeerContext *peer_ctx;
   int ret;
 
-  ret = Peers_insert_peer (peer);
   if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, own_identity))
   {
-    return ret;
+    return GNUNET_NO;
   }
+  ret = Peers_insert_peer (peer);
   peer_ctx = get_peer_ctx (peer);
-  if (GNUNET_NO == check_peer_flag_set (peer_ctx, Peers_VALID))
+  if (GNUNET_NO == Peers_check_peer_flag (peer, Peers_ONLINE))
   {
     check_peer_live (peer_ctx);
   }
   return ret;
 }
 
+
 /**
- * @brief Remove unecessary data
+ * @brief Check if peer is removable.
  *
- * If the other peer is not intending to send messages, we have messages pending
- * to be sent to this peer and we are not waiting for a reply, remove the
- * information about it (its #PeerContext).
+ * Check if
+ *  - a recv channel exists
+ *  - there are pending messages
+ *  - there is no pending pull reply
  *
- * @param peer the peer to clean
- * @return #GNUNET_YES if peer was removed
- *         #GNUNET_NO  otherwise
+ * @param peer the peer in question
+ * @return #GNUNET_YES    if peer is removable
+ *         #GNUNET_NO     if peer is NOT removable
+ *         #GNUNET_SYSERR if peer is not known
  */
 int
-Peers_clean_peer (const struct GNUNET_PeerIdentity *peer)
+Peers_check_removable (const struct GNUNET_PeerIdentity *peer)
 {
   struct PeerContext *peer_ctx;
 
-  // TODO actually remove unnecessary data
-
-  if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer)) 
+  if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
   {
-    return GNUNET_NO;
+    return GNUNET_SYSERR;
   }
 
   peer_ctx = get_peer_ctx (peer);
@@ -674,13 +1102,13 @@ Peers_clean_peer (const struct GNUNET_PeerIdentity *peer)
   {
     return GNUNET_NO;
   }
-  Peers_remove_peer (peer);
   return GNUNET_YES;
 }
 
+
 /**
  * @brief Remove peer
- * 
+ *
  * @param peer the peer to clean
  * @return #GNUNET_YES if peer was removed
  *         #GNUNET_NO  otherwise
@@ -690,7 +1118,7 @@ Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
 {
   struct PeerContext *peer_ctx;
 
-  if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer)) 
+  if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
   {
     return GNUNET_NO;
   }
@@ -700,10 +1128,9 @@ Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
   LOG (GNUNET_ERROR_TYPE_DEBUG,
        "Going to remove peer %s\n",
        GNUNET_i2s (&peer_ctx->peer_id));
+  Peers_unset_peer_flag (peer, Peers_ONLINE);
 
   GNUNET_array_grow (peer_ctx->pending_ops, peer_ctx->num_pending_ops, 0);
-  // TODO delete struct GNUNET_TRANSPORT_TransmitHandle *transmit_handle
-  /* Cancle messages that have not been sent yet */
   while (NULL != peer_ctx->pending_messages_head)
   {
     LOG (GNUNET_ERROR_TYPE_DEBUG,
@@ -713,21 +1140,27 @@ Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
   }
   /* If we are still waiting for notification whether this peer is live
    * cancel the according task */
-  if (NULL != peer_ctx->transmit_handle)
+  if (NULL != peer_ctx->liveliness_check_pending)
   {
     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
-         "Trying to cancle transmit_handle for peer %s\n",
+         "Removing pending liveliness check for peer %s\n",
          GNUNET_i2s (&peer_ctx->peer_id));
-    GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->transmit_handle);
-    peer_ctx->transmit_handle = NULL;
+    // TODO wait until cadet sets mq->cancel_impl
+    //GNUNET_MQ_send_cancel (peer_ctx->liveliness_check_pending->ev);
+    GNUNET_free (peer_ctx->liveliness_check_pending);
+    peer_ctx->liveliness_check_pending = NULL;
   }
   if (NULL != peer_ctx->send_channel)
   {
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        "Destroying send channel\n");
     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
     peer_ctx->send_channel = NULL;
   }
   if (NULL != peer_ctx->recv_channel)
   {
+    LOG (GNUNET_ERROR_TYPE_DEBUG,
+        "Destroying recv channel\n");
     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
     peer_ctx->recv_channel = NULL;
   }
@@ -748,6 +1181,7 @@ Peers_remove_peer (const struct GNUNET_PeerIdentity *peer)
   return GNUNET_YES;
 }
 
+
 /**
  * @brief set flags on a given peer.
  *
@@ -763,6 +1197,7 @@ Peers_set_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlag
   set_peer_flag (peer_ctx, flags);
 }
 
+
 /**
  * @brief unset flags on a given peer.
  *
@@ -778,20 +1213,26 @@ Peers_unset_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFl
   unset_peer_flag (peer_ctx, flags);
 }
 
+
 /**
  * @brief Check whether flags on a peer are set.
  *
  * @param peer the peer to check the flag of
  * @param flags the flags to check
  *
- * @return #GNUNET_YES if all given flags are set
- *         #GNUNET_NO  otherwise
+ * @return #GNUNET_SYSERR if peer is not known
+ *         #GNUNET_YES    if all given flags are set
+ *         #GNUNET_NO     otherwise
  */
 int
 Peers_check_peer_flag (const struct GNUNET_PeerIdentity *peer, enum Peers_PeerFlags flags)
 {
   struct PeerContext *peer_ctx;
 
+  if (GNUNET_NO == Peers_check_peer_known (peer))
+  {
+    return GNUNET_SYSERR;
+  }
   peer_ctx = get_peer_ctx (peer);
   return check_peer_flag_set (peer_ctx, flags);
 }
@@ -809,6 +1250,7 @@ Peers_set_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags)
   set_channel_flag (channel_flags, flags);
 }
 
+
 /**
  * @brief unset flags on a given channel.
  *
@@ -821,6 +1263,7 @@ Peers_unset_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags
   unset_channel_flag (channel_flags, flags);
 }
 
+
 /**
  * @brief Check whether flags on a channel are set.
  *
@@ -836,9 +1279,12 @@ Peers_check_channel_flag (uint32_t *channel_flags, enum Peers_ChannelFlags flags
   return check_channel_flag_set (channel_flags, flags);
 }
 
+
 /**
  * @brief Check whether we have information about the given peer.
  *
+ * FIXME probably deprecated. Make this the new _online.
+ *
  * @param peer peer in question
  *
  * @return #GNUNET_YES if peer is known
@@ -850,6 +1296,24 @@ Peers_check_peer_known (const struct GNUNET_PeerIdentity *peer)
   return GNUNET_CONTAINER_multipeermap_contains (peer_map, peer);
 }
 
+
+/**
+ * @brief Check whether @a peer is actually a peer.
+ *
+ * A valid peer is a peer that we know exists eg. we were connected to once.
+ *
+ * @param peer peer in question
+ *
+ * @return #GNUNET_YES if peer is valid
+ *         #GNUNET_NO  if peer is not valid
+ */
+int
+Peers_check_peer_valid (const struct GNUNET_PeerIdentity *peer)
+{
+  return GNUNET_CONTAINER_multipeermap_contains (valid_peers, peer);
+}
+
+
 /**
  * @brief Indicate that we want to send to the other peer
  *
@@ -864,6 +1328,7 @@ Peers_indicate_sending_intention (const struct GNUNET_PeerIdentity *peer)
   (void) get_channel (peer);
 }
 
+
 /**
  * @brief Check whether other peer has the intention to send/opened channel
  *        towars us
@@ -886,6 +1351,7 @@ Peers_check_peer_send_intention (const struct GNUNET_PeerIdentity *peer)
   return GNUNET_NO;
 }
 
+
 /**
  * Handle the channel a peer opens to us.
  *
@@ -902,7 +1368,7 @@ void *
 Peers_handle_inbound_channel (void *cls,
                               struct GNUNET_CADET_Channel *channel,
                               const struct GNUNET_PeerIdentity *initiator,
-                              uint32_t port,
+                              const struct GNUNET_HashCode *port,
                               enum GNUNET_CADET_ChannelOption options)
 {
   struct PeerContext *peer_ctx;
@@ -927,6 +1393,7 @@ Peers_handle_inbound_channel (void *cls,
   return peer_ctx->recv_channel_flags;
 }
 
+
 /**
  * @brief Check whether a sending channel towards the given peer exists
  *
@@ -952,6 +1419,7 @@ Peers_check_sending_channel_exists (const struct GNUNET_PeerIdentity *peer)
   return GNUNET_YES;
 }
 
+
 /**
  * @brief check whether the given channel is the sending channel of the given
  *        peer
@@ -989,6 +1457,7 @@ Peers_check_channel_role (const struct GNUNET_PeerIdentity *peer,
   return GNUNET_NO;
 }
 
+
 /**
  * @brief Destroy the send channel of a peer e.g. stop indicating a sending
  *        intention to another peer
@@ -1016,6 +1485,7 @@ Peers_destroy_sending_channel (const struct GNUNET_PeerIdentity *peer)
     set_channel_flag (peer_ctx->send_channel_flags, Peers_CHANNEL_CLEAN);
     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
     peer_ctx->send_channel = NULL;
+    (void) Peers_check_connected (peer);
     return GNUNET_YES;
   }
   return GNUNET_NO;
@@ -1024,9 +1494,6 @@ Peers_destroy_sending_channel (const struct GNUNET_PeerIdentity *peer)
 /**
  * This is called when a channel is destroyed.
  *
- * Removes peer completely from our knowledge if the send_channel was destroyed
- * Otherwise simply delete the recv_channel
- *
  * @param cls The closure
  * @param channel The channel being closed
  * @param channel_ctx The context associated with this channel
@@ -1050,13 +1517,12 @@ Peers_cleanup_destroyed_channel (void *cls,
        GNUNET_i2s (peer));
     return;
   }
-
   peer_ctx = get_peer_ctx (peer);
-  GNUNET_assert (NULL != peer_ctx); /* It could have been removed by shutdown_task */
 
   /* If our peer issued the destruction of the channel, the #Peers_TO_DESTROY
    * flag will be set. In this case simply make sure that the channels are
    * cleaned. */
+  /* FIXME This distinction seems to be redundant */
   if (Peers_check_peer_flag (peer, Peers_TO_DESTROY))
   {/* We initiatad the destruction of this particular peer */
     if (channel == peer_ctx->send_channel)
@@ -1064,6 +1530,18 @@ Peers_cleanup_destroyed_channel (void *cls,
     else if (channel == peer_ctx->recv_channel)
       peer_ctx->recv_channel = NULL;
 
+    if (NULL != peer_ctx->send_channel)
+    {
+      GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
+      peer_ctx->send_channel = NULL;
+    }
+    if (NULL != peer_ctx->recv_channel)
+    {
+      GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
+      peer_ctx->recv_channel = NULL;
+    }
+    /* Set the #Peers_ONLINE flag accordingly */
+    (void) Peers_check_connected (peer);
     return;
   }
 
@@ -1090,29 +1568,7 @@ Peers_cleanup_destroyed_channel (void *cls,
            GNUNET_i2s (peer));
     }
   }
-}
-
-/**
- * @brief Issue a check whether peer is live
- *
- * This tries to establish a channel to the given peer. Once the channel is
- * established successfully, we know the peer is live.
- *
- * @param peer the peer to check liveliness
- */
-void
-Peers_issue_peer_liveliness_check (const struct GNUNET_PeerIdentity *peer)
-{
-  struct PeerContext *peer_ctx;
-
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (peer, own_identity))
-  {
-    return; /* We know that we are online */
-  }
-
-  peer_ctx = create_or_get_peer_ctx (peer);
-  // TODO if LIVE/ONLINE
-  check_peer_live (peer_ctx);
+  (void) Peers_check_connected (peer);
 }
 
 /**
@@ -1133,7 +1589,7 @@ Peers_send_message (const struct GNUNET_PeerIdentity *peer,
   struct PendingMessage *pending_msg;
   struct GNUNET_MQ_Handle *mq;
 
-  pending_msg = insert_pending_message (peer, ev, "PULL REPLY");
+  pending_msg = insert_pending_message (peer, ev, type);
   mq = get_mq (peer);
   GNUNET_MQ_notify_sent (ev,
                          mq_notify_sent_cb,