torrent

package module
v0.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2026 License: GPL-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package torrent provides functionality to create and verify torrent files.

Index

Constants

View Source
const (
	// HashSize defines the size of an SHA-1 hash in bytes, used for consistent hash representation throughout the system.
	HashSize = sha1.Size
)

Variables

View Source
var (
	// ErrPieceHashMismatch indicates a mismatch between the computed and expected hash of a piece during validation.
	ErrPieceHashMismatch = errors.New("piece hash mismatch")

	// ErrTaskStillRunning indicates that an attempted operation on a task failed because the task is still running.
	ErrTaskStillRunning = errors.New("task is still running")
)

Functions

func GetPieceLength

func GetPieceLength(totalLength int64) int64

GetPieceLength returns the fitting piece length for the given size.

func WriteFile

func WriteFile(filename string, tFile *File) error

Types

type File

type File struct {
	Info         Info       `bencode:"info"`
	Announce     string     `bencode:"announce"`
	AnnounceList [][]string `bencode:"announce-list,omitempty"`
	Comment      string     `bencode:"comment,omitempty"`
	UserID       string     `bencode:"uid,omitempty"`
	Section      string     `bencode:"section,omitempty"`
	CreationDate int64      `bencode:"creation date,omitempty,ignore_unmarshal_type_error"`
	CreatedBy    string     `bencode:"created by,omitempty"`
	Resume       Resume     `bencode:"libtorrent_resume,omitempty"`
	RTorrent     RTorrent   `bencode:"rtorrent,omitempty"`
	Encoding     string     `bencode:"encoding,omitempty"`
}

func ReadFile

func ReadFile(filename string) (*File, error)

func ReadFileFromBytes

func ReadFileFromBytes(data []byte) (*File, error)

type FileInfo

type FileInfo struct {
	Length int64    `bencode:"length"`
	Path   []string `bencode:"path"`
	// FullPath is the full path to the file on the filesystem.
	// Note: Value is only used internally for piece generation.
	FullPath string `bencode:"-"`
	// Offset represents the starting position of the file within the concatenated data of all files in a torrent.
	Offset int64 `bencode:"-"`
}

FileInfo represents a file inside a Torrent.

func (FileInfo) BuildFullPath

func (fi FileInfo) BuildFullPath(root ...string) string

BuildFullPath constructs the full file path by joining the provided root paths with the FileInfo's internal Path slice.

type Files

type Files []FileInfo

Files is a helper type to use methods on this type.

func FilesFromNode added in v0.1.0

func FilesFromNode(rootNode *dtree.Node) (Files, error)

FilesFromNode extracts file information from a release.Info object and constructs a Files slice. It returns an error if any issues occur while determining relative file paths.

func FilesFromPath

func FilesFromPath(root string) (Files, error)

FilesFromPath retrieves all files from the specified root directory recursively and returns them as a Files object. It skips directories and gets the relative path for each file, handling errors during the process. An error is returned if the root directory cannot be accessed or traversed.

func (Files) PieceCount

func (files Files) PieceCount(pieceLength int64) int

PieceCount calculates the number of pieces needed for all files inside Files.

func (Files) TotalLength

func (files Files) TotalLength() int64

TotalLength calculates the total size of all files inside Files.

type Info

type Info struct {
	Name        string `bencode:"name"`
	Private     *bool  `bencode:"private,omitempty"`
	PieceLength int64  `bencode:"piece length"`
	Pieces      []byte `bencode:"pieces"`
	Files       Files  `bencode:"files,omitempty"`  // Multi file
	Length      int64  `bencode:"length,omitempty"` // Single file
	Source      string `bencode:"source,omitempty"`
	Publisher   string `bencode:"publisher,omitempty"`
}

Info is the struct that holds the meta-info for a torrent file.

func (*Info) IsDir

func (info *Info) IsDir() bool

func (*Info) UpvertedFiles

func (info *Info) UpvertedFiles() []FileInfo

UpvertedFiles returns the files in the Info struct or a single file if no files are present.

type MetaInfo

type MetaInfo struct {
	InfoBytes    bencode.Bytes `bencode:"info,omitempty"`
	Announce     string        `bencode:"announce,omitempty"`
	CreationDate int64         `bencode:"creation date,omitempty,ignore_unmarshal_type_error"`
	Comment      string        `bencode:"comment,omitempty"`
	CreatedBy    string        `bencode:"created by,omitempty"`
}

func (MetaInfo) Write

func (mi MetaInfo) Write(w io.Writer) error

Write bencodes and writes to a writer

type ParallelFileRead

type ParallelFileRead int

ParallelFileRead is a type that defines if the files should be read in parallel.

const (
	// ParallelFileReadDisabled disables parallel file reading (better for hdds).
	ParallelFileReadDisabled ParallelFileRead = iota
	// ParallelFileReadEnabled enables parallel reading of files (improves performance on ssds).
	ParallelFileReadEnabled
	// ParallelFileReadAuto enables it if the system is linux and ssd is detected.
	ParallelFileReadAuto
)

type PiecesProcessingTask

type PiecesProcessingTask struct {
	// contains filtered or unexported fields
}

PiecesProcessingTask is used to track the progress of the piece generation process.

func GeneratePieces

func GeneratePieces(files Files, pieceLength int64, parallelRead ParallelFileRead, hashThreads int) (*PiecesProcessingTask, error)

GeneratePieces is a convenience wrapper for GeneratePiecesWithContext using context.Background(). See GeneratePiecesWithContext for detailed documentation and usage examples.

func GeneratePiecesWithContext

func GeneratePiecesWithContext(ctx context.Context, files Files, pieceLength int64, parallelRead ParallelFileRead, hashThreads int) (*PiecesProcessingTask, error)

GeneratePiecesWithContext starts asynchronous generation of SHA-1 hashes for torrent pieces.

This function starts the hash generation process IMMEDIATELY in the background and returns directly. The caller is responsible for monitoring the returned PiecesProcessingTask to determine when the generation is complete and to retrieve the generated hashes.

Parameters:

  • ctx: Context for cancellation and timeout control
  • files: Files to generate hashes from (Files slice)
  • pieceLength: Length of each piece in bytes
  • parallelRead: Configuration for parallel file reading
  • hashThreads: Number of hash workers (0 = automatic optimization)

Returns:

  • *PiecesProcessingTask: Task handle for progress tracking and hash retrieval
  • error: Error during initialization (not during processing)

IMPORTANT: The task is started IMMEDIATELY! The caller MUST:

  1. Check task.IsFinished() regularly, or
  2. Listen for context cancellation
  3. Use task.GetPieces() to retrieve generated hashes when IsFinished() returns true
  4. Check task.GetError() for any processing errors

Usage example:

task, err := GeneratePiecesWithContext(ctx, files, 32768, parallelRead, 0)
if err != nil {
    return nil, fmt.Errorf("failed to start hash generation: %w", err)
}

// Wait until task is finished
for !task.IsFinished() {
    fmt.Printf("Progress: %d%% (%s hashed)\n",
        task.GetProgress(),
        utils.Bytes(int(task.GetBytesHashed())))
    time.Sleep(100 * time.Millisecond)
}

// Retrieve generated hashes
hashes, err := task.GetPieces()
if err != nil {
    return nil, fmt.Errorf("hash generation failed: %w", err)
}

fmt.Printf("Generated %d piece hashes (%d bytes)\n",
    len(hashes)/HashSize, len(hashes))
return hashes, nil

Error handling:

  • Initialization errors are returned immediately
  • Processing errors are available via task.GetError()
  • ErrTaskStillRunning is returned by GetPieces() if called before completion
  • Context cancellation stops processing cleanly

func VerifyPieces

func VerifyPieces(files Files, pieceLength int64, expectedHashes []byte,
	parallelRead ParallelFileRead, hashThreads int) (*PiecesProcessingTask, error)

VerifyPieces is a convenience wrapper for VerifyPiecesWithContext using context.Background(). See VerifyPiecesWithContext for detailed documentation and usage examples.

func VerifyPiecesWithContext

func VerifyPiecesWithContext(ctx context.Context, files Files, pieceLength int64, expectedHashes []byte,
	parallelRead ParallelFileRead, hashThreads int) (*PiecesProcessingTask, error)

VerifyPiecesWithContext starts asynchronous verification of torrent piece hashes against expected hashes.

This function starts the verification process IMMEDIATELY in the background and returns directly. The caller is responsible for monitoring the returned PiecesProcessingTask to determine when the verification is complete.

Parameters:

  • ctx: Context for cancellation and timeout control
  • files: Files to be verified (Files slice)
  • pieceLength: Length of each piece in bytes
  • expectedHashes: Expected SHA-1 hashes (20 bytes per piece)
  • parallelRead: Configuration for parallel file reading
  • hashThreads: Number of hash workers (0 = automatic optimization)

Returns:

  • *PiecesProcessingTask: Task handle for progress tracking and result querying
  • error: Error during initialization (not during processing)

IMPORTANT: The task is started IMMEDIATELY! The caller MUST:

  1. Check task.IsFinished() regularly, or
  2. Listen for context cancellation
  3. Check task.GetError() when IsFinished() returns true

Usage example:

task, err := VerifyPiecesWithContext(ctx, files, 32768, expectedHashes, parallelRead, 0)
if err != nil {
    return fmt.Errorf("failed to start verification: %w", err)
}

// Wait until task is finished
for !task.IsFinished() {
    fmt.Printf("Progress: %d%%\n", task.GetProgress())
    time.Sleep(100 * time.Millisecond)
}

// Check result
if err := task.GetError(); err != nil {
    if errors.Is(err, ErrPieceHashMismatch) {
        return fmt.Errorf("hash verification failed: %w", err)
    }
    return fmt.Errorf("verification error: %w", err)
}

fmt.Println("All pieces verified successfully!")

Error handling:

  • Initialization errors are returned immediately
  • Processing errors are available via task.GetError()
  • ErrPieceHashMismatch is set on hash mismatches
  • Context cancellation stops processing cleanly

func (*PiecesProcessingTask) GetBytesHashed

func (t *PiecesProcessingTask) GetBytesHashed() int64

GetBytesHashed returns the number of bytes hashed so far.

func (*PiecesProcessingTask) GetError

func (t *PiecesProcessingTask) GetError() error

GetError retrieves the error associated with the task in a thread-safe manner.

func (*PiecesProcessingTask) GetNumWorkers added in v0.2.0

func (t *PiecesProcessingTask) GetNumWorkers() int

GetNumWorkers returns the number of total workers.

func (*PiecesProcessingTask) GetPieces

func (t *PiecesProcessingTask) GetPieces() ([]byte, error)

GetPieces returns the generated piece hashes and any error associated with the task, ensuring thread-safe access.

func (*PiecesProcessingTask) GetProgress

func (t *PiecesProcessingTask) GetProgress() int

GetProgress returns the progress of the piece generation process.

func (*PiecesProcessingTask) IsCanceled

func (t *PiecesProcessingTask) IsCanceled() bool

IsCanceled checks if the task has been canceled by evaluating the context's Done channel.

func (*PiecesProcessingTask) IsFinished

func (t *PiecesProcessingTask) IsFinished() bool

IsFinished checks if the piece generation process has been completed. It is thread-safe and uses a mutex for locking.

type RTorrent

type RTorrent struct {
	ChunksDone        int    `bencode:"chunks_done"`
	ChunksWanted      int    `bencode:"chunks_wanted"`
	Complete          int    `bencode:"complete"`
	Directory         string `bencode:"directory"`
	Hashing           int    `bencode:"hasing"`
	State             int    `bencode:"state"`
	StateChanged      int64  `bencode:"state_changed"`
	StateCounter      int    `bencode:"state_counter"`
	TiedToFile        string `bencode:"tied_to_file"`
	TimestampFinished int64  `bencode:"timestamp.finished"`
	TimestampStarted  int64  `bencode:"timestamp.started"`
}

type Resume

type Resume struct {
	Bitfield                 int          `bencode:"bitfield"`
	Files                    []ResumeFile `bencode:"files"`
	UncertainPiecesTimestamp int64        `bencode:"uncertain_pieces.timestamp"`
}

type ResumeFile

type ResumeFile struct {
	Completed int64 `bencode:"completed"`
	Mtime     int64 `bencode:"mtime"`
	Priority  int   `bencode:"priority"`
}

type Service

type Service struct {
	// contains filtered or unexported fields
}

func (Service) Create

func (s Service) Create(rootNode *dtree.Node, announce ...string) ([]byte, error)

Create creates a torrent for a given node and returns the content as a byte slice.

func (Service) IncludeFastResume

func (s Service) IncludeFastResume(torrentContent []byte, baseDir string) ([]byte, error)

IncludeFastResume is used to incorporate fast resume data into the torrent file, allowing rtorrent to skip hash checks. basically the same as this perl script: https://github.com/rakshasa/rtorrent/blob/master/doc/rtorrent_fast_resume.pl

func (Service) Verify

func (s Service) Verify(tFile *File, sourcePath string) error

Verify verifies the files in the sourcePath against the torrent file.

type ServiceBuilder

type ServiceBuilder struct {
	// contains filtered or unexported fields
}

func NewServiceBuilder

func NewServiceBuilder() *ServiceBuilder

NewServiceBuilder creates a new ServiceBuilder with default values.

func (*ServiceBuilder) Build

func (s *ServiceBuilder) Build() *Service

Build creates a new Service with the provided configuration.

func (*ServiceBuilder) WithContext added in v0.3.0

func (s *ServiceBuilder) WithContext(ctx context.Context) *ServiceBuilder

WithContext sets the context for the service.

func (*ServiceBuilder) WithCreatedBy

func (s *ServiceBuilder) WithCreatedBy(createdBy string) *ServiceBuilder

WithCreatedBy sets metadata field `created by` to the given string.

func (*ServiceBuilder) WithHashThreads

func (s *ServiceBuilder) WithHashThreads(i int) *ServiceBuilder

WithHashThreads sets the number of threads to use for hashing.

func (*ServiceBuilder) WithParallelFileRead

func (s *ServiceBuilder) WithParallelFileRead(i int) *ServiceBuilder

WithParallelFileRead sets the parallelFileRead flag to enable or disable parallel file read mode.

func (*ServiceBuilder) WithSetProgress

func (s *ServiceBuilder) WithSetProgress(showProgress bool) *ServiceBuilder

WithSetProgress sets the showProgress flag to enable or disable the progress bar.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址