proto

package
v1.4.8 Latest Latest
Warning

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

Go to latest
Published: May 11, 2020 License: MIT Imports: 29 Imported by: 8

README

Proto

Coming Soon...

Contracts

Coming Soon...

SafeContract

Coming Soon...

ContractSet

Coming Soon...

Downloader

Coming Soon...

Editor

Coming Soon...

FileSection

Coming Soon...

FormContract

Coming Soon...

Merkle Roots

Coming Soon...

Negotiate

Coming Soon...

Reference Counter

The reference counter is a file that accompanies the contract and keeps track of the number of references to each sector. The number of references starts at one and increases as the user creates new backups of this contract. It decreases as the user deletes backups or deletes the file itself. Once the counter reaches zero, there is no way for the user to use the data stored in the sector. At this moment we are free to either reuse the sector in order to store newly uploaded data or to drop the sector when renewing the contract. The way we do that is by swapping the zero references sector with the last sector in the contract and dropping it from the reference counter list. This marks the sector as garbage and it's up for reuse/drop.

The reference counter is created and deleted together with the contract. The counts it holds should be updated on backup creation/deletion and on file deletion.

Renew

Coming Soon...

Seeds

Coming Soon...

Session

Coming Soon...

Documentation

Index

Constants

View Source
const (
	// FCSignedIdentiferSize is the size of a ContractSignedIdentifier
	FCSignedIdentiferSize = 80 // 32 bytes identifier, 32 bytes signature, 16 bytes prefix
)
View Source
const (
	// RefCounterHeaderSize is the size of the header in bytes
	RefCounterHeaderSize = 8
)

Variables

View Source
var (
	// ErrInvalidHeaderData is returned when we try to deserialize the header from
	// a []byte with incorrect data
	ErrInvalidHeaderData = errors.New("invalid header data")

	// ErrInvalidSectorNumber is returned when the requested sector doesnt' exist
	ErrInvalidSectorNumber = errors.New("invalid sector given - it does not exist")

	// ErrInvalidVersion is returned when the version of the file we are trying to
	// read does not match the current RefCounterHeaderSize
	ErrInvalidVersion = errors.New("invalid file version")

	// ErrInvalidUpdateInstruction is returned when trying to parse a WAL update
	// instruction that is too short to possibly contain all the required data.
	ErrInvalidUpdateInstruction = errors.New("instructions slice is too short to contain the required data")

	// ErrUpdateWithoutUpdateSession is returned when an update operation is
	// called without an open update session
	ErrUpdateWithoutUpdateSession = errors.New("an update operation was called without an open update session")

	// ErrUpdateAfterDelete is returned when an update operation is attempted to
	// be created after a delete
	ErrUpdateAfterDelete = errors.New("updates cannot be created after a deletion")

	// RefCounterVersion defines the latest version of the RefCounter
	RefCounterVersion = [8]byte{1}

	// UpdateNameDelete is the name of an idempotent update that deletes a file
	// from the disk.
	UpdateNameDelete = "RC_DELETE"

	// UpdateNameTruncate is the name of an idempotent update that truncates a
	// refcounter file by a number of sectors.
	UpdateNameTruncate = "RC_TRUNCATE"

	// UpdateNameWriteAt is the name of an idempotent update that writes a
	// value to a position in the file.
	UpdateNameWriteAt = "RC_WRITE_AT"
)
View Source
var (
	// ErrBadHostVersion indicates that the host is using an older, incompatible
	// version of the renter-host protocol.
	ErrBadHostVersion = errors.New("Bad host version; host does not support required protocols")
)
View Source
var ErrCSIDoesNotMatchSeed = errors.New("ContractSignedIdentifier signature bytes not equal")

ErrCSIDoesNotMatchSeed is returned when a ContractSignedIdentifier was not created with the current seed used by the renter.

Functions

func GenerateKeyPair added in v1.4.0

func GenerateKeyPair(renterSeed EphemeralRenterSeed, txn types.Transaction) (sk crypto.SecretKey, pk crypto.PublicKey)

GenerateKeyPair generates a secret and a public key for a contract to be used in its unlock conditions.

func GenerateKeyPairWithOutputID added in v1.4.0

func GenerateKeyPairWithOutputID(renterSeed EphemeralRenterSeed, inputParentID types.SiacoinOutputID) (sk crypto.SecretKey, pk crypto.PublicKey)

GenerateKeyPairWithOutputID generates a secret and a public key for a contract to be used in its unlock conditions.

func IsRevisionMismatch

func IsRevisionMismatch(err error) bool

IsRevisionMismatch returns true if err was caused by the host reporting a different revision number than expected.

Types

type ContractParams

type ContractParams struct {
	Allowance     modules.Allowance
	Host          modules.HostDBEntry
	Funding       types.Currency
	StartHeight   types.BlockHeight
	EndHeight     types.BlockHeight
	RefundAddress types.UnlockHash
	RenterSeed    EphemeralRenterSeed
}

ContractParams are supplied as an argument to FormContract.

type ContractSet added in v1.3.1

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

A ContractSet provides safe concurrent access to a set of contracts. Its purpose is to serialize modifications to individual contracts, as well as to provide operations on the set as a whole.

func NewContractSet added in v1.3.1

func NewContractSet(dir string, deps modules.Dependencies) (*ContractSet, error)

NewContractSet returns a ContractSet storing its contracts in the specified dir.

func (*ContractSet) Acquire added in v1.3.1

func (cs *ContractSet) Acquire(id types.FileContractID) (*SafeContract, bool)

Acquire looks up the contract for the specified host key and locks it before returning it. If the contract is not present in the set, Acquire returns false and a zero-valued RenterContract.

func (*ContractSet) Close added in v1.3.1

func (cs *ContractSet) Close() error

Close closes all contracts in a contract set, this means rendering it unusable for I/O

func (*ContractSet) ConvertV130Contract added in v1.3.1

func (cs *ContractSet) ConvertV130Contract(c V130Contract, cr V130CachedRevision) error

ConvertV130Contract creates a contract file for a v130 contract.

func (*ContractSet) Delete added in v1.3.1

func (cs *ContractSet) Delete(c *SafeContract)

Delete removes a contract from the set. The contract must have been previously acquired by Acquire. If the contract is not present in the set, Delete is a no-op.

func (*ContractSet) FormContract added in v1.3.1

func (cs *ContractSet) FormContract(params ContractParams, txnBuilder transactionBuilder, tpool transactionPool, hdb hostDB, cancel <-chan struct{}) (rc modules.RenterContract, formationTxnSet []types.Transaction, sweepTxn types.Transaction, sweepParents []types.Transaction, err error)

FormContract forms a contract with a host and submits the contract transaction to tpool. The contract is added to the ContractSet and its metadata is returned.

func (*ContractSet) IDs added in v1.3.1

func (cs *ContractSet) IDs() []types.FileContractID

IDs returns the fcid of each contract with in the set. The contracts are not locked.

func (*ContractSet) InsertContract added in v1.4.0

InsertContract inserts an existing contract into the set.

func (*ContractSet) Len added in v1.3.1

func (cs *ContractSet) Len() int

Len returns the number of contracts in the set.

func (*ContractSet) NewDownloader added in v1.3.1

func (cs *ContractSet) NewDownloader(host modules.HostDBEntry, id types.FileContractID, currentHeight types.BlockHeight, hdb hostDB, cancel <-chan struct{}) (_ *Downloader, err error)

NewDownloader initiates the download request loop with a host, and returns a Downloader.

func (*ContractSet) NewEditor added in v1.3.1

func (cs *ContractSet) NewEditor(host modules.HostDBEntry, id types.FileContractID, currentHeight types.BlockHeight, hdb hostDB, cancel <-chan struct{}) (_ *Editor, err error)

NewEditor initiates the contract revision process with a host, and returns an Editor.

func (*ContractSet) NewRawSession added in v1.4.0

func (cs *ContractSet) NewRawSession(host modules.HostDBEntry, currentHeight types.BlockHeight, hdb hostDB, cancel <-chan struct{}) (_ *Session, err error)

NewRawSession creates a new session unassociated with any contract.

func (*ContractSet) NewSession added in v1.4.0

func (cs *ContractSet) NewSession(host modules.HostDBEntry, id types.FileContractID, currentHeight types.BlockHeight, hdb hostDB, cancel <-chan struct{}) (_ *Session, err error)

NewSession initiates the RPC loop with a host and returns a Session.

func (*ContractSet) RateLimits added in v1.3.3

func (cs *ContractSet) RateLimits() (readBPS int64, writeBPS int64, packetSize uint64)

RateLimits sets the bandwidth limits for connections created by the contractSet.

func (*ContractSet) Renew added in v1.3.1

func (cs *ContractSet) Renew(oldContract *SafeContract, params ContractParams, txnBuilder transactionBuilder, tpool transactionPool, hdb hostDB, cancel <-chan struct{}) (rc modules.RenterContract, formationTxnSet []types.Transaction, sweepTxn types.Transaction, sweepParents []types.Transaction, err error)

Renew negotiates a new contract for data already stored with a host, and submits the new contract transaction to tpool. The new contract is added to the ContractSet and its metadata is returned.

func (*ContractSet) Return added in v1.3.1

func (cs *ContractSet) Return(c *SafeContract)

Return returns a locked contract to the set and unlocks it. The contract must have been previously acquired by Acquire. If the contract is not present in the set, Return panics.

func (*ContractSet) SetRateLimits added in v1.3.3

func (cs *ContractSet) SetRateLimits(readBPS int64, writeBPS int64, packetSize uint64)

SetRateLimits sets the bandwidth limits for connections created by the contractSet.

func (*ContractSet) View added in v1.3.1

View returns a copy of the contract with the specified host key. The contracts is not locked. Certain fields, including the MerkleRoots, are set to nil for safety reasons. If the contract is not present in the set, View returns false and a zero-valued RenterContract.

func (*ContractSet) ViewAll added in v1.3.1

func (cs *ContractSet) ViewAll() []modules.RenterContract

ViewAll returns the metadata of each contract in the set. The contracts are not locked.

type ContractSignedIdentifier added in v1.4.0

type ContractSignedIdentifier [FCSignedIdentiferSize]byte

ContractSignedIdentifier is an identifier with a prefix and appended signature, ready to be stored in the arbitrary data section of a transaction.

func PrefixedSignedIdentifier added in v1.4.0

func PrefixedSignedIdentifier(renterSeed EphemeralRenterSeed, txn types.Transaction, hostKey types.SiaPublicKey) (ContractSignedIdentifier, crypto.Ciphertext)

PrefixedSignedIdentifier is a helper function that creates a prefixed and signed identifier using a renter key and the first siacoin input of a transaction. NOTE: Always use PrefixedSignedIdentifier when creating identifiers for filecontracts. It wipes all the secrets required for creating the identifier from memory safely.

func (ContractSignedIdentifier) IsValid added in v1.4.0

IsValid checks the signature against a seed and contract to determine if it was created using the specified seed.

type Downloader

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

A Downloader retrieves sectors by calling the download RPC on a host. Downloaders are NOT thread- safe; calls to Sector must be serialized.

func (*Downloader) Close

func (hd *Downloader) Close() error

Close cleanly terminates the download loop with the host and closes the connection.

func (*Downloader) Download added in v1.4.0

func (hd *Downloader) Download(root crypto.Hash, offset, length uint32) (_ modules.RenterContract, _ []byte, err error)

Download retrieves the requested sector data and revises the underlying contract to pay the host proportionally to the data retrieved.

type Editor

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

A Editor modifies a Contract by calling the revise RPC on a host. It Editors are NOT thread-safe; calls to Upload must happen in serial.

func (*Editor) Close

func (he *Editor) Close() error

Close cleanly terminates the revision loop with the host and closes the connection.

func (*Editor) HostSettings added in v1.4.2

func (he *Editor) HostSettings() modules.HostExternalSettings

HostSettings returns the settings that are active in the current session.

func (*Editor) Upload

func (he *Editor) Upload(data []byte) (_ modules.RenterContract, _ crypto.Hash, err error)

Upload negotiates a revision that adds a sector to a file contract.

type EphemeralRenterSeed added in v1.4.0

type EphemeralRenterSeed RenterSeed

EphemeralRenterSeed is a renter seed derived from the master renter seed. The master seed should never be used directly.

type MerkleRootSet added in v1.3.1

type MerkleRootSet []crypto.Hash

MerkleRootSet is a set of Merkle roots, and gets encoded more efficiently.

func (MerkleRootSet) MarshalJSON added in v1.3.1

func (mrs MerkleRootSet) MarshalJSON() ([]byte, error)

MarshalJSON defines a JSON encoding for a MerkleRootSet.

func (*MerkleRootSet) UnmarshalJSON added in v1.3.1

func (mrs *MerkleRootSet) UnmarshalJSON(b []byte) error

UnmarshalJSON attempts to decode a MerkleRootSet, falling back on the legacy decoding of a []crypto.Hash if that fails.

type RefCounter added in v1.4.4

type RefCounter struct {
	RefCounterHeader
	// contains filtered or unexported fields
}

RefCounter keeps track of how many references to each sector exist.

Once the number of references drops to zero we consider the sector as garbage. We move the sector to end of the data and set the GarbageCollectionOffset to point to it. We can either reuse it to store new data or drop it from the contract at the end of the current period and before the contract renewal.

func LoadRefCounter added in v1.4.4

func LoadRefCounter(path string, wal *writeaheadlog.WAL) (*RefCounter, error)

LoadRefCounter loads a refcounter from disk

func NewCustomRefCounter added in v1.4.8

func NewCustomRefCounter(path string, numSec uint64, wal *writeaheadlog.WAL, deps modules.Dependencies) (*RefCounter, error)

NewCustomRefCounter creates a new sector reference counter file to accompany a contract file and allows setting custom dependencies

func NewRefCounter added in v1.4.4

func NewRefCounter(path string, numSec uint64, wal *writeaheadlog.WAL) (*RefCounter, error)

NewRefCounter creates a new sector reference counter file to accompany a contract file

func (*RefCounter) Append added in v1.4.4

func (rc *RefCounter) Append() (writeaheadlog.Update, error)

Append appends one counter to the end of the refcounter file and initializes it with `1`

func (*RefCounter) Count added in v1.4.4

func (rc *RefCounter) Count(secIdx uint64) (uint16, error)

Count returns the number of references to the given sector

func (*RefCounter) CreateAndApplyTransaction added in v1.4.6

func (rc *RefCounter) CreateAndApplyTransaction(updates ...writeaheadlog.Update) error

CreateAndApplyTransaction is a helper method that creates a writeaheadlog transaction and applies it.

func (*RefCounter) Decrement added in v1.4.4

func (rc *RefCounter) Decrement(secIdx uint64) (writeaheadlog.Update, error)

Decrement decrements the reference counter of a given sector. The sector is specified by its sequential number (secIdx). Returns the updated number of references or an error.

func (*RefCounter) DeleteRefCounter added in v1.4.4

func (rc *RefCounter) DeleteRefCounter() (writeaheadlog.Update, error)

DeleteRefCounter deletes the counter's file from disk

func (*RefCounter) DropSectors added in v1.4.4

func (rc *RefCounter) DropSectors(numSec uint64) (writeaheadlog.Update, error)

DropSectors removes the last numSec sector counts from the refcounter file

func (*RefCounter) Increment added in v1.4.4

func (rc *RefCounter) Increment(secIdx uint64) (writeaheadlog.Update, error)

Increment increments the reference counter of a given sector. The sector is specified by its sequential number (secIdx). Returns the updated number of references or an error.

func (*RefCounter) StartUpdate added in v1.4.6

func (rc *RefCounter) StartUpdate() error

StartUpdate acquires a lock, ensuring the caller is the only one currently allowed to perform updates on this refcounter file.

func (*RefCounter) Swap added in v1.4.4

func (rc *RefCounter) Swap(firstIdx, secondIdx uint64) ([]writeaheadlog.Update, error)

Swap swaps the two sectors at the given indices

func (*RefCounter) UpdateApplied added in v1.4.6

func (rc *RefCounter) UpdateApplied() error

UpdateApplied cleans up temporary data and releases the update lock, thus allowing other actors to acquire it in order to update the refcounter.

type RefCounterHeader added in v1.4.4

type RefCounterHeader struct {
	Version [8]byte
}

RefCounterHeader contains metadata about the reference counter file

type RenterSeed added in v1.4.0

type RenterSeed modules.Seed

RenterSeed is the master seed of the renter which is used to derive other seeds.

func DeriveRenterSeed added in v1.4.0

func DeriveRenterSeed(walletSeed modules.Seed) RenterSeed

DeriveRenterSeed creates a renterSeed for creating file contracts. NOTE: The seed returned by this function should be wiped once it's no longer in use.

func (RenterSeed) EphemeralRenterSeed added in v1.4.0

func (rs RenterSeed) EphemeralRenterSeed(windowStart types.BlockHeight) EphemeralRenterSeed

EphemeralRenterSeed creates a renterSeed for creating file contracts. NOTE: The seed returned by this function should be wiped once it's no longer in use.

type SafeContract added in v1.3.1

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

A SafeContract contains the most recent revision transaction negotiated with a host, and the secret key used to sign it.

func (*SafeContract) CommitPaymentIntent added in v1.4.8

func (c *SafeContract) CommitPaymentIntent(t *writeaheadlog.Transaction, signedTxn types.Transaction, amount types.Currency, rpc types.Specifier) error

CommitPaymentIntent will commit the intent to pay a host for an rpc by committing the signed txn in the contract's header.

func (*SafeContract) LastRevision added in v1.4.8

func (c *SafeContract) LastRevision() types.FileContractRevision

LastRevision returns the most recent revision

func (*SafeContract) Metadata added in v1.3.1

func (c *SafeContract) Metadata() modules.RenterContract

Metadata returns the metadata of a renter contract

func (*SafeContract) RecordPaymentIntent added in v1.4.8

func (c *SafeContract) RecordPaymentIntent(rev types.FileContractRevision, amount types.Currency, rpc types.Specifier) (*writeaheadlog.Transaction, error)

RecordPaymentIntent will records the changes we are about to make to the revision in order to pay a host for an RPC.

func (*SafeContract) Sign added in v1.4.8

func (c *SafeContract) Sign(hash crypto.Hash) crypto.Signature

Sign will sign the given hash using the safecontract's secret key

func (*SafeContract) UpdateUtility added in v1.3.3

func (c *SafeContract) UpdateUtility(utility modules.ContractUtility) error

UpdateUtility updates the utility field of a contract.

func (*SafeContract) Utility added in v1.3.3

func (c *SafeContract) Utility() modules.ContractUtility

Utility returns the contract utility for the contract.

type Session added in v1.4.0

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

A Session is an ongoing exchange of RPCs via the renter-host protocol.

TODO: The session type needs access to a logger. Probably the renter logger.

func (*Session) Append added in v1.4.0

func (s *Session) Append(data []byte) (_ modules.RenterContract, _ crypto.Hash, err error)

Append calls the Write RPC with a single Append action, returning the updated contract and the Merkle root of the appended sector.

func (*Session) Close added in v1.4.0

func (s *Session) Close() error

Close cleanly terminates the protocol session with the host and closes the connection.

func (*Session) HostSettings added in v1.4.2

func (s *Session) HostSettings() modules.HostExternalSettings

HostSettings returns the currently active host settings of the session.

func (*Session) Lock added in v1.4.0

Lock calls the Lock RPC, locking the supplied contract and returning its most recent revision.

func (*Session) Read added in v1.4.0

func (s *Session) Read(w io.Writer, req modules.LoopReadRequest, cancel <-chan struct{}) (_ modules.RenterContract, err error)

Read calls the Read RPC, writing the requested data to w. The RPC can be cancelled (with a granularity of one section) via the cancel channel.

func (*Session) ReadSection added in v1.4.0

func (s *Session) ReadSection(root crypto.Hash, offset, length uint32) (_ modules.RenterContract, _ []byte, err error)

ReadSection calls the Read RPC with a single section and returns the requested data. A Merkle proof is always requested.

func (*Session) RecoverSectorRoots added in v1.4.0

func (s *Session) RecoverSectorRoots(lastRev types.FileContractRevision, sk crypto.SecretKey) (_ types.Transaction, _ []crypto.Hash, err error)

RecoverSectorRoots calls the contract roots download RPC and returns the requested sector roots. The Revision and Signature fields of req are filled in automatically. If a Merkle proof is requested, it is verified.

func (*Session) Replace added in v1.4.1

func (s *Session) Replace(data []byte, sectorIndex uint64, trim bool) (_ modules.RenterContract, _ crypto.Hash, err error)

Replace calls the Write RPC with a series of actions that replace the sector at the specified index with data, returning the updated contract and the Merkle root of the new sector.

func (*Session) SectorRoots added in v1.4.0

func (s *Session) SectorRoots(req modules.LoopSectorRootsRequest) (_ modules.RenterContract, _ []crypto.Hash, err error)

SectorRoots calls the contract roots download RPC and returns the requested sector roots. The Revision and Signature fields of req are filled in automatically. If a Merkle proof is requested, it is verified.

func (*Session) Settings added in v1.4.0

func (s *Session) Settings() (modules.HostExternalSettings, error)

Settings calls the Settings RPC, returning the host's reported settings.

func (*Session) Unlock added in v1.4.0

func (s *Session) Unlock() error

Unlock calls the Unlock RPC, unlocking the currently-locked contract.

func (*Session) Write added in v1.4.0

func (s *Session) Write(actions []modules.LoopWriteAction) (_ modules.RenterContract, err error)

Write implements the Write RPC, except for ActionUpdate. A Merkle proof is always requested.

type V130CachedRevision added in v1.3.1

type V130CachedRevision struct {
	Revision    types.FileContractRevision `json:"revision"`
	MerkleRoots modules.MerkleRootSet      `json:"merkleroots"`
}

A V130CachedRevision contains changes that would be applied to a RenterContract if a contract revision succeeded.

type V130Contract added in v1.3.1

type V130Contract struct {
	HostPublicKey    types.SiaPublicKey         `json:"hostpublickey"`
	ID               types.FileContractID       `json:"id"`
	LastRevision     types.FileContractRevision `json:"lastrevision"`
	LastRevisionTxn  types.Transaction          `json:"lastrevisiontxn"`
	MerkleRoots      MerkleRootSet              `json:"merkleroots"`
	SecretKey        crypto.SecretKey           `json:"secretkey"`
	StartHeight      types.BlockHeight          `json:"startheight"`
	DownloadSpending types.Currency             `json:"downloadspending"`
	StorageSpending  types.Currency             `json:"storagespending"`
	UploadSpending   types.Currency             `json:"uploadspending"`
	TotalCost        types.Currency             `json:"totalcost"`
	ContractFee      types.Currency             `json:"contractfee"`
	TxnFee           types.Currency             `json:"txnfee"`
	SiafundFee       types.Currency             `json:"siafundfee"`
}

A V130Contract specifies the v130 contract format.

func (*V130Contract) EndHeight added in v1.3.1

func (c *V130Contract) EndHeight() types.BlockHeight

EndHeight returns the height at which the host is no longer obligated to store contract data.

func (*V130Contract) RenterFunds added in v1.3.1

func (c *V130Contract) RenterFunds() types.Currency

RenterFunds returns the funds remaining in the contract's Renter payout as of the most recent revision.

Jump to

Keyboard shortcuts

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