NAME

Net::BitTorrent::Storage::File - File-level I/O and Block Verification

SYNOPSIS

use Net::BitTorrent::Storage::File;

my $file = Net::BitTorrent::Storage::File->new(
    path        => './data/test.bin',
    size        => 1048576,
    pieces_root => $binary_merkle_root
);

# Write data to a specific offset
$file->write( 0, $chunk );

# Verify a 16KiB block against the Merkle tree (BEP 52)
my $is_valid = $file->verify_block( $index, $data );

# Read back data
my $data = $file->read( $offset, $len );

DESCRIPTION

Net::BitTorrent::Storage::File represents a single physical file within a BitTorrent swarm. It handles the raw reading and writing of data and integrates with Digest::Merkle::SHA256 to provide block level cryptographic verification.

In BitTorrent v2 (BEP 52), every file has its own Merkle tree. This class manages the mapping of block indices to Merkle tree leaves, ensuring that every 16KiB chunk written to disk is cryptographically verified against the swarm's trusted pieces root.

It is typically used as a component of Net::BitTorrent::Storage, which manages multiple files and provides a unified view of the swarm.

METHODS

read( $offset, $length )

Reads $length bytes from the file starting at $offset. Returns the binary data or undef if the file does not exist.

write( $offset, $data )

Writes the binary string $data to the file at $offset. Automatically creates the file and any parent directories if they are missing.

verify_block( $index, $data )

Calculates the SHA-256 hash of $data and inserts it into the file's internal Merkle tree at block index $index. Returns true if the updated tree root matches the expected pieces_root.

verify_block_audit( $index, $data, $audit_path )

Verifies a block using a provided audit path (a list of sibling hashes). This allows verifying data even if the rest of the Merkle tree has not been populated yet.

path() / size() / pieces_root()

Attribute readers for the file's metadata.

dump_state() / load_state( $state )

Persistence API for saving and restoring the populated Merkle tree hashes.

AUTHOR

Sanko Robinson <sanko@cpan.org>

COPYRIGHT

Copyright (C) 2008-2026 by Sanko Robinson.

This library is free software; you can redistribute it and/or modify it under the terms of the Artistic License 2.0.