package peer import ( "encoding/binary" "io" ) type Message int const ( Choke Message = iota // choke: Unchoke // unchoke: Interested // interested: NotInterested // not interested: Have // have: BitField // bitfield: Request // request: Piece // piece: Cancel // cancel: Port // port: DHT _ // keep-alive: _ _ Suggset HaveAll HaveNone Reject AllowedFast _ _ LTEPHandshake ) const Proto = `BitTorrent protocol` type Handshake struct { Proto string Flags [8]byte InfoHash [20]byte PeerID [20]byte } func (h Handshake) Encode(w io.Writer) { l := int8(len(h.Proto)) binary.Write(w, binary.BigEndian, l) w.Write([]byte(h.Proto)) w.Write(h.Flags[:]) w.Write(h.InfoHash[:]) w.Write(h.PeerID[:]) } func DecodeHandshake(r io.Reader) (Handshake, bool) { var h Handshake var l int8 binary.Read(r, binary.BigEndian, &l) if int(l) != len(Proto) { return h, false } proto := make([]byte, int(l)) r.Read(proto) h.Proto = string(proto) if h.Proto != Proto { return h, false } r.Read(h.Flags[:]) r.Read(h.InfoHash[:]) r.Read(h.PeerID[:]) return h, true }