Documentation ¶
Index ¶
- Constants
- Variables
- func AddContext(err error, ctx string) error
- func CalculateLeaves(dataSize uint64) uint64
- func CheckGouging(a Allowance, height uint64, hs *rhpv2.HostSettings, pt *rhpv3.HostPriceTable, ...) (err error)
- func ComposeErrors(errs ...error) error
- func ContainsError(base, target error) bool
- func CopyTransaction(txn types.Transaction) types.Transaction
- func DecodeV2Announcement(at types.Attestation) (na string, pk types.PublicKey, err error)
- func DeriveAccountKey(ak types.PrivateKey, hpk types.PublicKey) types.PrivateKey
- func DeriveEphemeralKey(rsk types.PrivateKey, hpk types.PublicKey) types.PrivateKey
- func DeriveRenterKey(masterKey types.PrivateKey, email string) []byte
- func EncodedLen(txn types.Transaction) int
- func FilesizeUnits(size uint64) string
- func Float64(c types.Currency) float64
- func FromFloat(f float64) types.Currency
- func GenerateKeyPair(seed types.Hash256) (sk types.PrivateKey, pk types.PublicKey)
- func KeyFromSeed(seed *Seed, index uint64) types.PrivateKey
- func MulFloat(c types.Currency, f float64) types.Currency
- func NewSeedPhrase() string
- func PeekErr(errChan <-chan error) (err error)
- func PostTax(height uint64, payout types.Currency) types.Currency
- func ReadCurrency(s string) types.Currency
- func RenterPayoutsPreTax(host HostDBEntry, funding, txnFee, basePrice, baseCollateral types.Currency, ...) (renterPayout, hostPayout, hostCollateral types.Currency, err error)
- func SeedFromPhrase(seed *Seed, phrase string) error
- func Tax(height uint64, payout types.Currency) types.Currency
- func ToString(c types.Currency) string
- func VerifyRangeProof(segments []byte, proof []types.Hash256, start, end int, root types.Hash256) bool
- func VerifySegment(base []byte, hashSet []types.Hash256, numSegments, proofIndex uint64, ...) bool
- type Allowance
- type BucketFiles
- type ContractMetadata
- type ContractUtility
- type ContractWatchStatus
- type CreditData
- type ExtendedContract
- type ExtendedContractSet
- type FileMetadata
- type FilterMode
- type HostAverages
- type HostDB
- type HostDBEntry
- type HostDBScan
- type HostDBScans
- type HostScoreBreakdown
- type MaintenanceSpending
- type Manager
- type MerkleTree
- type NetAddress
- type PoolTransaction
- type Portal
- type Price
- type Pricing
- type Provider
- type RPCError
- type RPCResponse
- type RPCSession
- func (s *RPCSession) ReadMessage(message RequestBody, maxLen uint64) error
- func (s *RPCSession) ReadRequest(req RequestBody, maxLen uint64) (types.Hash256, error)
- func (s *RPCSession) ReadResponse(resp RequestBody, maxLen uint64) error
- func (s *RPCSession) WriteError(err error) error
- func (s *RPCSession) WriteMessage(message RequestBody) error
- func (s *RPCSession) WriteResponse(resp RequestBody) error
- type Renter
- type RenterContract
- type RenterSettings
- type RenterSpending
- type RequestBody
- type Seed
- type Shard
- type Slab
- type SpendingDetails
- type Syncer
- type UserBalance
- type UserSpendings
- type Wallet
Constants ¶
const ( // BlocksPerHour is the number of blocks expected to be mined per hour. BlocksPerHour = uint64(6) // BlocksPerDay is the number of blocks expected to be mined per day. BlocksPerDay = 24 * BlocksPerHour // BlocksPerWeek is the number of blocks expected to be mined per week. BlocksPerWeek = 7 * BlocksPerDay // BlocksPerMonth is the number of blocks expected to be mined per month. BlocksPerMonth = 30 * BlocksPerDay // BlocksPerYear is the number of blocks expected to be mined per year. BlocksPerYear = 365 * BlocksPerDay )
const BytesPerTerabyte = 1024 * 1024 * 1024 * 1024
BytesPerTerabyte is how many bytes are there in one TiB.
const MaxEncodedNetAddressLength = 266
MaxEncodedNetAddressLength is the maximum length of a NetAddress encoded with the encode package. 266 was chosen because the maximum length for the hostname is 254 + 1 for the separating colon + 5 for the port + 8 byte string length prefix.
const MinMessageSize = 4096
MinMessageSize is the minimum size of an RPC message. If an encoded message would be smaller than minMessageSize, the sender MAY pad it with random data. This hinders traffic analysis by obscuring the true sizes of messages.
const OnHoldThreshold = 24 * time.Hour
OnHoldThreshold is how much time shall pass until we put the account in pre-payment mode.
const ( // SegmentSize is the chunk size that is used when taking the Merkle root // of a file. 64 is chosen because bandwidth is scarce and it optimizes for // the smallest possible storage proofs. Using a larger base, even 256 // bytes, would result in substantially faster hashing, but the bandwidth // tradeoff was deemed to be more important, as blockchain space is scarce. SegmentSize = 64 )
Variables ¶
var ( // MaxRPCPrice is how much the Satellite is willing to pay // for a single RPC call. MaxRPCPrice = types.HastingsPerSiacoin.Div64(1e6) // MaxSectorAccessPrice is how much the Satellite is willing // to pay to download a single sector. MaxSectorAccessPrice = types.HastingsPerSiacoin.Div64(1e5) )
var ( // BlockBytesPerMonthTerabyte is the conversion rate between block-bytes and month-TB. BlockBytesPerMonthTerabyte = types.NewCurrency64(BytesPerTerabyte).Mul64(BlocksPerMonth) )
var DefaultAllowance = Allowance{ Funds: types.HastingsPerSiacoin.Mul64(2500), Hosts: 50, Period: 2 * BlocksPerMonth, RenewWindow: BlocksPerMonth, ExpectedStorage: 1e12, ExpectedUpload: uint64(200e9) / BlocksPerMonth, ExpectedDownload: uint64(100e9) / BlocksPerMonth, MinShards: 10, TotalShards: 30, BlockHeightLeeway: 3, }
DefaultAllowance is the set of default allowance settings that will be used when allowances are not set or not fully set.
var DefaultPricing = Pricing{ FormContract: Price{ PrePayment: 0.1, Invoicing: 0.15, }, SaveMetadata: Price{ PrePayment: 0.01, Invoicing: 0.015, }, StoreMetadata: Price{ PrePayment: 0.01, Invoicing: 0.015, }, StorePartialData: Price{ PrePayment: 0.005, Invoicing: 0.0075, }, RetrieveMetadata: Price{ PrePayment: 0.1, Invoicing: 0.15, }, MigrateSlab: Price{ PrePayment: 0.01, Invoicing: 0.015, }, }
DefaultPricing provides some default prices if none are set.
var ( // ErrInsufficientBalance is returned when there aren't enough unused outputs // to cover the requested amount. ErrInsufficientBalance = errors.New("insufficient balance") )
Functions ¶
func AddContext ¶
AddContext wraps an error in a context.
func CalculateLeaves ¶
CalculateLeaves calculates the number of leaves that would be pushed from data of size 'dataSize'.
func CheckGouging ¶
func CheckGouging(a Allowance, height uint64, hs *rhpv2.HostSettings, pt *rhpv3.HostPriceTable, txnFee types.Currency) (err error)
CheckGouging performs a number of gouging checks before forming a contract with the host.
func ComposeErrors ¶
ComposeErrors combines several errors in one.
func ContainsError ¶
ContainsError checks if one error contains the other.
func CopyTransaction ¶
func CopyTransaction(txn types.Transaction) types.Transaction
CopyTransaction creates a deep copy of the transaction.
func DecodeV2Announcement ¶ added in v0.11.0
DecodeV2Announcement verifies a V2 host announcement against the signature.
func DeriveAccountKey ¶
func DeriveAccountKey(ak types.PrivateKey, hpk types.PublicKey) types.PrivateKey
DeriveAccountKey derives an account key to be used by the renter to access the ephemeral account at the host.
func DeriveEphemeralKey ¶
func DeriveEphemeralKey(rsk types.PrivateKey, hpk types.PublicKey) types.PrivateKey
DeriveEphemeralKey derives a secret key to be used by the renter for the exchange with the host.
func DeriveRenterKey ¶ added in v0.11.0
func DeriveRenterKey(masterKey types.PrivateKey, email string) []byte
DeriveRenterKey derives a key to be used by the renter for accessing the file contracts. NOTE: The key returned by this function should be wiped once it's no longer in use.
func EncodedLen ¶ added in v0.11.0
func EncodedLen(txn types.Transaction) int
EncodedLen returns the encoded length of a transaction.
func FilesizeUnits ¶
FilesizeUnits returns a string that displays a filesize in human-readable units.
func GenerateKeyPair ¶
GenerateKeyPair generates a private/public keypair from a seed.
func KeyFromSeed ¶ added in v0.11.0
func KeyFromSeed(seed *Seed, index uint64) types.PrivateKey
KeyFromSeed returns the Ed25519 key derived from the supplied seed at the specified index.
func PeekErr ¶
PeekErr checks if a chan error has an error waiting to be returned. If it has it will return that error. Otherwise it returns 'nil'.
func PostTax ¶
PostTax returns the amount of currency remaining in a file contract payout after tax.
func ReadCurrency ¶
ReadCurrency converts a string to types.Currency.
func RenterPayoutsPreTax ¶
func RenterPayoutsPreTax(host HostDBEntry, funding, txnFee, basePrice, baseCollateral types.Currency, period uint64, expectedStorage uint64) (renterPayout, hostPayout, hostCollateral types.Currency, err error)
RenterPayoutsPreTax calculates the renterPayout before tax and the hostPayout given a host, the available renter funding, the expected txnFee for the transaction and an optional basePrice in case this helper is used for a renewal. It also returns the hostCollateral.
func SeedFromPhrase ¶ added in v0.11.0
SeedFromPhrase converts the supplied phrase into a 16-byte seed.
func ToString ¶ added in v0.11.3
ToString formats a types.Currency to a maximum of 2 decimal places.
Types ¶
type Allowance ¶
type Allowance struct { Funds types.Currency Hosts uint64 Period uint64 RenewWindow uint64 // ExpectedStorage is the amount of data that we expect to have in a contract. ExpectedStorage uint64 // ExpectedUpload is the expected amount of data uploaded through the API, // before redundancy, per block. ExpectedUpload uint64 // ExpectedDownload is the expected amount of data downloaded through the // API per block. ExpectedDownload uint64 // Erasure coding parameters. MinShards uint64 TotalShards uint64 // The following fields provide price gouging protection for the user. By // setting a particular maximum price for each mechanism that a host can use // to charge users, the workers know to avoid hosts that go outside of the // safety range. MaxRPCPrice types.Currency MaxContractPrice types.Currency MaxDownloadBandwidthPrice types.Currency MaxSectorAccessPrice types.Currency MaxStoragePrice types.Currency MaxUploadBandwidthPrice types.Currency MinMaxCollateral types.Currency BlockHeightLeeway uint64 // UploadPacking indicates whether the upload packing is turned on. UploadPacking bool }
An Allowance dictates how much the renter is allowed to spend in a given period. Note that funds are spent on both storage and bandwidth.
func (Allowance) Active ¶
Active returns true if and only if this allowance has been set in the contractor.
func (*Allowance) DecodeFrom ¶
DecodeFrom implements types.DecoderFrom.
type BucketFiles ¶ added in v0.7.0
BucketFiles contains a list of filepaths within a single bucket.
func (*BucketFiles) DecodeFrom ¶ added in v0.7.0
func (bf *BucketFiles) DecodeFrom(d *types.Decoder)
DecodeFrom implements types.ProtocolObject.
func (*BucketFiles) EncodeTo ¶ added in v0.7.0
func (bf *BucketFiles) EncodeTo(e *types.Encoder)
EncodeTo implements types.ProtocolObject.
type ContractMetadata ¶
type ContractMetadata struct { ID types.FileContractID HostKey types.PublicKey StartHeight uint64 RenewedFrom types.FileContractID UploadSpending types.Currency DownloadSpending types.Currency FundAccountSpending types.Currency ContractPrice types.Currency TotalCost types.Currency Revision types.FileContractRevision }
ContractMetadata contains all metadata needed to re-create a contract.
func (*ContractMetadata) DecodeFrom ¶
func (cm *ContractMetadata) DecodeFrom(d *types.Decoder)
DecodeFrom implements requestBody.
func (*ContractMetadata) EncodeTo ¶
func (cm *ContractMetadata) EncodeTo(e *types.Encoder)
EncodeTo implements requestBody.
type ContractUtility ¶
type ContractUtility struct { GoodForUpload bool GoodForRenew bool // BadContract will be set to true if there's good reason to believe that // the contract is unusable and will continue to be unusable. For example, // if the host is claiming that the contract does not exist, the contract // should be marked as bad. BadContract bool LastOOSErr uint64 // OOS means Out Of Storage. // If a contract is locked, the utility should not be updated. 'Locked' is a // value that gets persisted. Locked bool }
ContractUtility contains metrics internal to the contractor that reflect the utility of a given contract.
type ContractWatchStatus ¶
type ContractWatchStatus struct { Archived bool FormationSweepHeight uint64 ContractFound bool LatestRevisionFound uint64 StorageProofFoundAtHeight uint64 DoubleSpendHeight uint64 WindowStart uint64 WindowEnd uint64 }
ContractWatchStatus provides information about the status of a contract in the manager's watchdog.
type CreditData ¶
CreditData contains the information about any running promotion.
type ExtendedContract ¶
type ExtendedContract struct { Contract rhpv2.ContractRevision StartHeight uint64 ContractPrice types.Currency TotalCost types.Currency UploadSpending types.Currency DownloadSpending types.Currency FundAccountSpending types.Currency RenewedFrom types.FileContractID }
ExtendedContract contains the contract and its metadata.
func (ExtendedContract) DecodeFrom ¶
func (ec ExtendedContract) DecodeFrom(d *types.Decoder)
DecodeFrom implements requestBody.
func (ExtendedContract) EncodeTo ¶
func (ec ExtendedContract) EncodeTo(e *types.Encoder)
EncodeTo implements requestBody.
type ExtendedContractSet ¶
type ExtendedContractSet struct {
Contracts []ExtendedContract
}
ExtendedContractSet is a collection of extendedContracts.
func (ExtendedContractSet) DecodeFrom ¶
func (ecs ExtendedContractSet) DecodeFrom(d *types.Decoder)
DecodeFrom implements requestBody.
func (ExtendedContractSet) EncodeTo ¶
func (ecs ExtendedContractSet) EncodeTo(e *types.Encoder)
EncodeTo implements requestBody.
type FileMetadata ¶
type FileMetadata struct { Key types.Hash256 `json:"key"` Bucket []byte `json:"bucket"` Path []byte `json:"path"` ETag string `json:"etag"` MimeType []byte `json:"mime"` Encrypted string `json:"encrypted"` Slabs []Slab `json:"slabs"` Data []byte `json:"data"` }
FileMetadata contains the uploaded file metadata.
func (*FileMetadata) DecodeFrom ¶
func (fm *FileMetadata) DecodeFrom(d *types.Decoder)
DecodeFrom implements types.ProtocolObject.
func (*FileMetadata) EncodeTo ¶
func (fm *FileMetadata) EncodeTo(e *types.Encoder)
EncodeTo implements types.ProtocolObject.
type FilterMode ¶
type FilterMode int
FilterMode is the helper type for the enum constants for the HostDB filter mode.
const ( HostDBFilterError FilterMode = iota HostDBDisableFilter HostDBActivateBlacklist HostDBActiveWhitelist )
HostDBFilterError HostDBDisableFilter HostDBActivateBlacklist and HostDBActiveWhitelist are the constants used to enable and disable the filter mode of the manager's hostdb.
func (*FilterMode) FromString ¶
func (fm *FilterMode) FromString(s string) error
FromString assigned the FilterMode from the provide string.
func (FilterMode) String ¶
func (fm FilterMode) String() string
String returns the string value for the FilterMode.
type HostAverages ¶
type HostAverages struct { NumHosts uint64 `json:"numhosts"` Duration uint64 `json:"duration"` StoragePrice types.Currency `json:"storageprice"` Collateral types.Currency `json:"collateral"` DownloadBandwidthPrice types.Currency `json:"downloadbandwidthprice"` UploadBandwidthPrice types.Currency `json:"uploadbandwidthprice"` ContractPrice types.Currency `json:"contractprice"` BaseRPCPrice types.Currency `json:"baserpcprice"` SectorAccessPrice types.Currency `json:"sectoraccessprice"` }
HostAverages contains the host network averages from HostDB.
func (*HostAverages) DecodeFrom ¶
func (ha *HostAverages) DecodeFrom(d *types.Decoder)
DecodeFrom implements types.DecoderFrom.
func (*HostAverages) EncodeTo ¶
func (ha *HostAverages) EncodeTo(e *types.Encoder)
EncodeTo implements types.EncoderTo.
type HostDB ¶
type HostDB interface { // ActiveHosts returns the list of hosts that are actively being selected // from. ActiveHosts() ([]HostDBEntry, error) // AllHosts returns the full list of hosts known to the hostdb, sorted in // order of preference. AllHosts() ([]HostDBEntry, error) // CheckForIPViolations accepts a number of host public keys and returns the // ones that violate the rules of the addressFilter. CheckForIPViolations([]types.PublicKey) ([]types.PublicKey, error) // Close closes the hostdb. Close() error // EstimateHostScore returns the estimated score breakdown of a host with the // provided settings. EstimateHostScore(Allowance, HostDBEntry) (HostScoreBreakdown, error) // Filter returns the hostdb's filterMode and filteredHosts. Filter() (FilterMode, map[string]types.PublicKey, []string, error) // SetFilterMode sets the renter's hostdb filter mode. SetFilterMode(FilterMode, []types.PublicKey, []string) error // Host returns the HostDBEntry for a given host. Host(pk types.PublicKey) (HostDBEntry, bool, error) // IncrementSuccessfulInteractions increments the number of successful // interactions with a host for a given key IncrementSuccessfulInteractions(types.PublicKey) error // IncrementFailedInteractions increments the number of failed interactions with // a host for a given key IncrementFailedInteractions(types.PublicKey) error // initialScanComplete returns a boolean indicating if the initial scan of the // hostdb is completed and the current block height of the hostdb. InitialScanComplete() (bool, uint64, error) // IPViolationsCheck returns a boolean indicating if the IP violation check is // enabled or not. IPViolationsCheck() (bool, error) // RandomHosts returns a set of random hosts, weighted by their estimated // usefulness / attractiveness to the renter. RandomHosts will not return // any offline or inactive hosts. RandomHosts(int, []types.PublicKey, []types.PublicKey) ([]HostDBEntry, error) // RandomHostsWithAllowance is the same as RandomHosts but accepts an // allowance as an argument to be used instead of the allowance set in the // manager. RandomHostsWithAllowance(int, []types.PublicKey, []types.PublicKey, Allowance) ([]HostDBEntry, error) // ScoreBreakdown returns a detailed explanation of the various properties // of the host. ScoreBreakdown(HostDBEntry) (HostScoreBreakdown, error) // SetAllowance updates the allowance used by the hostdb for weighing hosts by // updating the host weight function. It will completely rebuild the hosttree so // it should be used with care. SetAllowance(Allowance) error // SetIPViolationCheck enables/disables the IP violation check within the // hostdb. SetIPViolationCheck(enabled bool) error // LoadingComplete indicates if the HostDB has finished loading the hosts // from the database. LoadingComplete() bool // UpdateContracts rebuilds the knownContracts of the HostBD using the // provided contracts. UpdateContracts([]RenterContract) error }
A HostDB is a database of hosts that the manager can use for figuring out who to upload to, and download from.
type HostDBEntry ¶
type HostDBEntry struct { // Need to wrap rhpv2.HostSettings in a separate named field due to // issues with JSON encoding. Settings rhpv2.HostSettings `json:"settings"` PriceTable rhpv3.HostPriceTable `json:"pricetable"` // FirstSeen is the first block height at which this host was announced. FirstSeen uint64 `json:"firstseen"` // LastAnnouncement is the last block height at which this host was announced. LastAnnouncement uint64 `json:"lastannouncement"` // Measurements that have been taken on the host. The most recent // measurements are kept in full detail, historic ones are compressed into // the historic values. HistoricDowntime time.Duration `json:"historicdowntime"` HistoricUptime time.Duration `json:"historicuptime"` ScanHistory HostDBScans `json:"scanhistory"` // Measurements that are taken whenever we interact with a host. HistoricFailedInteractions float64 `json:"historicfailedinteractions"` HistoricSuccessfulInteractions float64 `json:"historicsuccessfulinteractions"` RecentFailedInteractions float64 `json:"recentfailedinteractions"` RecentSuccessfulInteractions float64 `json:"recentsuccessfulinteractions"` LastHistoricUpdate uint64 `json:"lasthistoricupdate"` // Measurements related to the IP subnet mask. IPNets []string `json:"ipnets"` LastIPNetChange time.Time `json:"lastipnetchange"` // The public key of the host, stored separately to minimize risk of certain // MitM based vulnerabilities. PublicKey types.PublicKey `json:"publickey"` // Filtered says whether or not a HostDBEntry is being filtered out of the // filtered hosttree due to the filter mode of the hosttree. Filtered bool `json:"filtered"` }
A HostDBEntry represents one host entry in the Manager's host DB. It aggregates the host's external settings and metrics with its public key.
type HostDBScan ¶
HostDBScan represents a single scan event.
type HostDBScans ¶
type HostDBScans []HostDBScan
HostDBScans represents a sortable slice of scans.
func (HostDBScans) Len ¶
func (s HostDBScans) Len() int
func (HostDBScans) Less ¶
func (s HostDBScans) Less(i, j int) bool
func (HostDBScans) Swap ¶
func (s HostDBScans) Swap(i, j int)
type HostScoreBreakdown ¶
type HostScoreBreakdown struct { Score types.Currency `json:"score"` Age float64 `json:"agescore"` Collateral float64 `json:"collateralscore"` Interactions float64 `json:"interactionscore"` StorageRemaining float64 `json:"storageremainingscore"` Uptime float64 `json:"uptimescore"` Version float64 `json:"versionscore"` Prices float64 `json:"pricescore"` }
HostScoreBreakdown breaks down the host scores.
type MaintenanceSpending ¶
type MaintenanceSpending struct { AccountBalanceCost types.Currency FundAccountCost types.Currency UpdatePriceTableCost types.Currency }
MaintenanceSpending is a helper struct that contains a breakdown of costs related to the maintenance (a.k.a upkeep) of the RHP3 protocol. This includes the costs to sync the account balance, update the price table, etc.
func (MaintenanceSpending) Add ¶
func (x MaintenanceSpending) Add(y MaintenanceSpending) MaintenanceSpending
Add is a convenience function that sums the fields of the spending object with the corresponding fields of the given object.
func (MaintenanceSpending) Sum ¶
func (x MaintenanceSpending) Sum() types.Currency
Sum is a convenience function that sums up all of the fields in the spending object and returns the total as a types.Currency.
type Manager ¶
type Manager interface { // AcceptContracts accepts a set of contracts from the renter // and adds them to the contract set. AcceptContracts(types.PublicKey, []ContractMetadata) // ActiveHosts returns an array of HostDB's active hosts. ActiveHosts() ([]HostDBEntry, error) // AllHosts returns an array of all hosts. AllHosts() ([]HostDBEntry, error) // AssembleParts puts together the parts of a multipart upload and // marks the resulting file as pending upload. AssembleParts(types.PublicKey, types.Hash256) error // BlockHeight returns the current block height. BlockHeight() uint64 // BufferedFilesDir returns the path to the buffered files directory. BufferedFilesDir() string // BytesUploaded returns the size of the file already uploaded. BytesUploaded(types.PublicKey, []byte, []byte) (string, uint64, error) // Close safely shuts down the manager. Close() error // Contracts returns storage contracts. Contracts() []RenterContract // ContractsByRenter returns storage contracts filtered by the renter. ContractsByRenter(types.PublicKey) []RenterContract // CreateNewRenter inserts a new renter into the map. CreateNewRenter(string, types.PublicKey) // DeleteBufferedFile deletes the specified file and the associated // database record. DeleteBufferedFile(types.PublicKey, []byte, []byte) error // DeleteBufferedFiles deletes the files waiting to be uploaded. DeleteBufferedFiles(types.PublicKey) error // DeleteMetadata deletes the renter's saved file metadata. DeleteMetadata(types.PublicKey) error // DeleteMultipart deletes an aborted multipart upload. DeleteMultipart(types.PublicKey, types.Hash256) error // DeleteMultipartUploads deletes the unfinished multipart uploads. DeleteMultipartUploads(types.PublicKey) error // DeleteObject deletes the saved file metadata object. DeleteObject(types.PublicKey, []byte, []byte) error // DeleteRenter deletes the renter data from the memory. DeleteRenter(string) // DownloadObject downloads an object and returns it. DownloadObject(io.Writer, types.PublicKey, []byte, []byte) error // FeeEstimation returns the recommended fee for a transaction. FeeEstimation() types.Currency // Filter returns the HostDB's filterMode and filteredHosts. Filter() (FilterMode, map[string]types.PublicKey, []string, error) // FormContract forms a contract with the specified host. FormContract(*RPCSession, types.PublicKey, types.PublicKey, types.PublicKey, uint64, uint64, uint64, uint64, uint64, uint64) (RenterContract, error) // FormContracts forms the required number of contracts with the hosts. FormContracts(types.PublicKey, types.PrivateKey, Allowance) ([]RenterContract, error) // GetAverages retrieves the host network averages. GetAverages() HostAverages // GetBalance retrieves the balance information on the account. GetBalance(string) (UserBalance, error) // GetBufferSize returns the total size of the temporary files. GetBufferSize() (uint64, error) // GetEmailPreferences returns the email preferences. GetEmailPreferences() (string, types.Currency) // GetModifiedSlabs returns the slabs modified since the last retrieval. GetModifiedSlabs(types.PublicKey) ([]Slab, error) // GetRenter returns the renter by the public key. GetRenter(types.PublicKey) (Renter, error) // GetSiacoinRate calculates the SC price in a given currency. GetSiacoinRate(string) (float64, error) // GetSpendings retrieves the user's spendings. GetSpendings(string, int, int) (UserSpendings, error) // Host returns the host associated with the given public key. Host(types.PublicKey) (HostDBEntry, bool, error) // IncrementStats increments the number of formed or renewed contracts. IncrementStats(string, bool) error // InitialScanComplete returns a boolean indicating if the initial scan of the // HostDB is completed. InitialScanComplete() (bool, uint64, error) // LockSiacoins moves a part of the balance to "locked". LockSiacoins(string, float64) error // Maintenance returns true if the maintenance mode is active. Maintenance() bool // OldContracts returns the contracts that have expired. OldContracts() []RenterContract // OldContractsByRenter returns expired contracts filtered by the renter. OldContractsByRenter(types.PublicKey) []RenterContract // PutMultipartPart associates the uploaded file with the part of // a multipart upload. PutMultipartPart(types.PublicKey, types.Hash256, int, string) error // RandomHosts picks up to the specified number of random hosts from the // hostdb sorted by weight. RandomHosts(uint64, Allowance) ([]HostDBEntry, error) // RefreshedContract returns a bool indicating if the contract was refreshed. RefreshedContract(types.FileContractID) bool // RegisterMultipart registers a new multipart upload. RegisterMultipart(types.PublicKey, types.Hash256, []byte, []byte, []byte, bool) (types.Hash256, error) // RegisterUpload associates the uploaded file with the object. RegisterUpload(types.PublicKey, []byte, []byte, []byte, bool, string, bool) error // RenewContract renews a contract. RenewContract(*RPCSession, types.PublicKey, types.FileContractID, uint64, uint64, uint64, uint64, uint64, uint64) (RenterContract, error) // RenewContracts renews a set of contracts and returns a new set. RenewContracts(types.PublicKey, types.PrivateKey, Allowance, []types.FileContractID) ([]RenterContract, error) // RenewedFrom returns the ID of the contract the given contract was renewed // from, if any. RenewedFrom(types.FileContractID) types.FileContractID // Renters retrieves the list of renters. Renters() []Renter // RetrieveMetadata retrieves the file metadata from the database. RetrieveMetadata(types.PublicKey, []BucketFiles) ([]FileMetadata, error) // RetrieveSpendings retrieves the user's spendings for the current and // the previous months in the specified currency. RetrieveSpendings(string, string) ([]UserSpendings, error) // ScoreBreakdown returns the score breakdown of the specific host. ScoreBreakdown(HostDBEntry) (HostScoreBreakdown, error) // SetAllowance sets the renter's allowance. SetAllowance(types.PublicKey, Allowance) error // SetEmailPreferences changes the email preferences. SetEmailPreferences(string, types.Currency) error // SetFilterMode sets the HostDB's filter mode. SetFilterMode(FilterMode, []types.PublicKey, []string) error // StartMaintenance switches the maintenance mode on and off. StartMaintenance(bool) error // UnlockSiacoins moves a part of the amount from "locked" to "available", // while the other part (fees and other spent funds) is "burned". UnlockSiacoins(string, float64, float64, uint64) error // UpdateBalance updates the balance information on the account. UpdateBalance(string, UserBalance) error // UpdateContract updates the contract with the new revision and spending // details. UpdateContract(types.FileContractRevision, []types.TransactionSignature, types.Currency, types.Currency, types.Currency) error // UpdateMetadata updates the file metadata in the database. UpdateMetadata(types.PublicKey, FileMetadata) error // UpdatePrices updates the pricing table in the database. UpdatePrices(Pricing) error // UpdateRenterSettings updates the renter's opt-in settings. UpdateRenterSettings(types.PublicKey, RenterSettings, types.PrivateKey, types.PrivateKey) error // UpdateSlab updates a file slab after a successful migration. UpdateSlab(types.PublicKey, Slab, bool) error // UpdateSpendings updates the user's spendings. UpdateSpendings(string, UserSpendings, int, int) error }
Manager implements the methods necessary to communicate with the hosts.
type MerkleTree ¶
type MerkleTree struct {
merkletree.Tree
}
MerkleTree wraps merkletree.Tree, changing some of the function definitions to assume sia-specific constants and return sia-specific types.
func NewTree ¶
func NewTree() *MerkleTree
NewTree returns a MerkleTree, which can be used for getting Merkle roots and Merkle proofs on data. See merkletree.Tree for more details.
func (*MerkleTree) PushObject ¶
func (t *MerkleTree) PushObject(obj types.EncoderTo)
PushObject encodes and adds the hash of the encoded object to the tree as a leaf.
func (*MerkleTree) Root ¶
func (t *MerkleTree) Root() (h types.Hash256)
Root is a redefinition of merkletree.Tree.Root, returning a types.Hash256 instead of a []byte.
type NetAddress ¶
type NetAddress string
A NetAddress contains the information needed to contact a peer.
func DecodeAnnouncement ¶
func DecodeAnnouncement(fullAnnouncement []byte) (na NetAddress, pk types.PublicKey, err error)
DecodeAnnouncement decodes announcement bytes into a host announcement, verifying the prefix and the signature.
func (NetAddress) Host ¶
func (na NetAddress) Host() string
Host removes the port from a NetAddress, returning just the host. If the address is not of the form "host:port" the empty string is returned. The port will still be returned for invalid NetAddresses (e.g. "unqualified:0" will return "unqualified"), but in general you should only call Host on valid addresses.
func (NetAddress) IsLocal ¶
func (na NetAddress) IsLocal() bool
IsLocal returns true if the input IP address belongs to a local address range such as 192.168.x.x or 127.x.x.x.
func (NetAddress) IsLoopback ¶
func (na NetAddress) IsLoopback() bool
IsLoopback returns true for IP addresses that are on the same machine.
func (NetAddress) IsStdValid ¶
func (na NetAddress) IsStdValid() error
IsStdValid returns an error if the NetAddress is invalid. A valid NetAddress is of the form "host:port", such that "host" is either a valid IPv4/IPv6 address or a valid hostname, and "port" is an integer in the range [1,65535]. Valid IPv4 addresses, IPv6 addresses, and hostnames are detailed in RFCs 791, 2460, and 952, respectively. Loopback addresses are allowed.
func (NetAddress) IsValid ¶
func (na NetAddress) IsValid() error
IsValid is an extension to IsStdValid that also forbids the loopback address.
NOTE: IsValid is being phased out in favor of allowing the loopback address but verifying through other means that the connection is not to yourself (which is the original reason that the loopback address was banned).
func (NetAddress) Port ¶
func (na NetAddress) Port() string
Port returns the NetAddress object's port number. If the address is not of the form "host:port" the empty string is returned. The port will still be returned for invalid NetAddresses (e.g. "localhost:0" will return "0"), but in general you should only call Port on valid addresses.
type PoolTransaction ¶ added in v0.11.0
type PoolTransaction struct { ID types.TransactionID `json:"id"` Raw types.Transaction `json:"raw"` Type string `json:"type"` Sent types.Currency `json:"sent"` Received types.Currency `json:"received"` Locked types.Currency `json:"locked"` }
A PoolTransaction summarizes the wallet-relevant data in a txpool transaction.
type Portal ¶
type Portal interface { // Close safely shuts down the portal. Close() error // GetAnnouncement returns the current portal announcement. GetAnnouncement() (string, uint64, error) // GetCredits retrieves the promotion data. GetCredits() CreditData // SetAnnouncement sets a new portal announcement. SetAnnouncement(string, uint64) error // SetCredits updates the promotion data. SetCredits(CreditData) }
Portal implements the portal server.
type Pricing ¶ added in v0.6.0
type Pricing struct { // FormContract is how much the satellite charges for // forming or renewing a single contract. FormContract Price `json:"formcontract"` // SaveMetadata is the fee for saving a single slab // metadata. SaveMetadata Price `json:"savemetadata"` // StoreMetadata is the fee for storing a single slab // metadata for one month. StoreMetadata Price `json:"storemetadata"` // StorePartialData is the fee for storing one MiB of // partial slab data for one month. StorePartialData Price `json:"storepartialdata"` // RetrieveMetadata is the fee for retrieving a single // slab metadata. RetrieveMetadata Price `json:"retrievemetadata"` // MigrateSlab is the fee for migrating a single slab. MigrateSlab Price `json:"migrateslab"` }
Pricing combines the individual prices.
var StaticPricing Pricing
StaticPricing keeps the current prices.
type Provider ¶
type Provider interface { // Close safely shuts down the provider. Close() error // PublicKey returns the provider's public key. PublicKey() types.PublicKey // SecretKey returns the provider's secret key. SecretKey() types.PrivateKey }
Provider implements the methods necessary to communicate with the renters.
type RPCError ¶
RPCError is the generic error transferred in an RPC.
func (*RPCError) DecodeFrom ¶
DecodeFrom implements types.DecoderFrom.
type RPCResponse ¶
type RPCResponse struct {
// contains filtered or unexported fields
}
RPCResponse if a helper type for encoding and decoding RPC response messages, which can represent either valid data or an error.
func (*RPCResponse) DecodeFrom ¶
func (resp *RPCResponse) DecodeFrom(d *types.Decoder)
DecodeFrom implements types.DecoderFrom.
func (*RPCResponse) EncodeTo ¶
func (resp *RPCResponse) EncodeTo(e *types.Encoder)
EncodeTo implements types.EncoderTo.
type RPCSession ¶
An RPCSession contains the state of an RPC session with a renter.
func (*RPCSession) ReadMessage ¶
func (s *RPCSession) ReadMessage(message RequestBody, maxLen uint64) error
readMessage reads an encrypted message from the renter.
func (*RPCSession) ReadRequest ¶
func (s *RPCSession) ReadRequest(req RequestBody, maxLen uint64) (types.Hash256, error)
ReadRequest reads an encrypted RPC request from the renter.
func (*RPCSession) ReadResponse ¶
func (s *RPCSession) ReadResponse(resp RequestBody, maxLen uint64) error
ReadResponse reads an encrypted RPC response from the renter.
func (*RPCSession) WriteError ¶
func (s *RPCSession) WriteError(err error) error
WriteError sends an error message to the renter.
func (*RPCSession) WriteMessage ¶
func (s *RPCSession) WriteMessage(message RequestBody) error
writeMessage sends an encrypted message to the renter.
func (*RPCSession) WriteResponse ¶
func (s *RPCSession) WriteResponse(resp RequestBody) error
WriteResponse sends an encrypted RPC responce to the renter.
type Renter ¶
type Renter struct { Allowance Allowance CurrentPeriod uint64 PublicKey types.PublicKey Email string // Link to the user account. Settings RenterSettings PrivateKey types.PrivateKey AccountKey types.PrivateKey }
Renter holds the data related to the specific renter.
func (*Renter) ContractEndHeight ¶
contractEndHeight returns the height at which the renter's contracts end.
type RenterContract ¶
type RenterContract struct { ID types.FileContractID HostPublicKey types.PublicKey RenterPublicKey types.PublicKey Transaction types.Transaction StartHeight uint64 EndHeight uint64 // RenterFunds is the amount remaining in the contract that the renter can // spend. RenterFunds types.Currency // The FileContract does not indicate what funds were spent on, so we have // to track the various costs manually. DownloadSpending types.Currency FundAccountSpending types.Currency MaintenanceSpending MaintenanceSpending StorageSpending types.Currency UploadSpending types.Currency // Utility contains utility information about the renter. Utility ContractUtility // TotalCost indicates the amount of money that the renter spent and/or // locked up while forming a contract. This includes fees, and includes // funds which were allocated (but not necessarily committed) to spend on // uploads/downloads/storage. TotalCost types.Currency // ContractFee is the amount of money paid to the host to cover potential // future transaction fees that the host may incur, and to cover any other // overheads the host may have. // // TxnFee is the amount of money spent on the transaction fee when putting // the renter contract on the blockchain. // // SiafundFee is the amount of money spent on siafund fees when creating the // contract. The siafund fee that the renter pays covers both the renter and // the host portions of the contract, and therefore can be unexpectedly high // if the the host collateral is high. ContractFee types.Currency TxnFee types.Currency SiafundFee types.Currency // Imported indicates if the contract was imported via RPCShareContracts. Imported bool // Unlocked indicates if the contract payout has been unlocked. Unlocked bool }
A RenterContract contains metadata about a file contract. It is read-only; modifying a RenterContract does not modify the actual file contract.
func (*RenterContract) Size ¶
func (rc *RenterContract) Size() uint64
Size returns the contract size.
type RenterSettings ¶
type RenterSettings struct { AutoRenewContracts bool `json:"autorenew"` BackupFileMetadata bool `json:"backupmetadata"` AutoRepairFiles bool `json:"autorepair"` ProxyUploads bool `json:"proxyuploads"` }
RenterSettings keep the opt-in settings of the renter.
type RenterSpending ¶
type RenterSpending struct { // ContractFees are the sum of all fees in the contract. This means it // includes the ContractFee, TxnFee and SiafundFee ContractFees types.Currency // DownloadSpending is the money currently spent on downloads. DownloadSpending types.Currency // FundAccountSpending is the money used to fund an ephemeral account on the // host. FundAccountSpending types.Currency // MaintenanceSpending is the money spent on maintenance tasks in support of // the RHP3 protocol, this includes updating the price table as well as // syncing the ephemeral account balance. MaintenanceSpending MaintenanceSpending // StorageSpending is the money currently spent on storage. StorageSpending types.Currency // ContractSpending is the total amount of money that the renter has put // into contracts, whether it's locked and the renter gets that money // back or whether it's spent and the renter won't get the money back. TotalAllocated types.Currency // UploadSpending is the money currently spent on uploads. UploadSpending types.Currency // Unspent is locked-away, unspent money. Unspent types.Currency // WithheldFunds are the funds from the previous period that are tied up // in contracts and have not been released yet WithheldFunds types.Currency // ReleaseBlock is the block at which the WithheldFunds should be // released to the renter, based on worst case. // Contract End Height + Host Window Size + Maturity Delay ReleaseBlock uint64 // PreviousSpending is the total spend funds from old contracts // that are not included in the current period spending PreviousSpending types.Currency }
RenterSpending contains the metrics about how much the renter has spent during the current billing period.
func (RenterSpending) SpendingBreakdown ¶
func (rs RenterSpending) SpendingBreakdown() (totalSpent, unspentAllocated, unspentUnallocated types.Currency)
SpendingBreakdown provides a breakdown of a few fields in the RenterSpending.
type RequestBody ¶
RequestBody is the common interface type for the renter requests.
type Shard ¶
Shard represents an individual shard.
func (*Shard) DecodeFrom ¶
DecodeFrom implements types.ProtocolObject.
type Slab ¶
type Slab struct { Key types.Hash256 `json:"key"` MinShards uint8 `json:"minShards"` Offset uint64 `json:"offset"` Length uint64 `json:"length"` Partial bool `json:"partial"` Shards []Shard `json:"shards"` }
Slab is a collection of shards.
func (*Slab) DecodeFrom ¶
DecodeFrom implements types.ProtocolObject.
type SpendingDetails ¶
type SpendingDetails struct { DownloadSpending types.Currency FundAccountSpending types.Currency MaintenanceSpending MaintenanceSpending StorageSpending types.Currency UploadSpending types.Currency }
SpendingDetails is a helper struct that contains a breakdown of where exactly the money was spent. The MaintenanceSpending field is an aggregate of costs spent on RHP3 maintenance, this includes updating the price table, syncing the account balance, etc.
type Syncer ¶ added in v0.11.0
type Syncer interface { // Addr returns the address of the Syncer. Addr() string // BroadcastHeader broadcasts a header to all peers. BroadcastHeader(h gateway.BlockHeader) // BroadcastTransactionSet broadcasts a transaction set to all peers. BroadcastTransactionSet(txns []types.Transaction) // BroadcastV2BlockOutline broadcasts a v2 block outline to all peers. BroadcastV2BlockOutline(b gateway.V2BlockOutline) // BroadcastV2TransactionSet broadcasts a v2 transaction set to all peers. BroadcastV2TransactionSet(index types.ChainIndex, txns []types.V2Transaction) // Close shuts down the Syncer. Close() error // Connect forms an outbound connection to a peer. Connect(ctx context.Context, addr string) (*syncer.Peer, error) // PeerInfo returns the information about the current peers. PeerInfo() []syncer.PeerInfo // Peers returns the set of currently-connected peers. Peers() []*syncer.Peer // Synced returns if the syncer is synced to the blockchain. Synced() bool }
A Syncer synchronizes blockchain data with peers.
type UserBalance ¶
type UserBalance struct { Email string `json:"email"` IsUser bool `json:"isuser"` IsRenter bool `json:"isrenter"` Subscribed bool `json:"subscribed"` Balance float64 `json:"balance"` Locked float64 `json:"locked"` Currency string `json:"currency"` SCRate float64 `json:"scrate"` StripeID string `json:"stripeid"` Invoice string `json:"-"` OnHold uint64 `json:"-"` }
UserBalance holds the current balance as well as the data on the chosen payment scheme.
type UserSpendings ¶
type UserSpendings struct { Locked float64 `json:"locked"` Used float64 `json:"used"` Overhead float64 `json:"overhead"` SCRate float64 `json:"scrate"` Formed uint64 `json:"formed"` Renewed uint64 `json:"renewed"` SlabsSaved uint64 `json:"slabssaved"` SlabsRetrieved uint64 `json:"slabsretrieved"` SlabsMigrated uint64 `json:"slabsmigrated"` }
UserSpendings contains the spendings in the current and the previous months.
type Wallet ¶
type Wallet interface { // AddressBalance returns the balance of the given address. AddressBalance(addr types.Address) (siacoins types.Currency, siafunds uint64) // Addresses returns the addresses of the wallet. Addresses() (addrs []types.Address) // AddWatch adds the given watched address to the wallet. AddWatch(addr types.Address) error // Annotate annotates a transaction set. Annotate(txns []types.Transaction) (ptxns []PoolTransaction) // Close shuts down the wallet. Close() error // ConfirmedBalance returns the total balance of the wallet. ConfirmedBalance() (siacoins, immatureSiacoins types.Currency, siafunds uint64) // Fund adds Siacoin inputs with the required amount to the transaction. Fund(txn *types.Transaction, amount types.Currency) (parents []types.Transaction, toSign []types.Hash256, err error) // MarkAddressUnused marks the provided address as unused which causes it to be // handed out by a subsequent call to `NextAddresses` again. MarkAddressUnused(addrs ...types.UnlockConditions) error // MarkWalletInputs scans a transaction and infers which inputs belong to this // wallet. This allows those inputs to be signed. MarkWalletInputs(txn types.Transaction) (toSign []types.Hash256) // NextAddress returns an unlock hash that is ready to receive Siacoins or // Siafunds. NextAddress() (types.UnlockConditions, error) // Release marks the outputs as unused. Release(txnSet []types.Transaction) // RemoveWatch removes the given watched address from the wallet. RemoveWatch(addr types.Address) error // Reserve reserves the given ids for the given duration. Reserve(ids []types.Hash256, duration time.Duration) error // RenterSeed derives a renter seed. RenterSeed(email string) []byte // SendSiacoins creates a transaction sending 'amount' to 'dest'. The // transaction is submitted to the transaction pool and is also returned. Fees // are added to the amount sent. SendSiacoins(amount types.Currency, dest types.Address) ([]types.Transaction, error) // Sign signs the specified transaction using keys derived from the wallet seed. Sign(cs consensus.State, txn *types.Transaction, toSign []types.Hash256) error // Tip returns the wallet's internal processed chain index. Tip() types.ChainIndex // UnconfirmedBalance returns the balance of the wallet contained in // the unconfirmed transactions. UnconfirmedBalance() (outgoing, incoming types.Currency) // UnspentSiacoinOutputs returns the unspent SC outputs of the wallet. UnspentSiacoinOutputs() (sces []types.SiacoinElement) // UnspentSiafundOutputs returns the unspent SF outputs of the wallet. UnspentSiafundOutputs() (sfes []types.SiafundElement) // WatchedAddresses returns a list of the addresses watched by the wallet. WatchedAddresses() (addrs []types.Address) }
Wallet stores and manages Siacoins.