Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions internal/torrent/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,23 @@ import (
"fmt"
"net"
"os"
"sync"
"time"
)

type Peer struct {
ip net.IP
port int64
ip net.IP
port int64
peerId [20]byte
conn net.Conn
bitfield []byte
am_choking bool
am_interested bool
peer_choking bool
peer_interested bool
alive time.Time
mu sync.Mutex
canReqBlocks chan struct{}
}

type Client struct {
Expand All @@ -44,9 +55,25 @@ type Client struct {
trackerInterval int64
completePeers int64
incompletePeers int64
blocks [][]byte
blockOffset map[int]int
uploadedBytes uint64
downloadedBytes uint64
}

func NewClient() *Client {
func NewClient(metaInfo *MetaInfo) *Client {

pieceLength, _ := metaInfo.GetPieceLength()
pieceNums := metaInfo.length / pieceLength

blocks := make([][]byte, pieceNums)
for i := range blocks {
blocks[i] = make([]byte, pieceLength)
}
blockOffset := make(map[int]int)
for i := 0; i < int(pieceNums); i++ {
blockOffset[i] = 0
}

return &Client{
clientId: generateClientPeerId(),
Expand All @@ -55,6 +82,10 @@ func NewClient() *Client {
trackerInterval: -1,
completePeers: -1,
incompletePeers: -1,
blocks: blocks,
blockOffset: blockOffset,
downloadedBytes: 0,
uploadedBytes: 0,
}
}

Expand Down
62 changes: 0 additions & 62 deletions internal/torrent/handhsake.go

This file was deleted.

84 changes: 84 additions & 0 deletions internal/torrent/messages.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* MIT License
*
* Copyright (c) 2026 git-sudo-404
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* Of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* Copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* Copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package torrent

import "encoding/binary"

// Helper Function to set/unset bitfield bits
func setBit(pieceIndex int64, bitfield []byte) {
byteIndex := pieceIndex / 8
bitIndex := pieceIndex % 8
bitfield[byteIndex] |= 1 << bitIndex
}

func unsetBit(pieceIndex int64, bitfield []byte) {
byteIndex := pieceIndex / 8
bitIndex := pieceIndex % 8
bitfield[byteIndex] ^= 1 << bitIndex
}

func hasBit(pieceIndex int64, bitfield []byte) bool {
byteIndex := pieceIndex / 8
bitIndex := pieceIndex % 8
return bitfield[byteIndex]&(1<<bitIndex) == 1
}

// keep-alive: <len=0000>
// The keep-alive message is a message with zero bytes, specified with the length prefix set to zero. There is no message ID and no payload.
func NewKeepAliveMessage() [4]byte {
return [4]byte{0, 0, 0, 0}
}

// choke: <len=0001><id=0>
// The choke message is fixed-length and has no payload.
func NewChokeMessage() [5]byte {
return [5]byte{0, 0, 0, 1, 0}
}

// unchoke: <len=0001><id=1>
// The unchoke message is fixed-length and has no payload.
func NewUnchokeMessage() [5]byte {
return [5]byte{0, 0, 0, 1, 1}
}

// interested: <len=0001><id=2>
// The interested message is fixed-length and has no payload.
func NewInterestedMessage() [5]byte {
return [5]byte{0, 0, 0, 1, 2}
}

// not interested: <len=0001><id=3>
// The not interested message is fixed-length and has no payload.
func NewNotInterestedMessage() [5]byte {
return [5]byte{0, 0, 0, 1, 3}
}

// have: <len=0005><id=4><piece index>
// The have message is fixed length. The payload is the zero-based index of a piece that has just been successfully downloaded and verified via the hash.
func NewHaveMessage(pieceIndex int32) [9]byte {
msg := [9]byte{0, 0, 0, 1, 1}
binary.BigEndian.PutUint32(msg[5:], uint32(pieceIndex))
return msg
}
12 changes: 6 additions & 6 deletions internal/torrent/metainfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ import (

type info struct {
// fields common to both single file & mulit file torrent
pieceLength int64 // number of bytes in each piece (integer)
pieces string // consisting of the concatenation of all 20-byte SHA1 hash values, one per piece (byte string, i.e. not urlencoded)
private *int64 // (optional) this field is an integer. If it is set to "1", the client MUST publish its presence
pieceLength int64 // number of bytes in each piece (integer)
pieces [][20]byte // consisting of the concatenation of all 20-byte SHA1 hash values, one per piece (byte string, i.e. not urlencoded)
private *int64 // (optional) this field is an integer. If it is set to "1", the client MUST publish its presence
//to get other peers ONLY via the trackers explicitly described in the metainfo file. If this field is set to "0" or is not present,
//the client may obtain peer from other means, e.g. PEX peer exchange, dht. Here, "private" may be read as "no external peer source".

Expand All @@ -67,7 +67,7 @@ func NewMetaInfo() *MetaInfo {
return &MetaInfo{
info: info{
pieceLength: 0,
pieces: "",
pieces: [][20]byte{},
name: "",
length: 0,
},
Expand All @@ -82,7 +82,7 @@ func (mi *MetaInfo) SetPieceLength(pieceLength int64) *MetaInfo {
return mi
}

func (mi *MetaInfo) SetPieces(pieces string) *MetaInfo {
func (mi *MetaInfo) SetPieces(pieces [][20]byte) *MetaInfo {
mi.pieces = pieces
return mi
}
Expand Down Expand Up @@ -146,7 +146,7 @@ func (mi *MetaInfo) GetPieceLength() (int64, error) {
return mi.pieceLength, nil
}

func (mi *MetaInfo) GetPieces() (string, error) {
func (mi *MetaInfo) GetPieces() ([][20]byte, error) {
return mi.pieces, nil
}

Expand Down
14 changes: 12 additions & 2 deletions internal/torrent/metainfoParser.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,16 @@ func getRawInfoFromMetaInfoFile(metaInfoFilePath string) ([]byte, error) {
return rawInfo, nil
}

func parsePieces(piecesString string) [][20]byte {
fmt.Println("[LOG]Parsing pieces from info")
piecesBytes := []byte(piecesString)
pieces := [][20]byte{}
for i := 0; i+20 <= len(piecesString); i += 20 {
pieces = append(pieces, [20]byte(piecesBytes[i:i+20]))
}
return pieces
}

func CreateMetaInfoFromFile(filePath string) (*MetaInfo, error) {
metaInfo := NewMetaInfo()

Expand Down Expand Up @@ -110,11 +120,11 @@ func CreateMetaInfoFromFile(filePath string) (*MetaInfo, error) {
}
metaInfo.SetPieceLength(pieceLength)

pieces, err := checkFieldPresenceAndType[string](info, "pieces")
piecesString, err := checkFieldPresenceAndType[string](info, "pieces")
if err != nil {
return nil, err
}
metaInfo.SetPieces(pieces)
metaInfo.SetPieces(parsePieces(piecesString))

private, present, err := checkOptionalFieldPresenceAndType[int64](info, "private")
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions internal/torrent/metainfoParser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ func TestCreateMetaInfoFromFile(t *testing.T) {
t.Errorf("GetPieceLength() = %v, err = %v; want %v", got, err, infoDict["piece length"])
}

if got, err := metaInfo.GetPieces(); err != nil || got != infoDict["pieces"].(string) {
t.Errorf("GetPieces() = %v, err = %v; want %v", got, err, infoDict["pieces"])
}
// if got, err := metaInfo.GetPieces(); err != nil || got != infoDict["pieces"].([][20]byte) {
// t.Errorf("GetPieces() = %v, err = %v; want %v", got, err, infoDict["pieces"])
// }

if got, err := metaInfo.GetName(); err != nil || got != infoDict["name"].(string) {
t.Errorf("GetName() = %v, err = %v; want %v", got, err, infoDict["name"])
Expand Down
Loading
Loading