Documentation
¶
Overview ¶
Package torrent provides functionality to create and verify torrent files.
Index ¶
- Constants
- Variables
- func GetPieceLength(totalLength int64) int64
- func WriteFile(filename string, tFile *File) error
- type File
- type FileInfo
- type Files
- type Info
- type MetaInfo
- type ParallelFileRead
- type PiecesProcessingTask
- func GeneratePieces(files Files, pieceLength int64, parallelRead ParallelFileRead, hashThreads int) (*PiecesProcessingTask, error)
- func GeneratePiecesWithContext(ctx context.Context, files Files, pieceLength int64, ...) (*PiecesProcessingTask, error)
- func VerifyPieces(files Files, pieceLength int64, expectedHashes []byte, ...) (*PiecesProcessingTask, error)
- func VerifyPiecesWithContext(ctx context.Context, files Files, pieceLength int64, expectedHashes []byte, ...) (*PiecesProcessingTask, error)
- func (t *PiecesProcessingTask) GetBytesHashed() int64
- func (t *PiecesProcessingTask) GetError() error
- func (t *PiecesProcessingTask) GetNumWorkers() int
- func (t *PiecesProcessingTask) GetPieces() ([]byte, error)
- func (t *PiecesProcessingTask) GetProgress() int
- func (t *PiecesProcessingTask) IsCanceled() bool
- func (t *PiecesProcessingTask) IsFinished() bool
- type RTorrent
- type Resume
- type ResumeFile
- type Service
- type ServiceBuilder
- func (s *ServiceBuilder) Build() *Service
- func (s *ServiceBuilder) WithContext(ctx context.Context) *ServiceBuilder
- func (s *ServiceBuilder) WithCreatedBy(createdBy string) *ServiceBuilder
- func (s *ServiceBuilder) WithHashThreads(i int) *ServiceBuilder
- func (s *ServiceBuilder) WithParallelFileRead(i int) *ServiceBuilder
- func (s *ServiceBuilder) WithSetProgress(showProgress bool) *ServiceBuilder
Constants ¶
const ( // HashSize defines the size of an SHA-1 hash in bytes, used for consistent hash representation throughout the system. HashSize = sha1.Size )
Variables ¶
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 ¶
GetPieceLength returns the fitting piece length for the given size.
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 ReadFileFromBytes ¶
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 ¶
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
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 ¶
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 ¶
PieceCount calculates the number of pieces needed for all files inside Files.
func (Files) TotalLength ¶
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) UpvertedFiles ¶
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"`
}
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:
- Check task.IsFinished() regularly, or
- Listen for context cancellation
- Use task.GetPieces() to retrieve generated hashes when IsFinished() returns true
- 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:
- Check task.IsFinished() regularly, or
- Listen for context cancellation
- 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 Service ¶
type Service struct {
// contains filtered or unexported fields
}
func (Service) Create ¶
Create creates a torrent for a given node and returns the content as a byte slice.
func (Service) IncludeFastResume ¶
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
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.