mirror of
https://github.com/veggiedefender/torrent-client.git
synced 2025-03-27 07:41:17 +02:00
Rewrite handshake Serialize
This commit is contained in:
parent
439a0e19a8
commit
a83013d250
@ -23,14 +23,13 @@ func New(infoHash, peerID [20]byte) *Handshake {
|
||||
|
||||
// Serialize serializes the handshake to a buffer
|
||||
func (h *Handshake) Serialize() []byte {
|
||||
pstrlen := len(h.Pstr)
|
||||
bufLen := 49 + pstrlen
|
||||
buf := make([]byte, bufLen)
|
||||
buf[0] = byte(pstrlen)
|
||||
copy(buf[1:], h.Pstr)
|
||||
// Leave 8 reserved bytes
|
||||
copy(buf[1+pstrlen+8:], h.InfoHash[:])
|
||||
copy(buf[1+pstrlen+8+20:], h.PeerID[:])
|
||||
buf := make([]byte, len(h.Pstr)+49)
|
||||
buf[0] = byte(len(h.Pstr))
|
||||
curr := 1
|
||||
curr += copy(buf[curr:], h.Pstr)
|
||||
curr += copy(buf[curr:], make([]byte, 8)) // 8 reserved bytes
|
||||
curr += copy(buf[curr:], h.InfoHash[:])
|
||||
curr += copy(buf[curr:], h.PeerID[:])
|
||||
return buf
|
||||
}
|
||||
|
||||
|
@ -32,6 +32,14 @@ func TestSerialize(t *testing.T) {
|
||||
},
|
||||
output: []byte{19, 66, 105, 116, 84, 111, 114, 114, 101, 110, 116, 32, 112, 114, 111, 116, 111, 99, 111, 108, 0, 0, 0, 0, 0, 0, 0, 0, 134, 212, 200, 0, 36, 164, 105, 190, 76, 80, 188, 90, 16, 44, 247, 23, 128, 49, 0, 116, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
|
||||
},
|
||||
"different pstr": {
|
||||
input: &Handshake{
|
||||
Pstr: "BitTorrent protocol, but cooler?",
|
||||
InfoHash: [20]byte{134, 212, 200, 0, 36, 164, 105, 190, 76, 80, 188, 90, 16, 44, 247, 23, 128, 49, 0, 116},
|
||||
PeerID: [20]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
|
||||
},
|
||||
output: []byte{32, 66, 105, 116, 84, 111, 114, 114, 101, 110, 116, 32, 112, 114, 111, 116, 111, 99, 111, 108, 44, 32, 98, 117, 116, 32, 99, 111, 111, 108, 101, 114, 63, 0, 0, 0, 0, 0, 0, 0, 0, 134, 212, 200, 0, 36, 164, 105, 190, 76, 80, 188, 90, 16, 44, 247, 23, 128, 49, 0, 116, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
|
Loading…
x
Reference in New Issue
Block a user