1 /* Copyright (c) 2012-2019. The SimGrid Team. All rights reserved. */
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. */
9 #include "s4u-peer.hpp"
10 #include "s4u-tracker.hpp"
12 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_bt_peer, "Messages specific for the peers");
15 * User parameters for transferred file data. For the test, the default values are :
16 * File size: 10 pieces * 5 blocks/piece * 16384 bytes/block = 819200 bytes
18 constexpr unsigned long FILE_PIECES = 10UL;
19 constexpr unsigned long PIECES_BLOCKS = 5UL;
20 constexpr int BLOCK_SIZE = 16384;
22 /** Number of blocks asked by each request */
23 constexpr unsigned long BLOCKS_REQUESTED = 2UL;
25 constexpr bool ENABLE_END_GAME_MODE = true;
26 constexpr double SLEEP_DURATION = 1.0;
27 #define BITS_TO_BYTES(x) (((x) / 8 + (x) % 8) ? 1 : 0)
29 Peer::Peer(std::vector<std::string> args)
32 xbt_assert(args.size() == 3 || args.size() == 4, "Wrong number of arguments");
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]);
41 deadline = std::stod(args[2]);
42 } catch (const std::invalid_argument&) {
43 throw std::invalid_argument("Invalid deadline:" + args[2]);
45 xbt_assert(deadline > 0, "Wrong deadline supplied");
47 if (args.size() == 4 && args[3] == "1") {
48 bitfield_ = (1U << FILE_PIECES) - 1U;
49 bitfield_blocks = (1ULL << (FILE_PIECES * PIECES_BLOCKS)) - 1ULL;
51 pieces_count.resize(FILE_PIECES);
53 XBT_INFO("Hi, I'm joining the network with id %d", id);
56 /** Peer main function */
57 void Peer::operator()()
59 // Getting peer data from the tracker.
60 if (getPeersFromTracker()) {
61 XBT_DEBUG("Got %zu peers from the tracker. Current status is: %s", connected_peers.size(), getStatus().c_str());
62 begin_receive_time = simgrid::s4u::Engine::get_clock();
63 mailbox_->set_receiver(simgrid::s4u::Actor::self());
65 sendHandshakeToAllPeers();
71 XBT_INFO("Couldn't contact the tracker.");
74 XBT_INFO("Here is my current status: %s", getStatus().c_str());
77 bool Peer::getPeersFromTracker()
79 simgrid::s4u::Mailbox* tracker_mailbox = simgrid::s4u::Mailbox::by_name(TRACKER_MAILBOX);
80 // Build the task to send to the tracker
81 TrackerQuery* peer_request = new TrackerQuery(id, mailbox_);
83 XBT_DEBUG("Sending a peer request to the tracker.");
84 tracker_mailbox->put(peer_request, TRACKER_COMM_SIZE, GET_PEERS_TIMEOUT);
85 } catch (const simgrid::TimeoutException&) {
86 XBT_DEBUG("Timeout expired when requesting peers to tracker");
92 TrackerAnswer* answer = static_cast<TrackerAnswer*>(mailbox_->get(GET_PEERS_TIMEOUT));
93 // Add the peers the tracker gave us to our peer list.
94 for (auto const& peer_id : answer->getPeers())
96 connected_peers.emplace(peer_id, Connection(peer_id));
98 } catch (const simgrid::TimeoutException&) {
99 XBT_DEBUG("Timeout expired when requesting peers to tracker");
105 void Peer::sendHandshakeToAllPeers()
107 for (auto const& kv : connected_peers) {
108 const Connection& remote_peer = kv.second;
109 Message* handshake = new Message(MESSAGE_HANDSHAKE, id, mailbox_);
110 remote_peer.mailbox_->put_init(handshake, MESSAGE_HANDSHAKE_SIZE)->detach();
111 XBT_DEBUG("Sending a HANDSHAKE to %d", remote_peer.id);
115 void Peer::sendMessage(simgrid::s4u::Mailbox* mailbox, e_message_type type, uint64_t size)
117 const char* type_names[6] = {"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED", "CANCEL"};
118 XBT_DEBUG("Sending %s to %s", type_names[type], mailbox->get_cname());
119 mailbox->put_init(new Message(type, id, bitfield_, mailbox_), size)->detach();
122 void Peer::sendBitfield(simgrid::s4u::Mailbox* mailbox)
124 XBT_DEBUG("Sending a BITFIELD to %s", mailbox->get_cname());
126 ->put_init(new Message(MESSAGE_BITFIELD, id, bitfield_, mailbox_),
127 MESSAGE_BITFIELD_SIZE + BITS_TO_BYTES(FILE_PIECES))
131 void Peer::sendPiece(simgrid::s4u::Mailbox* mailbox, unsigned int piece, int block_index, int block_length)
133 xbt_assert(not hasNotPiece(piece), "Tried to send a unavailable piece.");
134 XBT_DEBUG("Sending the PIECE %u (%d,%d) to %s", piece, block_index, block_length, mailbox->get_cname());
135 mailbox->put_init(new Message(MESSAGE_PIECE, id, mailbox_, piece, block_index, block_length), BLOCK_SIZE)->detach();
138 void Peer::sendHaveToAllPeers(unsigned int piece)
140 XBT_DEBUG("Sending HAVE message to all my peers");
141 for (auto const& kv : connected_peers) {
142 const Connection& remote_peer = kv.second;
143 remote_peer.mailbox_->put_init(new Message(MESSAGE_HAVE, id, mailbox_, piece), MESSAGE_HAVE_SIZE)->detach();
147 void Peer::sendRequestTo(Connection* remote_peer, unsigned int piece)
149 remote_peer->current_piece = piece;
150 xbt_assert(remote_peer->hasPiece(piece));
151 int block_index = getFirstMissingBlockFrom(piece);
152 if (block_index != -1) {
153 int block_length = std::min(BLOCKS_REQUESTED, PIECES_BLOCKS - block_index);
154 XBT_DEBUG("Sending a REQUEST to %s for piece %u (%d,%d)", remote_peer->mailbox_->get_cname(), piece, block_index,
156 remote_peer->mailbox_
157 ->put_init(new Message(MESSAGE_REQUEST, id, mailbox_, piece, block_index, block_length), MESSAGE_REQUEST_SIZE)
162 std::string Peer::getStatus()
164 std::string res = std::string("");
165 for (int i = FILE_PIECES - 1; i >= 0; i--)
166 res = std::string((bitfield_ & (1U << i)) ? "1" : "0") + res;
170 bool Peer::hasFinished()
172 return bitfield_ == (1U << FILE_PIECES) - 1U;
175 /** Indicates if the remote peer has a piece not stored by the local peer */
176 bool Peer::isInterestedBy(Connection* remote_peer)
178 return remote_peer->bitfield & (bitfield_ ^ ((1 << FILE_PIECES) - 1));
181 bool Peer::isInterestedByFree(Connection* remote_peer)
183 for (unsigned int i = 0; i < FILE_PIECES; i++)
184 if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
189 void Peer::updatePiecesCountFromBitfield(unsigned int bitfield)
191 for (unsigned int i = 0; i < FILE_PIECES; i++)
192 if (bitfield & (1U << i))
196 unsigned int Peer::countPieces(unsigned int bitfield)
198 unsigned int count = 0U;
199 unsigned int n = bitfield;
207 int Peer::nbInterestedPeers()
210 for (auto const& kv : connected_peers)
211 if (kv.second.interested)
218 double next_choked_update = simgrid::s4u::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
219 XBT_DEBUG("Start downloading.");
221 /* Send a "handshake" message to all the peers it got (since it couldn't have gotten more than 50 peers) */
222 sendHandshakeToAllPeers();
223 XBT_DEBUG("Starting main leech loop listening on mailbox: %s", mailbox_->get_cname());
225 void* data = nullptr;
226 while (simgrid::s4u::Engine::get_clock() < deadline && countPieces(bitfield_) < FILE_PIECES) {
227 if (comm_received == nullptr) {
228 comm_received = mailbox_->get_async(&data);
230 if (comm_received->test()) {
231 message = static_cast<Message*>(data);
234 comm_received = nullptr;
236 // We don't execute the choke algorithm if we don't already have a piece
237 if (simgrid::s4u::Engine::get_clock() >= next_choked_update && countPieces(bitfield_) > 0) {
239 next_choked_update += UPDATE_CHOKED_INTERVAL;
241 simgrid::s4u::this_actor::sleep_for(SLEEP_DURATION);
246 XBT_DEBUG("%d becomes a seeder", id);
251 double next_choked_update = simgrid::s4u::Engine::get_clock() + UPDATE_CHOKED_INTERVAL;
252 XBT_DEBUG("Start seeding.");
253 // start the main seed loop
254 void* data = nullptr;
255 while (simgrid::s4u::Engine::get_clock() < deadline) {
256 if (comm_received == nullptr) {
257 comm_received = mailbox_->get_async(&data);
259 if (comm_received->test()) {
260 message = static_cast<Message*>(data);
263 comm_received = nullptr;
265 if (simgrid::s4u::Engine::get_clock() >= next_choked_update) {
267 // TODO: Change the choked peer algorithm when seeding.
268 next_choked_update += UPDATE_CHOKED_INTERVAL;
270 simgrid::s4u::this_actor::sleep_for(SLEEP_DURATION);
276 void Peer::updateActivePeersSet(Connection* remote_peer)
278 if (remote_peer->interested && not remote_peer->choked_upload)
279 active_peers.insert(remote_peer);
281 active_peers.erase(remote_peer);
284 void Peer::handleMessage()
286 const char* type_names[10] = {"HANDSHAKE", "CHOKE", "UNCHOKE", "INTERESTED", "NOTINTERESTED",
287 "HAVE", "BITFIELD", "REQUEST", "PIECE", "CANCEL"};
289 XBT_DEBUG("Received a %s message from %s", type_names[message->type], message->return_mailbox->get_cname());
291 auto known_peer = connected_peers.find(message->peer_id);
292 Connection* remote_peer = (known_peer == connected_peers.end()) ? nullptr : &known_peer->second;
293 xbt_assert(remote_peer != nullptr || message->type == MESSAGE_HANDSHAKE,
294 "The impossible did happened: A not-in-our-list peer sent us a message.");
296 switch (message->type) {
297 case MESSAGE_HANDSHAKE:
298 // Check if the peer is in our connection list.
299 if (remote_peer == nullptr) {
300 XBT_DEBUG("This peer %d was unknown, answer to its handshake", message->peer_id);
301 connected_peers.emplace(message->peer_id, Connection(message->peer_id));
302 sendMessage(message->return_mailbox, MESSAGE_HANDSHAKE, MESSAGE_HANDSHAKE_SIZE);
304 // Send our bitfield to the peer
305 sendBitfield(message->return_mailbox);
307 case MESSAGE_BITFIELD:
308 // Update the pieces list
309 updatePiecesCountFromBitfield(message->bitfield);
310 // Store the bitfield
311 remote_peer->bitfield = message->bitfield;
312 xbt_assert(not remote_peer->am_interested, "Should not be interested at first");
313 if (isInterestedBy(remote_peer)) {
314 remote_peer->am_interested = true;
315 sendMessage(message->return_mailbox, MESSAGE_INTERESTED, MESSAGE_INTERESTED_SIZE);
318 case MESSAGE_INTERESTED:
319 // Update the interested state of the peer.
320 remote_peer->interested = true;
321 updateActivePeersSet(remote_peer);
323 case MESSAGE_NOTINTERESTED:
324 remote_peer->interested = false;
325 updateActivePeersSet(remote_peer);
327 case MESSAGE_UNCHOKE:
328 xbt_assert(remote_peer->choked_download);
329 remote_peer->choked_download = false;
330 // Send requests to the peer, since it has unchoked us
331 if (remote_peer->am_interested)
332 requestNewPieceTo(remote_peer);
335 xbt_assert(not remote_peer->choked_download);
336 remote_peer->choked_download = true;
337 if (remote_peer->current_piece != -1)
338 removeCurrentPiece(remote_peer, remote_peer->current_piece);
341 XBT_DEBUG("\t for piece %d", message->piece);
342 xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
343 "Wrong HAVE message received");
344 remote_peer->bitfield = remote_peer->bitfield | (1U << static_cast<unsigned int>(message->piece));
345 pieces_count[message->piece]++;
346 // If the piece is in our pieces, we tell the peer that we are interested.
347 if (not remote_peer->am_interested && hasNotPiece(message->piece)) {
348 remote_peer->am_interested = true;
349 sendMessage(message->return_mailbox, MESSAGE_INTERESTED, MESSAGE_INTERESTED_SIZE);
350 if (not remote_peer->choked_download)
351 requestNewPieceTo(remote_peer);
354 case MESSAGE_REQUEST:
355 xbt_assert(remote_peer->interested);
356 xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
357 "Wrong HAVE message received");
358 if (not remote_peer->choked_upload) {
359 XBT_DEBUG("\t for piece %d (%d,%d)", message->piece, message->block_index,
360 message->block_index + message->block_length);
361 if (not hasNotPiece(message->piece)) {
362 sendPiece(message->return_mailbox, message->piece, message->block_index, message->block_length);
365 XBT_DEBUG("\t for piece %d but he is choked.", message->peer_id);
369 XBT_DEBUG(" \t for piece %d (%d,%d)", message->piece, message->block_index,
370 message->block_index + message->block_length);
371 xbt_assert(not remote_peer->choked_download);
372 xbt_assert(remote_peer->am_interested || ENABLE_END_GAME_MODE,
373 "Can't received a piece if I'm not interested without end-game mode!"
374 "piece (%d) bitfield (%u) remote bitfield (%u)",
375 message->piece, bitfield_, remote_peer->bitfield);
376 xbt_assert(not remote_peer->choked_download, "Can't received a piece if I'm choked !");
377 xbt_assert((message->piece >= 0 && static_cast<unsigned int>(message->piece) < FILE_PIECES),
378 "Wrong piece received");
379 // TODO: Execute a computation.
380 if (hasNotPiece(static_cast<unsigned int>(message->piece))) {
381 updateBitfieldBlocks(message->piece, message->block_index, message->block_length);
382 if (hasCompletedPiece(static_cast<unsigned int>(message->piece))) {
383 // Removing the piece from our piece list
384 removeCurrentPiece(remote_peer, message->piece);
385 // Setting the fact that we have the piece
386 bitfield_ = bitfield_ | (1U << static_cast<unsigned int>(message->piece));
387 XBT_DEBUG("My status is now %s", getStatus().c_str());
388 // Sending the information to all the peers we are connected to
389 sendHaveToAllPeers(message->piece);
390 // sending UNINTERESTED to peers that do not have what we want.
391 updateInterestedAfterReceive();
392 } else { // piece not completed
393 sendRequestTo(remote_peer, message->piece); // ask for the next block
396 XBT_DEBUG("However, we already have it");
397 xbt_assert(ENABLE_END_GAME_MODE, "Should not happen because we don't use end game mode !");
398 requestNewPieceTo(remote_peer);
406 // Update the peer speed.
408 remote_peer->addSpeedValue(1.0 / (simgrid::s4u::Engine::get_clock() - begin_receive_time));
410 begin_receive_time = simgrid::s4u::Engine::get_clock();
413 /** Selects the appropriate piece to download and requests it to the remote_peer */
414 void Peer::requestNewPieceTo(Connection* remote_peer)
416 int piece = selectPieceToDownload(remote_peer);
418 current_pieces |= (1U << (unsigned int)piece);
419 sendRequestTo(remote_peer, piece);
423 void Peer::removeCurrentPiece(Connection* remote_peer, unsigned int current_piece)
425 current_pieces &= ~(1U << current_piece);
426 remote_peer->current_piece = -1;
429 /** @brief Return the piece to be downloaded
430 * There are two cases (as described in "Bittorrent Architecture Protocol", Ryan Toole :
431 * If a piece is partially downloaded, this piece will be selected prioritarily
432 * If the peer has strictly less than 4 pieces, he chooses a piece at random.
433 * If the peer has more than pieces, he downloads the pieces that are the less replicated (rarest policy).
434 * If all pieces have been downloaded or requested, we select a random requested piece (endgame mode).
435 * @param remote_peer: information about the connection
436 * @return the piece to download if possible. -1 otherwise
438 int Peer::selectPieceToDownload(Connection* remote_peer)
440 int piece = partiallyDownloadedPiece(remote_peer);
441 // strict priority policy
446 if (countPieces(current_pieces) >= (FILE_PIECES - countPieces(bitfield_)) && isInterestedBy(remote_peer)) {
447 if (not ENABLE_END_GAME_MODE)
449 int nb_interesting_pieces = 0;
450 // compute the number of interesting pieces
451 for (unsigned int i = 0; i < FILE_PIECES; i++)
452 if (hasNotPiece(i) && remote_peer->hasPiece(i))
453 nb_interesting_pieces++;
455 xbt_assert(nb_interesting_pieces != 0);
456 // get a random interesting piece
457 int random_piece_index = simgrid::xbt::random::uniform_int(0, nb_interesting_pieces - 1);
458 int current_index = 0;
459 for (unsigned int i = 0; i < FILE_PIECES; i++) {
460 if (hasNotPiece(i) && remote_peer->hasPiece(i)) {
461 if (random_piece_index == current_index) {
468 xbt_assert(piece != -1);
471 // Random first policy
472 if (countPieces(bitfield_) < 4 && isInterestedByFree(remote_peer)) {
473 int nb_interesting_pieces = 0;
474 // compute the number of interesting pieces
475 for (unsigned int i = 0; i < FILE_PIECES; i++)
476 if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
477 nb_interesting_pieces++;
478 xbt_assert(nb_interesting_pieces != 0);
479 // get a random interesting piece
480 int random_piece_index = simgrid::xbt::random::uniform_int(0, nb_interesting_pieces - 1);
481 int current_index = 0;
482 for (unsigned int i = 0; i < FILE_PIECES; i++) {
483 if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i)) {
484 if (random_piece_index == current_index) {
491 xbt_assert(piece != -1);
493 } else { // Rarest first policy
494 short min = SHRT_MAX;
495 int nb_min_pieces = 0;
496 int current_index = 0;
497 // compute the smallest number of copies of available pieces
498 for (unsigned int i = 0; i < FILE_PIECES; i++) {
499 if (pieces_count[i] < min && hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
500 min = pieces_count[i];
503 xbt_assert(min != SHRT_MAX || not isInterestedByFree(remote_peer));
504 // compute the number of rarest pieces
505 for (unsigned int i = 0; i < FILE_PIECES; i++)
506 if (pieces_count[i] == min && hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i))
509 xbt_assert(nb_min_pieces != 0 || not isInterestedByFree(remote_peer));
510 // get a random rarest piece
511 int random_rarest_index = 0;
512 if (nb_min_pieces > 0) {
513 random_rarest_index = simgrid::xbt::random::uniform_int(0, nb_min_pieces - 1);
515 for (unsigned int i = 0; i < FILE_PIECES; i++)
516 if (pieces_count[i] == min && hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i)) {
517 if (random_rarest_index == current_index) {
524 xbt_assert(piece != -1 || not isInterestedByFree(remote_peer));
529 void Peer::updateChokedPeers()
531 if (nbInterestedPeers() == 0)
533 XBT_DEBUG("(%d) update_choked peers %zu active peers", id, active_peers.size());
534 // update the current round
535 round_ = (round_ + 1) % 3;
536 Connection* chosen_peer = nullptr;
537 // select first active peer and remove it from the set
538 Connection* choked_peer;
539 if (active_peers.empty()) {
540 choked_peer = nullptr;
542 choked_peer = *active_peers.begin();
543 active_peers.erase(choked_peer);
546 /**If we are currently seeding, we unchoke the peer which has been unchoked the last time.*/
548 double unchoke_time = simgrid::s4u::Engine::get_clock() + 1;
549 for (auto& kv : connected_peers) {
550 Connection& remote_peer = kv.second;
551 if (remote_peer.last_unchoke < unchoke_time && remote_peer.interested && remote_peer.choked_upload) {
552 unchoke_time = remote_peer.last_unchoke;
553 chosen_peer = &remote_peer;
557 // Random optimistic unchoking
561 // We choose a random peer to unchoke.
562 std::unordered_map<int, Connection>::iterator chosen_peer_it = connected_peers.begin();
563 std::advance(chosen_peer_it, simgrid::xbt::random::uniform_int(0, connected_peers.size() - 1));
564 chosen_peer = &chosen_peer_it->second;
565 if (not chosen_peer->interested || not chosen_peer->choked_upload)
566 chosen_peer = nullptr;
568 XBT_DEBUG("Nothing to do, keep going");
570 } while (chosen_peer == nullptr && j < MAXIMUM_PEERS);
572 // Use the "fastest download" policy.
573 double fastest_speed = 0.0;
574 for (auto& kv : connected_peers) {
575 Connection& remote_peer = kv.second;
576 if (remote_peer.peer_speed > fastest_speed && remote_peer.choked_upload && remote_peer.interested) {
577 fastest_speed = remote_peer.peer_speed;
578 chosen_peer = &remote_peer;
584 if (chosen_peer != nullptr)
585 XBT_DEBUG("(%d) update_choked peers unchoked (%d) ; int (%d) ; choked (%d) ", id, chosen_peer->id,
586 chosen_peer->interested, chosen_peer->choked_upload);
588 if (choked_peer != chosen_peer) {
589 if (choked_peer != nullptr) {
590 xbt_assert(not choked_peer->choked_upload, "Tries to choked a choked peer");
591 choked_peer->choked_upload = true;
592 updateActivePeersSet(choked_peer);
593 XBT_DEBUG("(%d) Sending a CHOKE to %d", id, choked_peer->id);
594 sendMessage(choked_peer->mailbox_, MESSAGE_CHOKE, MESSAGE_CHOKE_SIZE);
596 if (chosen_peer != nullptr) {
597 xbt_assert((chosen_peer->choked_upload), "Tries to unchoked an unchoked peer");
598 chosen_peer->choked_upload = false;
599 active_peers.insert(chosen_peer);
600 chosen_peer->last_unchoke = simgrid::s4u::Engine::get_clock();
601 XBT_DEBUG("(%d) Sending a UNCHOKE to %d", id, chosen_peer->id);
602 updateActivePeersSet(chosen_peer);
603 sendMessage(chosen_peer->mailbox_, MESSAGE_UNCHOKE, MESSAGE_UNCHOKE_SIZE);
608 /** @brief Update "interested" state of peers: send "not interested" to peers that don't have any more pieces we want.*/
609 void Peer::updateInterestedAfterReceive()
611 for (auto& kv : connected_peers) {
612 Connection& remote_peer = kv.second;
613 if (remote_peer.am_interested) {
614 bool interested = false;
615 // Check if the peer still has a piece we want.
616 for (unsigned int i = 0; i < FILE_PIECES; i++)
617 if (hasNotPiece(i) && remote_peer.hasPiece(i)) {
622 if (not interested) { // no more piece to download from connection
623 remote_peer.am_interested = false;
624 sendMessage(remote_peer.mailbox_, MESSAGE_NOTINTERESTED, MESSAGE_NOTINTERESTED_SIZE);
630 void Peer::updateBitfieldBlocks(int piece, int block_index, int block_length)
632 xbt_assert((piece >= 0 && static_cast<unsigned int>(piece) <= FILE_PIECES), "Wrong piece.");
633 xbt_assert((block_index >= 0 && static_cast<unsigned int>(block_index) <= PIECES_BLOCKS), "Wrong block : %d.",
635 for (int i = block_index; i < (block_index + block_length); i++)
636 bitfield_blocks |= (1ULL << static_cast<unsigned int>(piece * PIECES_BLOCKS + i));
639 bool Peer::hasCompletedPiece(unsigned int piece)
641 for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
642 if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
647 int Peer::getFirstMissingBlockFrom(int piece)
649 for (unsigned int i = 0; i < PIECES_BLOCKS; i++)
650 if (not(bitfield_blocks & 1ULL << (piece * PIECES_BLOCKS + i)))
655 /** Returns a piece that is partially downloaded and stored by the remote peer if any -1 otherwise. */
656 int Peer::partiallyDownloadedPiece(Connection* remote_peer)
658 for (unsigned int i = 0; i < FILE_PIECES; i++)
659 if (hasNotPiece(i) && remote_peer->hasPiece(i) && isNotDownloadingPiece(i) && getFirstMissingBlockFrom(i) > 0)