Reputation: 33
I am trying to work on a bittorrent client and I got so far into requesting for pieces.
My request message looks like that:
total_length = 1 + 4 + 4 + 4
return struct.pack('> i b i i i', total_length, msg_types.request, piece_index,begin,
block_length)
Let's say I send a request message with the following parameters:
piece_index = 0
begin = 0
block_length = 0x1000
When recieveing a response I read it in the next way:
read 4 first bytes of every message (thats the length of the message)
read a message in the length provided earlier
(lets assume that this is a "piece" msg) I parse it in the next way:
msg_type, piece_index, block_offset = struct.unpack('! b i i', payload[:9])
block = payload[9:]
build_block_into_piece_and_update(block, block_offset, msg_len)
request_next_block()
and then this is how my build_block_into_piece_and_update
looks like:
def build_piece_into_file_and_update(data, offset, msg_length):
block_length = msg_length - 9
for i in range(len(data)):
current_piece_data[i + offset] = data[i]
self.block_offset += block_length
if self.block_offset + 1 >= self.piece_size:
self.current_piece_index += 1
self.block_offset = 0
print("moving into next piece")
This is where I get confused: Usually the block_length and the len(data) is the same, however: when there are variances (usually the length of data is shorter, block_length always keeps being 0x1000), what should I do? should I just assume the "missing bytes" have the value 0f 0 and then write it into current_piece_data?
When gathering all blocks in a piece I try to compare the SHA-1 value of it into the hash provided to me (in this example, the hash of piece number 0) and I never get the same hash.
Thanks for every response!
Upvotes: 0
Views: 195
Reputation: 43125
Check if you're decoding things correctly by comparing with wireshark.
Then, as BEP3 says:
'request' messages contain an index, begin, and length. The last two are byte offsets. Length is generally a power of two unless it gets truncated by the end of the file.
So check if you're requesting bytes beyond the end of the torrent. Peers really shouldn't be responding to an invalid request, but maybe some implementations incorrectly do anyway.
And you should treat peers as potentially untrusted or buggy. They can send random garbage and try to corrupt your data. So you should only accept exactly what you requested.
Upvotes: 0