github.com/NebulousLabs/Sia@v1.3.7/siatest/localfile.go (about)

     1  package siatest
     2  
     3  import (
     4  	"io/ioutil"
     5  	"math"
     6  	"os"
     7  	"path/filepath"
     8  	"strconv"
     9  
    10  	"github.com/NebulousLabs/Sia/crypto"
    11  	"github.com/NebulousLabs/errors"
    12  	"github.com/NebulousLabs/fastrand"
    13  )
    14  
    15  type (
    16  	// LocalFile is a helper struct that represents a file uploaded to the Sia
    17  	// network.
    18  	LocalFile struct {
    19  		path     string
    20  		checksum crypto.Hash
    21  	}
    22  )
    23  
    24  // NewFile creates and returns a new LocalFile. It will write size random bytes
    25  // to the file and give the file a random name.
    26  func NewFile(size int) (*LocalFile, error) {
    27  	fileName := strconv.Itoa(fastrand.Intn(math.MaxInt32))
    28  	path := filepath.Join(SiaTestingDir, fileName)
    29  	bytes := fastrand.Bytes(size)
    30  	err := ioutil.WriteFile(path, bytes, 0600)
    31  	return &LocalFile{
    32  		path:     path,
    33  		checksum: crypto.HashBytes(bytes),
    34  	}, err
    35  }
    36  
    37  // Delete removes the LocalFile from disk.
    38  func (lf *LocalFile) Delete() error {
    39  	return os.Remove(lf.path)
    40  }
    41  
    42  // checkIntegrity compares the in-memory checksum to the checksum of the data
    43  // on disk
    44  func (lf *LocalFile) checkIntegrity() error {
    45  	data, err := ioutil.ReadFile(lf.path)
    46  	if err != nil {
    47  		return errors.AddContext(err, "failed to read file from disk")
    48  	}
    49  	if crypto.HashBytes(data) != lf.checksum {
    50  		return errors.New("checksums don't match")
    51  	}
    52  	return nil
    53  }
    54  
    55  // fileName returns the file name of the file on disk
    56  func (lf *LocalFile) fileName() string {
    57  	return filepath.Base(lf.path)
    58  }
    59  
    60  // partialChecksum returns the checksum of a part of the file.
    61  func (lf *LocalFile) partialChecksum(from, to uint64) (crypto.Hash, error) {
    62  	data, err := ioutil.ReadFile(lf.path)
    63  	if err != nil {
    64  		return crypto.Hash{}, errors.AddContext(err, "failed to read file from disk")
    65  	}
    66  	return crypto.HashBytes(data[from:to]), nil
    67  }