File: s4u-peer.cpp

package info (click to toggle)
simgrid 4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 38,980 kB
  • sloc: cpp: 123,583; ansic: 66,779; python: 8,358; java: 6,406; fortran: 6,079; f90: 5,123; xml: 4,587; sh: 2,337; perl: 1,436; makefile: 105; lisp: 49; javascript: 7; sed: 6
file content (669 lines) | stat: -rw-r--r-- 25,177 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
/* Copyright (c) 2012-2025. The SimGrid Team. All rights reserved.          */

/* This program is free software; you can redistribute it and/or modify it
 * under the terms of the license (GNU LGPL) which comes with this package. */

#include <algorithm>
#include <array>
#include <climits>

#include "s4u-peer.hpp"
#include "s4u-tracker.hpp"

XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_bt_peer, "Messages specific for the peers");
namespace sg4 = simgrid::s4u;

/*
 * User parameters for transferred file data. For the test, the default values are :
 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
 */
constexpr unsigned long FILE_PIECES   = 10UL;
constexpr unsigned long PIECES_BLOCKS = 5UL;
constexpr int BLOCK_SIZE              = 16384;

/** Number of blocks asked by each request */
constexpr unsigned long BLOCKS_REQUESTED = 2UL;

constexpr double SLEEP_DURATION     = 1.0;
#define BITS_TO_BYTES(x) (((x) / 8 + (x) % 8) ? 1 : 0)

/** Message sizes
 * Sizes based on report by A. Legout et al, Understanding BitTorrent: An Experimental Perspective
 * http://hal.inria.fr/inria-00000156/en
 */
constexpr unsigned message_size(MessageType type)
{
  constexpr std::array<unsigned, 10> sizes{{/* HANDSHAKE     */ 68,
                                            /* CHOKE         */ 5,
                                            /* UNCHOKE       */ 5,
                                            /* INTERESTED    */ 5,
                                            /* NOTINTERESTED */ 5,
                                            /* HAVE          */ 9,
                                            /* BITFIELD      */ 5,
                                            /* REQUEST       */ 17,
                                            /* PIECE         */ 13,
                                            /* CANCEL        */ 17}};
  return sizes.at(static_cast<int>(type));
}

constexpr const char* message_name(MessageType type)
{
  constexpr std::array<const char*, 10> names{{"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED", "HAVE",
                                               "BITFIELD", "REQUEST", "PIECE", "CANCEL"}};
  return names.at(static_cast<int>(type));
}

Peer::Peer(std::vector<std::string> args)
{
  // Check arguments
  xbt_assert(args.size() == 3 || args.size() == 4, "Wrong number of arguments");
  try {
    id       = std::stoi(args[1]);
    mailbox_ = sg4::Mailbox::by_name(std::to_string(id));
  } catch (const std::invalid_argument&) {
    throw std::invalid_argument("Invalid ID:" + args[1]);
  }
  random.set_seed(id);

  try {
    deadline = std::stod(args[2]);
  } catch (const std::invalid_argument&) {
    throw std::invalid_argument("Invalid deadline:" + args[2]);
  }
  xbt_assert(deadline > 0, "Wrong deadline supplied");

  if (args.size() == 4 && args[3] == "1") {
    bitfield_       = (1U << FILE_PIECES) - 1U;
    bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
  }
  pieces_count.resize(FILE_PIECES);

  XBT_INFO("Hi, I'm joining the network with id %d", id);
}

/** Peer main function */
void Peer::operator()()
{
  // Getting peer data from the tracker.
  if (getPeersFromTracker()) {
    XBT_DEBUG("Got %zu peers from the tracker. Current status is: %s", connected_peers.size(), getStatus().c_str());
    begin_receive_time = sg4::Engine::get_clock();
    mailbox_->set_receiver(sg4::Actor::self());
    if (hasFinished()) {
      sendHandshakeToAllPeers();
    } else {
      leech();
    }
    seed();
  } else {
    XBT_INFO("Couldn't contact the tracker.");
  }

  XBT_INFO("Here is my current status: %s", getStatus().c_str());
}

bool Peer::getPeersFromTracker()
{
  sg4::Mailbox* tracker_mailbox = sg4::Mailbox::by_name(TRACKER_MAILBOX);
  // Build the task to send to the tracker
  auto* peer_request = new TrackerQuery(id, mailbox_);
  try {
    XBT_DEBUG("Sending a peer request to the tracker.");
    tracker_mailbox->put(peer_request, TRACKER_COMM_SIZE, GET_PEERS_TIMEOUT);
  } catch (const simgrid::TimeoutException&) {
    XBT_DEBUG("Timeout expired when requesting peers to tracker");
    delete peer_request;
    return false;
  }

  try {
    auto answer = mailbox_->get_unique<TrackerAnswer>(GET_PEERS_TIMEOUT);
    // Add the peers the tracker gave us to our peer list.
    for (auto const& peer_id : answer->getPeers())
      if (id != peer_id)
        connected_peers.try_emplace(peer_id, peer_id);
  } catch (const simgrid::TimeoutException&) {
    XBT_DEBUG("Timeout expired when requesting peers to tracker");
    return false;
  }
  return true;
}

void Peer::sendHandshakeToAllPeers()
{
  for (auto const& [_, remote_peer] : connected_peers) {
    auto* handshake               = new Message(MessageType::HANDSHAKE, id, mailbox_);
    remote_peer.mailbox_->put_init(handshake, message_size(MessageType::HANDSHAKE))->detach();
    XBT_DEBUG("Sending a HANDSHAKE to %d", remote_peer.id);
  }
}

void Peer::sendMessage(sg4::Mailbox* mailbox, MessageType type, uint64_t size)
{
  XBT_DEBUG("Sending %s to %s", message_name(type), mailbox->get_cname());
  mailbox->put_init(new Message(type, id, bitfield_, mailbox_), size)->detach();
}

void Peer::sendBitfield(sg4::Mailbox* mailbox)
{
  XBT_DEBUG("Sending a BITFIELD to %s", mailbox->get_cname());
  mailbox
      ->put_init(new Message(MessageType::BITFIELD, id, bitfield_, mailbox_),
                 message_size(MessageType::BITFIELD) + BITS_TO_BYTES(FILE_PIECES))
      ->detach();
}

void Peer::sendPiece(sg4::Mailbox* mailbox, unsigned int piece, int block_index, int block_length)
{
  xbt_assert(not hasNotPiece(piece), "Tried to send a unavailable piece.");
  XBT_DEBUG("Sending the PIECE %u (%d,%d) to %s", piece, block_index, block_length, mailbox->get_cname());
  mailbox->put_init(new Message(MessageType::PIECE, id, mailbox_, piece, block_index, block_length), BLOCK_SIZE)
      ->detach();
}

void Peer::sendHaveToAllPeers(unsigned int piece)
{
  XBT_DEBUG("Sending HAVE message to all my peers");
  for (auto const& [_, remote_peer] : connected_peers) {
    remote_peer.mailbox_->put_init(new Message(MessageType::HAVE, id, mailbox_, piece), message_size(MessageType::HAVE))
        ->detach();
  }
}

void Peer::sendRequestTo(Connection* remote_peer, unsigned int piece)
{
  remote_peer->current_piece = piece;
  xbt_assert(remote_peer->hasPiece(piece));
  int block_index = getFirstMissingBlockFrom(piece);
  if (block_index != -1) {
    int block_length = static_cast<int>(std::min(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index));
    XBT_DEBUG("Sending a REQUEST to %s for piece %u (%d,%d)", remote_peer->mailbox_->get_cname(), piece, block_index,
              block_length);
    remote_peer->mailbox_
        ->put_init(new Message(MessageType::REQUEST, id, mailbox_, piece, block_index, block_length),
                   message_size(MessageType::REQUEST))
        ->detach();
  }
}

std::string Peer::getStatus() const
{
  std::string res;
  for (unsigned i = 0; i < FILE_PIECES; i++)
    res += (bitfield_ & (1U << i)) ? '1' : '0';
  return res;
}

bool Peer::hasFinished() const
{
  return bitfield_ == (1U << FILE_PIECES) - 1U;
}

/** Indicates if the remote peer has a piece not stored by the local peer */
bool Peer::isInterestedBy(const Connection* remote_peer) const
{
  return remote_peer->bitfield & (bitfield_ ^ ((1 << FILE_PIECES) - 1));
}

bool Peer::isInterestedByFree(const Connection* remote_peer) const
{
  for (unsigned int i = 0; i < FILE_PIECES; i++)
    if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
      return true;
  return false;
}

void Peer::updatePiecesCountFromBitfield(unsigned int bitfield)
{
  for (unsigned int i = 0; i < FILE_PIECES; i++)
    if (bitfield & (1U << i))
      pieces_count[i]++;
}

unsigned int Peer::countPieces(unsigned int bitfield) const
{
  unsigned int count = 0U;
  unsigned int n     = bitfield;
  while (n) {
    count += n & 1U;
    n >>= 1U;
  }
  return count;
}

int Peer::nbInterestedPeers() const
{
  return static_cast<int>(std::count_if(connected_peers.begin(), connected_peers.end(),
                                        [](const auto& kv) { return kv.second.interested; }));
}

void Peer::leech()
{
  double next_choked_update = sg4::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
  XBT_DEBUG("Start downloading.");

  /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
  sendHandshakeToAllPeers();
  XBT_DEBUG("Starting main leech loop listening on mailbox: %s", mailbox_->get_cname());

  while (sg4::Engine::get_clock() < deadline && countPieces(bitfield_) < FILE_PIECES) {
    if (comm_received == nullptr) {
      comm_received = mailbox_->get_async<Message>(&message);
    }
    if (comm_received->test()) {
      handleMessage();
      delete message;
      comm_received = nullptr;
    } else {
      // We don't execute the choke algorithm if we don't already have a piece
      if (sg4::Engine::get_clock() >= next_choked_update && countPieces(bitfield_) > 0) {
        updateChokedPeers();
        next_choked_update += UPDATE_CHOKED_INTERVAL;
      } else {
        sg4::this_actor::sleep_for(SLEEP_DURATION);
      }
    }
  }
  if (hasFinished())
    XBT_DEBUG("%d becomes a seeder", id);
}

void Peer::seed()
{
  double next_choked_update = sg4::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
  XBT_DEBUG("Start seeding.");
  // start the main seed loop
  while (sg4::Engine::get_clock() < deadline) {
    if (comm_received == nullptr) {
      comm_received = mailbox_->get_async<Message>(&message);
    }
    if (comm_received->test()) {
      handleMessage();
      delete message;
      comm_received = nullptr;
    } else {
      if (sg4::Engine::get_clock() >= next_choked_update) {
        updateChokedPeers();
        // TODO: Change the choked peer algorithm when seeding.
        next_choked_update += UPDATE_CHOKED_INTERVAL;
      } else {
        sg4::this_actor::sleep_for(SLEEP_DURATION);
      }
    }
  }
}

void Peer::updateActivePeersSet(Connection* remote_peer)
{
  if (remote_peer->interested && not remote_peer->choked_upload)
    active_peers.insert(remote_peer);
  else
    active_peers.erase(remote_peer);
}

void Peer::handleMessage()
{
  XBT_DEBUG("Received a %s message from %s", message_name(message->type), message->return_mailbox->get_cname());

  auto known_peer         = connected_peers.find(message->peer_id);
  Connection* remote_peer = (known_peer == connected_peers.end()) ? nullptr : &known_peer->second;
  xbt_assert(remote_peer != nullptr || message->type == MessageType::HANDSHAKE,
             "The impossible did happened: A not-in-our-list peer sent us a message.");

  switch (message->type) {
    case MessageType::HANDSHAKE:
      // Check if the peer is in our connection list.
      if (remote_peer == nullptr) {
        XBT_DEBUG("This peer %d was unknown, answer to its handshake", message->peer_id);
        connected_peers.try_emplace(message->peer_id, message->peer_id);
        sendMessage(message->return_mailbox, MessageType::HANDSHAKE, message_size(MessageType::HANDSHAKE));
      }
      // Send our bitfield to the peer
      sendBitfield(message->return_mailbox);
      break;
    case MessageType::BITFIELD:
      // Update the pieces list
      updatePiecesCountFromBitfield(message->bitfield);
      // Store the bitfield
      remote_peer->bitfield = message->bitfield;
      xbt_assert(not remote_peer->am_interested, "Should not be interested at first");
      if (isInterestedBy(remote_peer)) {
        remote_peer->am_interested = true;
        sendMessage(message->return_mailbox, MessageType::INTERESTED, message_size(MessageType::INTERESTED));
      }
      break;
    case MessageType::INTERESTED:
      // Update the interested state of the peer.
      remote_peer->interested = true;
      updateActivePeersSet(remote_peer);
      break;
    case MessageType::NOTINTERESTED:
      remote_peer->interested = false;
      updateActivePeersSet(remote_peer);
      break;
    case MessageType::UNCHOKE:
      xbt_assert(remote_peer->choked_download);
      remote_peer->choked_download = false;
      // Send requests to the peer, since it has unchoked us
      if (remote_peer->am_interested)
        requestNewPieceTo(remote_peer);
      break;
    case MessageType::CHOKE:
      xbt_assert(not remote_peer->choked_download);
      remote_peer->choked_download = true;
      if (remote_peer->current_piece != -1)
        removeCurrentPiece(remote_peer, remote_peer->current_piece);
      break;
    case MessageType::HAVE:
      XBT_DEBUG("\t for piece %d", message->piece);
      xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
                 "Wrong HAVE message received");
      remote_peer->bitfield = remote_peer->bitfield | (1U << static_cast<unsigned int>(message->piece));
      pieces_count[message->piece]++;
      // If the piece is in our pieces, we tell the peer that we are interested.
      if (not remote_peer->am_interested && hasNotPiece(message->piece)) {
        remote_peer->am_interested = true;
        sendMessage(message->return_mailbox, MessageType::INTERESTED, message_size(MessageType::INTERESTED));
        if (not remote_peer->choked_download)
          requestNewPieceTo(remote_peer);
      }
      break;
    case MessageType::REQUEST:
      xbt_assert(remote_peer->interested);
      xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
                 "Wrong HAVE message received");
      if (not remote_peer->choked_upload) {
        XBT_DEBUG("\t for piece %d (%d,%d)", message->piece, message->block_index,
                  message->block_index + message->block_length);
        if (not hasNotPiece(message->piece)) {
          sendPiece(message->return_mailbox, message->piece, message->block_index, message->block_length);
        }
      } else {
        XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
      }
      break;
    case MessageType::PIECE:
      XBT_DEBUG(" \t for piece %d (%d,%d)", message->piece, message->block_index,
                message->block_index + message->block_length);
      xbt_assert(not remote_peer->choked_download);
      xbt_assert(not remote_peer->choked_download, "Can't received a piece if I'm choked !");
      xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
                 "Wrong piece received");
      // TODO: Execute a computation.
      if (hasNotPiece(static_cast<unsigned int>(message->piece))) {
        updateBitfieldBlocks(message->piece, message->block_index, message->block_length);
        if (hasCompletedPiece(static_cast<unsigned int>(message->piece))) {
          // Removing the piece from our piece list
          removeCurrentPiece(remote_peer, message->piece);
          // Setting the fact that we have the piece
          bitfield_ = bitfield_ | (1U << static_cast<unsigned int>(message->piece));
          XBT_DEBUG("My status is now %s", getStatus().c_str());
          // Sending the information to all the peers we are connected to
          sendHaveToAllPeers(message->piece);
          // sending UNINTERESTED to peers that do not have what we want.
          updateInterestedAfterReceive();
        } else {                                      // piece not completed
          sendRequestTo(remote_peer, message->piece); // ask for the next block
        }
      } else {
        XBT_DEBUG("However, we already have it");
        requestNewPieceTo(remote_peer);
      }
      break;
    case MessageType::CANCEL:
      break;
    default:
      THROW_IMPOSSIBLE;
  }
  // Update the peer speed.
  if (remote_peer) {
    remote_peer->addSpeedValue(1.0 / (sg4::Engine::get_clock() - begin_receive_time));
  }
  begin_receive_time = sg4::Engine::get_clock();
}

/** Selects the appropriate piece to download and requests it to the remote_peer */
void Peer::requestNewPieceTo(Connection* remote_peer)
{
  int piece = selectPieceToDownload(remote_peer);
  if (piece != -1) {
    current_pieces |= (1U << (unsigned int)piece);
    sendRequestTo(remote_peer, piece);
  }
}

void Peer::removeCurrentPiece(Connection* remote_peer, unsigned int current_piece)
{
  current_pieces &= ~(1U << current_piece);
  remote_peer->current_piece = -1;
}

/** @brief Return the piece to be downloaded
 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
 * If a piece is partially downloaded, this piece will be selected prioritarily
 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
 * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
 * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
 * @param remote_peer: information about the connection
 * @return the piece to download if possible. -1 otherwise
 */
int Peer::selectPieceToDownload(const Connection* remote_peer)
{
  int piece = partiallyDownloadedPiece(remote_peer);
  // strict priority policy
  if (piece != -1)
    return piece;

  // end game mode
  if (countPieces(current_pieces) >= (FILE_PIECES - countPieces(bitfield_)) && isInterestedBy(remote_peer)) {
    int nb_interesting_pieces = 0;
    // compute the number of interesting pieces
    for (unsigned int i = 0; i < FILE_PIECES; i++)
      if (remotePeerHasMissingPiece(remote_peer, i))
        nb_interesting_pieces++;

    xbt_assert(nb_interesting_pieces != 0);
    // get a random interesting piece
    int random_piece_index = random.uniform_int(0, nb_interesting_pieces - 1);
    int current_index      = 0;
    for (unsigned int i = 0; i < FILE_PIECES; i++) {
      if (remotePeerHasMissingPiece(remote_peer, i)) {
        if (random_piece_index == current_index) {
          piece = i;
          break;
        }
        current_index++;
      }
    }
    xbt_assert(piece != -1);
    return piece;
  }
  // Random first policy
  if (countPieces(bitfield_) < 4 && isInterestedByFree(remote_peer)) {
    int nb_interesting_pieces = 0;
    // compute the number of interesting pieces
    for (unsigned int i = 0; i < FILE_PIECES; i++)
      if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
        nb_interesting_pieces++;
    xbt_assert(nb_interesting_pieces != 0);
    // get a random interesting piece
    int random_piece_index = random.uniform_int(0, nb_interesting_pieces - 1);
    int current_index      = 0;
    for (unsigned int i = 0; i < FILE_PIECES; i++) {
      if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i)) {
        if (random_piece_index == current_index) {
          piece = i;
          break;
        }
        current_index++;
      }
    }
    xbt_assert(piece != -1);
    return piece;
  } else { // Rarest first policy
    short min         = SHRT_MAX;
    int nb_min_pieces = 0;
    int current_index = 0;
    // compute the smallest number of copies of available pieces
    for (unsigned int i = 0; i < FILE_PIECES; i++) {
      if (pieces_count[i] < min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
        min = pieces_count[i];
    }

    xbt_assert(min != SHRT_MAX || not isInterestedByFree(remote_peer));
    // compute the number of rarest pieces
    for (unsigned int i = 0; i < FILE_PIECES; i++)
      if (pieces_count[i] == min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i))
        nb_min_pieces++;

    xbt_assert(nb_min_pieces != 0 || not isInterestedByFree(remote_peer));
    // get a random rarest piece
    int random_rarest_index = 0;
    if (nb_min_pieces > 0) {
      random_rarest_index = random.uniform_int(0, nb_min_pieces - 1);
    }
    for (unsigned int i = 0; i < FILE_PIECES; i++)
      if (pieces_count[i] == min && remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i)) {
        if (random_rarest_index == current_index) {
          piece = i;
          break;
        }
        current_index++;
      }

    xbt_assert(piece != -1 || not isInterestedByFree(remote_peer));
    return piece;
  }
}

void Peer::updateChokedPeers()
{
  if (nbInterestedPeers() == 0)
    return;
  XBT_DEBUG("(%d) update_choked peers %zu active peers", id, active_peers.size());
  // update the current round
  round_                  = (round_ + 1) % 3;
  Connection* chosen_peer = nullptr;
  // select first active peer and remove it from the set
  Connection* choked_peer;
  if (active_peers.empty()) {
    choked_peer = nullptr;
  } else {
    choked_peer = *active_peers.begin();
    active_peers.erase(choked_peer);
  }

  /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
  if (hasFinished()) {
    double unchoke_time = sg4::Engine::get_clock() + 1;
    for (auto& [_, remote_peer] : connected_peers) {
      if (remote_peer.last_unchoke < unchoke_time && remote_peer.interested && remote_peer.choked_upload) {
        unchoke_time = remote_peer.last_unchoke;
        chosen_peer  = &remote_peer;
      }
    }
  } else {
    // Random optimistic unchoking
    if (round_ == 0) {
      int j = 0;
      do {
        // We choose a random peer to unchoke.
        auto chosen_peer_it = connected_peers.begin();
        std::advance(chosen_peer_it, random.uniform_int(0, static_cast<int>(connected_peers.size() - 1)));
        chosen_peer = &chosen_peer_it->second;
        if (not chosen_peer->interested || not chosen_peer->choked_upload)
          chosen_peer = nullptr;
        else
          XBT_DEBUG("Nothing to do, keep going");
        j++;
      } while (chosen_peer == nullptr && j < MAXIMUM_PEERS);
    } else {
      // Use the "fastest download" policy.
      double fastest_speed = 0.0;
      for (auto& [_, remote_peer] : connected_peers) {
        if (remote_peer.peer_speed > fastest_speed && remote_peer.choked_upload && remote_peer.interested) {
          fastest_speed = remote_peer.peer_speed;
          chosen_peer   = &remote_peer;
        }
      }
    }
  }

  if (chosen_peer != nullptr)
    XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", id, chosen_peer->id,
              chosen_peer->interested, chosen_peer->choked_upload);

  if (choked_peer != chosen_peer) {
    if (choked_peer != nullptr) {
      xbt_assert(not choked_peer->choked_upload, "Tries to choked a choked peer");
      choked_peer->choked_upload = true;
      updateActivePeersSet(choked_peer);
      XBT_DEBUG("(%d) Sending a CHOKE to %d", id, choked_peer->id);
      sendMessage(choked_peer->mailbox_, MessageType::CHOKE, message_size(MessageType::CHOKE));
    }
    if (chosen_peer != nullptr) {
      xbt_assert((chosen_peer->choked_upload), "Tries to unchoked an unchoked peer");
      chosen_peer->choked_upload = false;
      active_peers.insert(chosen_peer);
      chosen_peer->last_unchoke = sg4::Engine::get_clock();
      XBT_DEBUG("(%d) Sending a UNCHOKE to %d", id, chosen_peer->id);
      updateActivePeersSet(chosen_peer);
      sendMessage(chosen_peer->mailbox_, MessageType::UNCHOKE, message_size(MessageType::UNCHOKE));
    }
  }
}

/** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.*/
void Peer::updateInterestedAfterReceive()
{
  for (auto& [_, remote_peer] : connected_peers) {
    if (remote_peer.am_interested) {
      bool interested = false;
      // Check if the peer still has a piece we want.
      for (unsigned int i = 0; i < FILE_PIECES; i++)
        if (remotePeerHasMissingPiece(&remote_peer, i)) {
          interested = true;
          break;
        }

      if (not interested) { // no more piece to download from connection
        remote_peer.am_interested = false;
        sendMessage(remote_peer.mailbox_, MessageType::NOTINTERESTED, message_size(MessageType::NOTINTERESTED));
      }
    }
  }
}

void Peer::updateBitfieldBlocks(int piece, int block_index, int block_length)
{
  xbt_assert((piece >= 0 && static_cast<unsigned int>(piece) <= FILE_PIECES), "Wrong piece.");
  xbt_assert((block_index >= 0 && static_cast<unsigned int>(block_index) <= PIECES_BLOCKS), "Wrong block : %d.",
             block_index);
  for (int i = block_index; i < (block_index + block_length); i++)
    bitfield_blocks |= (1ULL << static_cast<unsigned int>(piece * PIECES_BLOCKS + i));
}

bool Peer::hasCompletedPiece(unsigned int piece) const
{
  for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
    if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
      return false;
  return true;
}

int Peer::getFirstMissingBlockFrom(int piece) const
{
  for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
    if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
      return i;
  return -1;
}

/** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
int Peer::partiallyDownloadedPiece(const Connection* remote_peer) const
{
  for (unsigned int i = 0; i < FILE_PIECES; i++)
    if (remotePeerHasMissingPiece(remote_peer, i) && isNotDownloadingPiece(i) && getFirstMissingBlockFrom(i) > 0)
      return i;
  return -1;
}