Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
2fa42dc4f534bb9d8827d08f504a3b0cd51acd97
[simgrid.git] / examples / s4u / app-bittorrent / s4u-peer.cpp
1 /* Copyright (c) 2012-2020. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include <algorithm>
7 #include <array>
8 #include <climits>
9
10 #include "s4u-peer.hpp"
11 #include "s4u-tracker.hpp"
12
13 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_bt_peer, "Messages specific for the peers");
14
15 /*
16  * User parameters for transferred file data. For the test, the default values are :
17  * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
18  */
19 constexpr unsigned long FILE_PIECES   = 10UL;
20 constexpr unsigned long PIECES_BLOCKS = 5UL;
21 constexpr int BLOCK_SIZE              = 16384;
22
23 /** Number of blocks asked by each request */
24 constexpr unsigned long BLOCKS_REQUESTED = 2UL;
25
26 constexpr double SLEEP_DURATION     = 1.0;
27 #define BITS_TO_BYTES(x) (((x) / 8 + (x) % 8) ? 1 : 0)
28
29 Peer::Peer(std::vector<std::string> args)
30 {
31   // Check arguments
32   xbt_assert(args.size() == 3 || args.size() == 4, "Wrong number of arguments");
33   try {
34     id       = std::stoi(args[1]);
35     mailbox_ = simgrid::s4u::Mailbox::by_name(std::to_string(id));
36   } catch (const std::invalid_argument&) {
37     throw std::invalid_argument("Invalid ID:" + args[1]);
38   }
39   random.set_seed(id);
40
41   try {
42     deadline = std::stod(args[2]);
43   } catch (const std::invalid_argument&) {
44     throw std::invalid_argument("Invalid deadline:" + args[2]);
45   }
46   xbt_assert(deadline > 0, "Wrong deadline supplied");
47
48   if (args.size() == 4 && args[3] == "1") {
49     bitfield_       = (1U << FILE_PIECES) - 1U;
50     bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
51   }
52   pieces_count.resize(FILE_PIECES);
53
54   XBT_INFO("Hi, I'm joining the network with id %d", id);
55 }
56
57 /** Peer main function */
58 void Peer::operator()()
59 {
60   // Getting peer data from the tracker.
61   if (getPeersFromTracker()) {
62     XBT_DEBUG("Got %zu peers from the tracker. Current status is: %s", connected_peers.size(), getStatus().c_str());
63     begin_receive_time = simgrid::s4u::Engine::get_clock();
64     mailbox_->set_receiver(simgrid::s4u::Actor::self());
65     if (hasFinished()) {
66       sendHandshakeToAllPeers();
67     } else {
68       leech();
69     }
70     seed();
71   } else {
72     XBT_INFO("Couldn't contact the tracker.");
73   }
74
75   XBT_INFO("Here is my current status: %s", getStatus().c_str());
76 }
77
78 bool Peer::getPeersFromTracker()
79 {
80   simgrid::s4u::Mailbox* tracker_mailbox = simgrid::s4u::Mailbox::by_name(TRACKER_MAILBOX);
81   // Build the task to send to the tracker
82   auto* peer_request = new TrackerQuery(id, mailbox_);
83   try {
84     XBT_DEBUG("Sending a peer request to the tracker.");
85     tracker_mailbox->put(peer_request, TRACKER_COMM_SIZE, GET_PEERS_TIMEOUT);
86   } catch (const simgrid::TimeoutException&) {
87     XBT_DEBUG("Timeout expired when requesting peers to tracker");
88     delete peer_request;
89     return false;
90   }
91
92   try {
93     auto* answer = static_cast<TrackerAnswer*>(mailbox_->get(GET_PEERS_TIMEOUT));
94     // Add the peers the tracker gave us to our peer list.
95     for (auto const& peer_id : answer->getPeers())
96       if (id != peer_id)
97         connected_peers.emplace(peer_id, Connection(peer_id));
98     delete answer;
99   } catch (const simgrid::TimeoutException&) {
100     XBT_DEBUG("Timeout expired when requesting peers to tracker");
101     return false;
102   }
103   return true;
104 }
105
106 void Peer::sendHandshakeToAllPeers()
107 {
108   for (auto const& kv : connected_peers) {
109     const Connection& remote_peer = kv.second;
110     auto* handshake               = new Message(MESSAGE_HANDSHAKE, id, mailbox_);
111     remote_peer.mailbox_->put_init(handshake, MESSAGE_HANDSHAKE_SIZE)->detach();
112     XBT_DEBUG("Sending a HANDSHAKE to %d", remote_peer.id);
113   }
114 }
115
116 void Peer::sendMessage(simgrid::s4u::Mailbox* mailbox, e_message_type type, uint64_t size)
117 {
118   constexpr std::array<const char*, 6> type_names{
119       {"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED", "CANCEL"}};
120   XBT_DEBUG("Sending %s to %s", type_names[type], mailbox->get_cname());
121   mailbox->put_init(new Message(type, id, bitfield_, mailbox_), size)->detach();
122 }
123
124 void Peer::sendBitfield(simgrid::s4u::Mailbox* mailbox)
125 {
126   XBT_DEBUG("Sending a BITFIELD to %s", mailbox->get_cname());
127   mailbox
128       ->put_init(new Message(MESSAGE_BITFIELD, id, bitfield_, mailbox_),
129                  MESSAGE_BITFIELD_SIZE + BITS_TO_BYTES(FILE_PIECES))
130       ->detach();
131 }
132
133 void Peer::sendPiece(simgrid::s4u::Mailbox* mailbox, unsigned int piece, int block_index, int block_length)
134 {
135   xbt_assert(not hasNotPiece(piece), "Tried to send a unavailable piece.");
136   XBT_DEBUG("Sending the PIECE %u (%d,%d) to %s", piece, block_index, block_length, mailbox->get_cname());
137   mailbox->put_init(new Message(MESSAGE_PIECE, id, mailbox_, piece, block_index, block_length), BLOCK_SIZE)->detach();
138 }
139
140 void Peer::sendHaveToAllPeers(unsigned int piece)
141 {
142   XBT_DEBUG("Sending HAVE message to all my peers");
143   for (auto const& kv : connected_peers) {
144     const Connection& remote_peer = kv.second;
145     remote_peer.mailbox_->put_init(new Message(MESSAGE_HAVE, id, mailbox_, piece), MESSAGE_HAVE_SIZE)->detach();
146   }
147 }
148
149 void Peer::sendRequestTo(Connection* remote_peer, unsigned int piece)
150 {
151   remote_peer->current_piece = piece;
152   xbt_assert(remote_peer->hasPiece(piece));
153   int block_index = getFirstMissingBlockFrom(piece);
154   if (block_index != -1) {
155     int block_length = static_cast<int>(std::min(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index));
156     XBT_DEBUG("Sending a REQUEST to %s for piece %u (%d,%d)", remote_peer->mailbox_->get_cname(), piece, block_index,
157               block_length);
158     remote_peer->mailbox_
159         ->put_init(new Message(MESSAGE_REQUEST, id, mailbox_, piece, block_index, block_length), MESSAGE_REQUEST_SIZE)
160         ->detach();
161   }
162 }
163
164 std::string Peer::getStatus() const
165 {
166   std::string res;
167   for (unsigned i = 0; i < FILE_PIECES; i++)
168     res += (bitfield_ & (1U << i)) ? '1' : '0';
169   return res;
170 }
171
172 bool Peer::hasFinished() const
173 {
174   return bitfield_ == (1U << FILE_PIECES) - 1U;
175 }
176
177 /** Indicates if the remote peer has a piece not stored by the local peer */
178 bool Peer::isInterestedBy(const Connection* remote_peer) const
179 {
180   return remote_peer->bitfield & (bitfield_ ^ ((1 << FILE_PIECES) - 1));
181 }
182
183 bool Peer::isInterestedByFree(const Connection* remote_peer) const
184 {
185   for (unsigned int i = 0; i < FILE_PIECES; i++)
186     if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
187       return true;
188   return false;
189 }
190
191 void Peer::updatePiecesCountFromBitfield(unsigned int bitfield)
192 {
193   for (unsigned int i = 0; i < FILE_PIECES; i++)
194     if (bitfield & (1U << i))
195       pieces_count[i]++;
196 }
197
198 unsigned int Peer::countPieces(unsigned int bitfield) const
199 {
200   unsigned int count = 0U;
201   unsigned int n     = bitfield;
202   while (n) {
203     count += n & 1U;
204     n >>= 1U;
205   }
206   return count;
207 }
208
209 int Peer::nbInterestedPeers() const
210 {
211   int nb = 0;
212   for (auto const& kv : connected_peers)
213     if (kv.second.interested)
214       nb++;
215   return nb;
216 }
217
218 void Peer::leech()
219 {
220   double next_choked_update = simgrid::s4u::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
221   XBT_DEBUG("Start downloading.");
222
223   /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
224   sendHandshakeToAllPeers();
225   XBT_DEBUG("Starting main leech loop listening on mailbox: %s", mailbox_->get_cname());
226
227   void* data = nullptr;
228   while (simgrid::s4u::Engine::get_clock() < deadline && countPieces(bitfield_) < FILE_PIECES) {
229     if (comm_received == nullptr) {
230       comm_received = mailbox_->get_async(&data);
231     }
232     if (comm_received->test()) {
233       message = static_cast<Message*>(data);
234       handleMessage();
235       delete message;
236       comm_received = nullptr;
237     } else {
238       // We don't execute the choke algorithm if we don't already have a piece
239       if (simgrid::s4u::Engine::get_clock() >= next_choked_update && countPieces(bitfield_) > 0) {
240         updateChokedPeers();
241         next_choked_update += UPDATE_CHOKED_INTERVAL;
242       } else {
243         simgrid::s4u::this_actor::sleep_for(SLEEP_DURATION);
244       }
245     }
246   }
247   if (hasFinished())
248     XBT_DEBUG("%d becomes a seeder", id);
249 }
250
251 void Peer::seed()
252 {
253   double next_choked_update = simgrid::s4u::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
254   XBT_DEBUG("Start seeding.");
255   // start the main seed loop
256   void* data = nullptr;
257   while (simgrid::s4u::Engine::get_clock() < deadline) {
258     if (comm_received == nullptr) {
259       comm_received = mailbox_->get_async(&data);
260     }
261     if (comm_received->test()) {
262       message = static_cast<Message*>(data);
263       handleMessage();
264       delete message;
265       comm_received = nullptr;
266     } else {
267       if (simgrid::s4u::Engine::get_clock() >= next_choked_update) {
268         updateChokedPeers();
269         // TODO: Change the choked peer algorithm when seeding.
270         next_choked_update += UPDATE_CHOKED_INTERVAL;
271       } else {
272         simgrid::s4u::this_actor::sleep_for(SLEEP_DURATION);
273       }
274     }
275   }
276 }
277
278 void Peer::updateActivePeersSet(Connection* remote_peer)
279 {
280   if (remote_peer->interested && not remote_peer->choked_upload)
281     active_peers.insert(remote_peer);
282   else
283     active_peers.erase(remote_peer);
284 }
285
286 void Peer::handleMessage()
287 {
288   constexpr std::array<const char*, 10> type_names{{"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED",
289                                                     "HAVE", "BITFIELD", "REQUEST", "PIECE", "CANCEL"}};
290
291   XBT_DEBUG("Received a %s message from %s", type_names[message->type], message->return_mailbox->get_cname());
292
293   auto known_peer         = connected_peers.find(message->peer_id);
294   Connection* remote_peer = (known_peer == connected_peers.end()) ? nullptr : &known_peer->second;
295   xbt_assert(remote_peer != nullptr || message->type == MESSAGE_HANDSHAKE,
296              "The impossible did happened: A not-in-our-list peer sent us a message.");
297
298   switch (message->type) {
299     case MESSAGE_HANDSHAKE:
300       // Check if the peer is in our connection list.
301       if (remote_peer == nullptr) {
302         XBT_DEBUG("This peer %d was unknown, answer to its handshake", message->peer_id);
303         connected_peers.emplace(message->peer_id, Connection(message->peer_id));
304         sendMessage(message->return_mailbox, MESSAGE_HANDSHAKE, MESSAGE_HANDSHAKE_SIZE);
305       }
306       // Send our bitfield to the peer
307       sendBitfield(message->return_mailbox);
308       break;
309     case MESSAGE_BITFIELD:
310       // Update the pieces list
311       updatePiecesCountFromBitfield(message->bitfield);
312       // Store the bitfield
313       remote_peer->bitfield = message->bitfield;
314       xbt_assert(not remote_peer->am_interested, "Should not be interested at first");
315       if (isInterestedBy(remote_peer)) {
316         remote_peer->am_interested = true;
317         sendMessage(message->return_mailbox, MESSAGE_INTERESTED, MESSAGE_INTERESTED_SIZE);
318       }
319       break;
320     case MESSAGE_INTERESTED:
321       // Update the interested state of the peer.
322       remote_peer->interested = true;
323       updateActivePeersSet(remote_peer);
324       break;
325     case MESSAGE_NOTINTERESTED:
326       remote_peer->interested = false;
327       updateActivePeersSet(remote_peer);
328       break;
329     case MESSAGE_UNCHOKE:
330       xbt_assert(remote_peer->choked_download);
331       remote_peer->choked_download = false;
332       // Send requests to the peer, since it has unchoked us
333       if (remote_peer->am_interested)
334         requestNewPieceTo(remote_peer);
335       break;
336     case MESSAGE_CHOKE:
337       xbt_assert(not remote_peer->choked_download);
338       remote_peer->choked_download = true;
339       if (remote_peer->current_piece != -1)
340         removeCurrentPiece(remote_peer, remote_peer->current_piece);
341       break;
342     case MESSAGE_HAVE:
343       XBT_DEBUG("\t for piece %d", message->piece);
344       xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
345                  "Wrong HAVE message received");
346       remote_peer->bitfield = remote_peer->bitfield | (1U << static_cast<unsigned int>(message->piece));
347       pieces_count[message->piece]++;
348       // If the piece is in our pieces, we tell the peer that we are interested.
349       if (not remote_peer->am_interested && hasNotPiece(message->piece)) {
350         remote_peer->am_interested = true;
351         sendMessage(message->return_mailbox, MESSAGE_INTERESTED, MESSAGE_INTERESTED_SIZE);
352         if (not remote_peer->choked_download)
353           requestNewPieceTo(remote_peer);
354       }
355       break;
356     case MESSAGE_REQUEST:
357       xbt_assert(remote_peer->interested);
358       xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
359                  "Wrong HAVE message received");
360       if (not remote_peer->choked_upload) {
361         XBT_DEBUG("\t for piece %d (%d,%d)", message->piece, message->block_index,
362                   message->block_index + message->block_length);
363         if (not hasNotPiece(message->piece)) {
364           sendPiece(message->return_mailbox, message->piece, message->block_index, message->block_length);
365         }
366       } else {
367         XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
368       }
369       break;
370     case MESSAGE_PIECE:
371       XBT_DEBUG(" \t for piece %d (%d,%d)", message->piece, message->block_index,
372                 message->block_index + message->block_length);
373       xbt_assert(not remote_peer->choked_download);
374       xbt_assert(not remote_peer->choked_download, "Can't received a piece if I'm choked !");
375       xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
376                  "Wrong piece received");
377       // TODO: Execute a computation.
378       if (hasNotPiece(static_cast<unsigned int>(message->piece))) {
379         updateBitfieldBlocks(message->piece, message->block_index, message->block_length);
380         if (hasCompletedPiece(static_cast<unsigned int>(message->piece))) {
381           // Removing the piece from our piece list
382           removeCurrentPiece(remote_peer, message->piece);
383           // Setting the fact that we have the piece
384           bitfield_ = bitfield_ | (1U << static_cast<unsigned int>(message->piece));
385           XBT_DEBUG("My status is now %s", getStatus().c_str());
386           // Sending the information to all the peers we are connected to
387           sendHaveToAllPeers(message->piece);
388           // sending UNINTERESTED to peers that do not have what we want.
389           updateInterestedAfterReceive();
390         } else {                                      // piece not completed
391           sendRequestTo(remote_peer, message->piece); // ask for the next block
392         }
393       } else {
394         XBT_DEBUG("However, we already have it");
395         requestNewPieceTo(remote_peer);
396       }
397       break;
398     case MESSAGE_CANCEL:
399       break;
400     default:
401       THROW_IMPOSSIBLE;
402   }
403   // Update the peer speed.
404   if (remote_peer) {
405     remote_peer->addSpeedValue(1.0 / (simgrid::s4u::Engine::get_clock() - begin_receive_time));
406   }
407   begin_receive_time = simgrid::s4u::Engine::get_clock();
408 }
409
410 /** Selects the appropriate piece to download and requests it to the remote_peer */
411 void Peer::requestNewPieceTo(Connection* remote_peer)
412 {
413   int piece = selectPieceToDownload(remote_peer);
414   if (piece != -1) {
415     current_pieces |= (1U << (unsigned int)piece);
416     sendRequestTo(remote_peer, piece);
417   }
418 }
419
420 void Peer::removeCurrentPiece(Connection* remote_peer, unsigned int current_piece)
421 {
422   current_pieces &= ~(1U << current_piece);
423   remote_peer->current_piece = -1;
424 }
425
426 /** @brief Return the piece to be downloaded
427  * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
428  * If a piece is partially downloaded, this piece will be selected prioritarily
429  * If the peer has strictly less than 4 pieces, he chooses a piece at random.
430  * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
431  * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
432  * @param remote_peer: information about the connection
433  * @return the piece to download if possible. -1 otherwise
434  */
435 int Peer::selectPieceToDownload(const Connection* remote_peer)
436 {
437   int piece = partiallyDownloadedPiece(remote_peer);
438   // strict priority policy
439   if (piece != -1)
440     return piece;
441
442   // end game mode
443   if (countPieces(current_pieces) >= (FILE_PIECES - countPieces(bitfield_)) && isInterestedBy(remote_peer)) {
444     int nb_interesting_pieces = 0;
445     // compute the number of interesting pieces
446     for (unsigned int i = 0; i < FILE_PIECES; i++)
447       if (remotePeerHasMissingPiece(remote_peer, i))
448         nb_interesting_pieces++;
449
450     xbt_assert(nb_interesting_pieces != 0);
451     // get a random interesting piece
452     int random_piece_index = random.uniform_int(0, nb_interesting_pieces - 1);
453     int current_index      = 0;
454     for (unsigned int i = 0; i < FILE_PIECES; i++) {
455       if (remotePeerHasMissingPiece(remote_peer, i)) {
456         if (random_piece_index == current_index) {
457           piece = i;
458           break;
459         }
460         current_index++;
461       }
462     }
463     xbt_assert(piece != -1);
464     return piece;
465   }
466   // Random first policy
467   if (countPieces(bitfield_) < 4 && isInterestedByFree(remote_peer)) {
468     int nb_interesting_pieces = 0;
469     // compute the number of interesting pieces
470     for (unsigned int i = 0; i < FILE_PIECES; i++)
471       if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
472         nb_interesting_pieces++;
473     xbt_assert(nb_interesting_pieces != 0);
474     // get a random interesting piece
475     int random_piece_index = random.uniform_int(0, nb_interesting_pieces - 1);
476     int current_index      = 0;
477     for (unsigned int i = 0; i < FILE_PIECES; i++) {
478       if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i)) {
479         if (random_piece_index == current_index) {
480           piece = i;
481           break;
482         }
483         current_index++;
484       }
485     }
486     xbt_assert(piece != -1);
487     return piece;
488   } else { // Rarest first policy
489     short min         = SHRT_MAX;
490     int nb_min_pieces = 0;
491     int current_index = 0;
492     // compute the smallest number of copies of available pieces
493     for (unsigned int i = 0; i < FILE_PIECES; i++) {
494       if (pieces_count[i] < min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
495         min = pieces_count[i];
496     }
497
498     xbt_assert(min != SHRT_MAX || not isInterestedByFree(remote_peer));
499     // compute the number of rarest pieces
500     for (unsigned int i = 0; i < FILE_PIECES; i++)
501       if (pieces_count[i] == min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
502         nb_min_pieces++;
503
504     xbt_assert(nb_min_pieces != 0 || not isInterestedByFree(remote_peer));
505     // get a random rarest piece
506     int random_rarest_index = 0;
507     if (nb_min_pieces > 0) {
508       random_rarest_index = random.uniform_int(0, nb_min_pieces - 1);
509     }
510     for (unsigned int i = 0; i < FILE_PIECES; i++)
511       if (pieces_count[i] == min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i)) {
512         if (random_rarest_index == current_index) {
513           piece = i;
514           break;
515         }
516         current_index++;
517       }
518
519     xbt_assert(piece != -1 || not isInterestedByFree(remote_peer));
520     return piece;
521   }
522 }
523
524 void Peer::updateChokedPeers()
525 {
526   if (nbInterestedPeers() == 0)
527     return;
528   XBT_DEBUG("(%d) update_choked peers %zu active peers", id, active_peers.size());
529   // update the current round
530   round_                  = (round_ + 1) % 3;
531   Connection* chosen_peer = nullptr;
532   // select first active peer and remove it from the set
533   Connection* choked_peer;
534   if (active_peers.empty()) {
535     choked_peer = nullptr;
536   } else {
537     choked_peer = *active_peers.begin();
538     active_peers.erase(choked_peer);
539   }
540
541   /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
542   if (hasFinished()) {
543     double unchoke_time = simgrid::s4u::Engine::get_clock() + 1;
544     for (auto& kv : connected_peers) {
545       Connection& remote_peer = kv.second;
546       if (remote_peer.last_unchoke < unchoke_time && remote_peer.interested && remote_peer.choked_upload) {
547         unchoke_time = remote_peer.last_unchoke;
548         chosen_peer  = &remote_peer;
549       }
550     }
551   } else {
552     // Random optimistic unchoking
553     if (round_ == 0) {
554       int j = 0;
555       do {
556         // We choose a random peer to unchoke.
557         auto chosen_peer_it = connected_peers.begin();
558         std::advance(chosen_peer_it, random.uniform_int(0, static_cast<int>(connected_peers.size() - 1)));
559         chosen_peer = &chosen_peer_it->second;
560         if (not chosen_peer->interested || not chosen_peer->choked_upload)
561           chosen_peer = nullptr;
562         else
563           XBT_DEBUG("Nothing to do, keep going");
564         j++;
565       } while (chosen_peer == nullptr && j < MAXIMUM_PEERS);
566     } else {
567       // Use the "fastest download" policy.
568       double fastest_speed = 0.0;
569       for (auto& kv : connected_peers) {
570         Connection& remote_peer = kv.second;
571         if (remote_peer.peer_speed > fastest_speed && remote_peer.choked_upload && remote_peer.interested) {
572           fastest_speed = remote_peer.peer_speed;
573           chosen_peer   = &remote_peer;
574         }
575       }
576     }
577   }
578
579   if (chosen_peer != nullptr)
580     XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", id, chosen_peer->id,
581               chosen_peer->interested, chosen_peer->choked_upload);
582
583   if (choked_peer != chosen_peer) {
584     if (choked_peer != nullptr) {
585       xbt_assert(not choked_peer->choked_upload, "Tries to choked a choked peer");
586       choked_peer->choked_upload = true;
587       updateActivePeersSet(choked_peer);
588       XBT_DEBUG("(%d) Sending a CHOKE to %d", id, choked_peer->id);
589       sendMessage(choked_peer->mailbox_, MESSAGE_CHOKE, MESSAGE_CHOKE_SIZE);
590     }
591     if (chosen_peer != nullptr) {
592       xbt_assert((chosen_peer->choked_upload), "Tries to unchoked an unchoked peer");
593       chosen_peer->choked_upload = false;
594       active_peers.insert(chosen_peer);
595       chosen_peer->last_unchoke = simgrid::s4u::Engine::get_clock();
596       XBT_DEBUG("(%d) Sending a UNCHOKE to %d", id, chosen_peer->id);
597       updateActivePeersSet(chosen_peer);
598       sendMessage(chosen_peer->mailbox_, MESSAGE_UNCHOKE, MESSAGE_UNCHOKE_SIZE);
599     }
600   }
601 }
602
603 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.*/
604 void Peer::updateInterestedAfterReceive()
605 {
606   for (auto& kv : connected_peers) {
607     Connection& remote_peer = kv.second;
608     if (remote_peer.am_interested) {
609       bool interested = false;
610       // Check if the peer still has a piece we want.
611       for (unsigned int i = 0; i < FILE_PIECES; i++)
612         if (remotePeerHasMissingPiece(&remote_peer, i)) {
613           interested = true;
614           break;
615         }
616
617       if (not interested) { // no more piece to download from connection
618         remote_peer.am_interested = false;
619         sendMessage(remote_peer.mailbox_, MESSAGE_NOTINTERESTED, MESSAGE_NOTINTERESTED_SIZE);
620       }
621     }
622   }
623 }
624
625 void Peer::updateBitfieldBlocks(int piece, int block_index, int block_length)
626 {
627   xbt_assert((piece >= 0 && static_cast<unsigned int>(piece) <= FILE_PIECES), "Wrong piece.");
628   xbt_assert((block_index >= 0 && static_cast<unsigned int>(block_index) <= PIECES_BLOCKS), "Wrong block : %d.",
629              block_index);
630   for (int i = block_index; i < (block_index + block_length); i++)
631     bitfield_blocks |= (1ULL << static_cast<unsigned int>(piece * PIECES_BLOCKS + i));
632 }
633
634 bool Peer::hasCompletedPiece(unsigned int piece) const
635 {
636   for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
637     if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
638       return false;
639   return true;
640 }
641
642 int Peer::getFirstMissingBlockFrom(int piece) const
643 {
644   for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
645     if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
646       return i;
647   return -1;
648 }
649
650 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
651 int Peer::partiallyDownloadedPiece(const Connection* remote_peer) const
652 {
653   for (unsigned int i = 0; i < FILE_PIECES; i++)
654     if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i) && getFirstMissingBlockFrom(i) > 0)
655       return i;
656   return -1;
657 }