I’m stuck on Stage #ND2 C++
I have tested everything but I keep getting wrong hashes, and my first PIECE
ID is indeed 7 but the rest is -32 and the returned index
, begin
are gibberish from the first response
Anyone can help?
Here are my logs:
Here’s my code
void TorrentClient::downloadPiece(const std::string &path, size_t pieceIndex) const
{
std::ofstream out(path, std::ios_base::out);
if (!out) {
std::stringstream error;
error << "Error creating file: " << path << std::endl;
exit_with_message(error);
}
auto message = m_client->recv();
if (!message.isType(PeerMessagesType::BITFIELD))
exit_with_message(make_message(message));
m_client->send(PeerMessage(PeerMessagesType::INTERESTED));
message = m_client->recv();
if (!message.isType(PeerMessagesType::UNCHOKE))
exit_with_message(make_message(message));
size_t size = m_torrent.piece_length;
size_t blockIndex = 0;
while (size > 0) {
size_t blockSize = size > BLOCK_SIZE ? BLOCK_SIZE : size;
std::stringstream ss;
ss << bitos(pieceIndex)
<< bitos(BLOCK_SIZE * (blockIndex++))
<< bitos(blockSize);
m_client->send(PeerMessage(PeerMessagesType::REQUEST, ss.str()));
message = m_client->recv();
// if (!message.isType(PeerMessagesType::PIECE))
// exit_with_message(make_message(message));
auto payload = std::string_view(message.getPayload());
[[maybe_unused]]
auto index = bstoi(std::string(payload.substr(0, sizeof(int))));
payload.remove_prefix(sizeof(int));
[[maybe_unused]]
auto begin = bstoi(std::string(payload.substr(0, sizeof(int))));
payload.remove_prefix(sizeof(int));
auto block = payload;
out << block;
size -= block.size();
}
}
NOTE: the receive and send method is tested out effectively where they ensure sending and receiving the whole message regardless of the size. also the maximum buffer size is 32 KB which is twice as big as block size