modules

package
v0.5.2-beta Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2016 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// GatewayDir is the name of the directory used to store the gateway's
	// persistent data.
	GatewayDir = "gateway"
	// WellConnectedThreshold is the number of outbound connections at which the
	// gateway will not attempt to make new outbound connections.
	WellConnectedThreshold = 8
)
View Source
const (
	// AcceptResponse defines the response that is sent to a successful RPC.
	AcceptResponse = "accept"

	// HostDir names the directory that contains the host persistence.
	HostDir = "host"

	// MaxFileContractSetLen determines the maximum allowed size of a
	// transaction set that can be sent when trying to negotiate a file
	// contract. The transaction set will contain all of the unconfirmed
	// dependencies of the file contract, meaning that it can be quite large.
	// The transaction pool's size limit for transaction sets has been chosen
	// as a reasonable guideline for determining what is too large.
	MaxFileContractSetLen = TransactionSetSizeLimit - 1e3
)
View Source
const (
	// TransactionSizeLimit defines the size of the largest transaction that
	// will be accepted by the transaction pool according to the IsStandard
	// rules.
	TransactionSizeLimit = 16e3

	// TransactionSetSizeLimit defines the largest set of dependent unconfirmed
	// transactions that will be accepted by the transaction pool.
	TransactionSetSizeLimit = 250e3
)
View Source
const (
	// WalletDir is the directory that contains the wallet persistance.
	WalletDir = "wallet"

	// SeedChecksumSize is the number of bytes that are used to checksum
	// addresses to prevent accidental spending.
	SeedChecksumSize = 6

	// PublicKeysPerSeed define the number of public keys that get pregenerated
	// for a seed at startup when searching for balances in the blockchain.
	PublicKeysPerSeed = 2500

	// WalletSeedPreloadDepth is the number of addresses that get automatically
	// loaded by the wallet at startup.
	WalletSeedPreloadDepth = 25
)
View Source
const (
	// ExplorerDir is the name of the directory that is typically used for the
	// explorer.
	ExplorerDir = "explorer"
)
View Source
const (
	// MinerDir is the name of the directory that is used to store the miner's
	// persistent data.
	MinerDir = "miner"
)
View Source
const (
	// RenterDir is the name of the directory that is used to store the
	// renter's persistent data.
	RenterDir = "renter"
)

Variables

View Source
var (
	// ErrBlockKnown is an error indicating that a block is already in the
	// database.
	ErrBlockKnown = errors.New("block already present in database")

	// ErrBlockUnsolved indicates that a block did not meet the required POW
	// target.
	ErrBlockUnsolved = errors.New("block does not meet target")

	// ErrInvalidConsensusChangeID indicates that ConsensusSetPersistSubscribe
	// was called with a consensus change id that is not recognized. Most
	// commonly, this means that the consensus set was deleted or replaced and
	// now the module attempting the subscription has desynchonized. This error
	// should be handled by the module, and not reported to the user.
	ErrInvalidConsensusChangeID = errors.New("consensus subscription has invalid id - files are inconsistent")

	// ErrNonExtendingBlock indicates that a block is valid but does not result
	// in a fork that is the heaviest known fork - the consensus set has not
	// changed as a result of seeing the block.
	ErrNonExtendingBlock = errors.New("block does not extend the longest fork")
)
View Source
var (
	// RPCSettings is the specifier for requesting settings from the host.
	RPCSettings = types.Specifier{'S', 'e', 't', 't', 'i', 'n', 'g', 's'}

	// RPCUpload is the specifier for initiating an upload with the host.
	RPCUpload = types.Specifier{'U', 'p', 'l', 'o', 'a', 'd'}

	// RPCRenew is the specifier to renewing an existing contract.
	RPCRenew = types.Specifier{'R', 'e', 'n', 'e', 'w'}

	// RPCRevise is the specifier for revising an existing file contract.
	RPCRevise = types.Specifier{'R', 'e', 'v', 'i', 's', 'e'}

	// RPCDownload is the specifier for downloading a file from a host.
	RPCDownload = types.Specifier{'D', 'o', 'w', 'n', 'l', 'o', 'a', 'd'}

	// PrefixHostAnnouncement is used to indicate that a transaction's
	// Arbitrary Data field contains a host announcement. The encoded
	// announcement will follow this prefix.
	PrefixHostAnnouncement = types.Specifier{'H', 'o', 's', 't', 'A', 'n', 'n', 'o', 'u', 'n', 'c', 'e', 'm', 'e', 'n', 't'}
)
View Source
var (
	// LogSettings is the recommended settings for logging. This value is
	// DEPRECATED. Instead, the persist.Logger should be used.
	LogSettings = log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile

	// SafeMutexDelay is the recommended timeout for the deadlock detecting
	// mutex. This value is DEPRECATED, as safe mutexes are no longer
	// recommended. Instead, the locking conventions should be followed and a
	// traditional mutex or a demote mutex should be used.
	SafeMutexDelay time.Duration
)
View Source
var (
	// ErrDuplicateTransactionSet is the error that gets returned if a
	// duplicate transaction set is given to the transaction pool.
	ErrDuplicateTransactionSet = errors.New("transaction is a duplicate")

	// ErrLargeTransaction is the error that gets returned if a transaction
	// provided to the transaction pool is larger than what is allowed by the
	// IsStandard rules.
	ErrLargeTransaction = errors.New("transaction is too large for this transaction pool")

	// ErrLargeTransactionSet is the error that gets returned if a transaction
	// set is given to the transaction pool if the transaction is larger than
	// limit placed by the IsStandard rules of the transaction pool.
	ErrLargeTransactionSet = errors.New("transaction set is too large for this transaction pool")

	// ErrInvalidArbPrefix is the error that gets returned if a transaction is
	// submitted to the transaction pool which contains a prefix that is not
	// recognized. This helps prevent miners on old versions from mining
	// potentially illegal transactions in the event of a soft-fork.
	ErrInvalidArbPrefix = errors.New("transaction contains non-standard arbitrary data")

	// PrefixNonSia defines the prefix that should be appended to any
	// transactions that use the arbitrary data for reasons outside of the
	// standard Sia protocol. This will prevent these transactions from being
	// rejected by the IsStandard set of rules, but also means that the data
	// will never be used within the formal Sia protocol.
	PrefixNonSia = types.Specifier{'N', 'o', 'n', 'S', 'i', 'a'}

	// TransactionPoolDir is the name of the directory that is used to store
	// the transaction pool's persistent data.
	TransactionPoolDir = "transactionpool"
)
View Source
var (
	// ErrBadEncryptionKey is returned if the incorrect encryption key to a
	// file is provided.
	ErrBadEncryptionKey = errors.New("provided encryption key is incorrect")

	// ErrLowBalance is returned if the wallet does not have enough funds to
	// complete the desired action.
	ErrLowBalance = errors.New("insufficient balance")

	// ErrPotentialDoubleSpend is returned when the wallet is uncertain whether
	// a spend is going to be legal or not.
	ErrPotentialDoubleSpend = errors.New("wallet has coins spent in unconfirmed transactions - not enough remaining coins to complete transaction")

	// ErrLockedWallet is returned when an action cannot be performed due to
	// the wallet being locked.
	ErrLockedWallet = errors.New("wallet must be unlocked before it can be used")
)
View Source
var (
	// BootstrapPeers is a list of peers that can be used to find other peers -
	// when a client first connects to the network, the only options for
	// finding peers are either manual entry of peers or to use a hardcoded
	// bootstrap point. While the bootstrap point could be a central service,
	// it can also be a list of peers that are known to be stable. We have
	// chosen to hardcode known-stable peers.
	BootstrapPeers = []NetAddress{
		"23.239.14.98:9981",
		"87.98.216.46:9981",
		"45.79.132.35:9981",
		"68.55.10.144:9981",
		"109.206.33.225:9981",
		"79.51.183.132:9981",
		"176.9.59.110:9981",
	}
)

TODO: Move this and it's functionality into the gateway package.

Functions

func SeedToString added in v1.0.0

func SeedToString(seed Seed, did mnemonics.DictionaryID) (string, error)

SeedToString converts a wallet seed to a human friendly string.

func StoragePriceToConsensus

func StoragePriceToConsensus(siacoinsMonthTB uint64) (hastingsBlockByte types.Currency)

StoragePriceToConsensus converts a human storage price, having the unit 'Siacoins Per Month Per Terabyte', to a consensus storage price, having the unit 'Hastings Per Block Per Byte'.

func StoragePriceToHuman

func StoragePriceToHuman(hastingsBlockByte types.Currency) (siacoinsMonthTB uint64, err error)

StoragePriceToHuman converts a consensus storage price, having the unit 'Hastings Per Block Per Byte', to a human storage price, having the unit 'Siacoins Per Month Per Terabyte'. An error is returned if the result would overflow a uint64. If the result is between 0 and 1, the value is rounded to the nearest value.

Types

type BlockFacts added in v1.0.0

type BlockFacts struct {
	BlockID           types.BlockID     `json:"blockid"`
	Difficulty        types.Currency    `json:"difficulty"`
	EstimatedHashrate types.Currency    `json:"estimatedhashrate"`
	Height            types.BlockHeight `json:"height"`
	MaturityTimestamp types.Timestamp   `json:"maturitytimestamp"`
	Target            types.Target      `json:"target"`
	TotalCoins        types.Currency    `json:"totalcoins"`

	// Transaction type counts.
	MinerPayoutCount          uint64 `json:"minerpayoutcount"`
	TransactionCount          uint64 `json:"transactioncount"`
	SiacoinInputCount         uint64 `json:"siacoininputcount"`
	SiacoinOutputCount        uint64 `json:"siacoinoutputcount"`
	FileContractCount         uint64 `json:"filecontractcount"`
	FileContractRevisionCount uint64 `json:"filecontractrevisioncount"`
	StorageProofCount         uint64 `json:"storageproofcount"`
	SiafundInputCount         uint64 `json:"siafundinputcount"`
	SiafundOutputCount        uint64 `json:"siafundoutputcount"`
	MinerFeeCount             uint64 `json:"minerfeecount"`
	ArbitraryDataCount        uint64 `json:"arbitrarydatacount"`
	TransactionSignatureCount uint64 `json:"transactionsignaturecount"`

	// Factoids about file contracts.
	ActiveContractCost  types.Currency `json:"activecontractcost"`
	ActiveContractCount uint64         `json:"activecontractcount"`
	ActiveContractSize  types.Currency `json:"activecontractsize"`
	TotalContractCost   types.Currency `json:"totalcontractcost"`
	TotalContractSize   types.Currency `json:"totalcontractsize"`
	TotalRevisionVolume types.Currency `json:"totalrevisionvolume"`
}

BlockFacts returns a bunch of statistics about the consensus set as they were at a specific block.

type BlockManager added in v1.0.0

type BlockManager interface {
	// HeaderForWork returns a block header that can be grinded on and
	// resubmitted to the miner. HeaderForWork() will remember the block that
	// corresponds to the header for 50 calls.
	HeaderForWork() (types.BlockHeader, types.Target, error)

	// SubmitHeader takes a block header that has been worked on and has a
	// valid target.
	SubmitHeader(types.BlockHeader) error

	// BlocksMined returns the number of blocks and stale blocks that have been
	// mined using this miner.
	BlocksMined() (goodBlocks, staleBlocks int)
}

BlockManager contains functions that can interface with external miners, providing and receiving blocks that have experienced nonce grinding.

type CPUMiner added in v1.0.0

type CPUMiner interface {
	// CPUHashrate returns the hashrate of the cpu miner in hashes per second.
	CPUHashrate() int

	// Mining returns true if the cpu miner is enabled, and false otherwise.
	CPUMining() bool

	// StartMining turns on the miner, which will endlessly work for new
	// blocks.
	StartCPUMining()

	// StopMining turns off the miner, but keeps the same number of threads.
	StopCPUMining()
}

CPUMiner provides access to a single-threaded cpu miner.

type ConsensusChange added in v0.3.3

type ConsensusChange struct {
	// ID is a unique id for the consensus change derived from the reverted
	// and applied blocks.
	ID ConsensusChangeID

	// RevertedBlocks is the list of blocks that were reverted by the change.
	// The reverted blocks were always all reverted before the applied blocks
	// were applied. The revered blocks are presented in the order that they
	// were reverted.
	RevertedBlocks []types.Block

	// AppliedBlocks is the list of blocks that were applied by the change. The
	// applied blocks are always all applied after all the reverted blocks were
	// reverted. The applied blocks are presented in the order that they were
	// applied.
	AppliedBlocks []types.Block

	// SiacoinOutputDiffs contains the set of siacoin diffs that were applied
	// to the consensus set in the recent change. The direction for the set of
	// diffs is 'DiffApply'.
	SiacoinOutputDiffs []SiacoinOutputDiff

	// FileContractDiffs contains the set of file contract diffs that were
	// applied to the consensus set in the recent change. The direction for the
	// set of diffs is 'DiffApply'.
	FileContractDiffs []FileContractDiff

	// SiafundOutputDiffs contains the set of siafund diffs that were applied
	// to the consensus set in the recent change. The direction for the set of
	// diffs is 'DiffApply'.
	SiafundOutputDiffs []SiafundOutputDiff

	// DelayedSiacoinOutputDiffs contains the set of delayed siacoin output
	// diffs that were applied to the consensus set in the recent change.
	DelayedSiacoinOutputDiffs []DelayedSiacoinOutputDiff

	// SiafundPoolDiffs are the siafund pool diffs that were applied to the
	// consensus set in the recent change.
	SiafundPoolDiffs []SiafundPoolDiff
}

A ConsensusChange enumerates a set of changes that occured to the consensus set.

func (ConsensusChange) Append added in v1.0.0

Append takes to ConsensusChange objects and adds all of their diffs together.

NOTE: It is possible for diffs to overlap or be inconsistent. This function should only be used with consecutive or disjoint consensus change objects.

type ConsensusChangeID added in v1.0.0

type ConsensusChangeID crypto.Hash

ConsensusChangeID is the id of a consensus change.

type ConsensusConflict added in v1.0.0

type ConsensusConflict string

ConsensusConflict implements the error interface, and indicates that a transaction was rejected due to being incompatible with the current consensus set, meaning either a double spend or a consensus rule violation - it is unlikely that the transaction will ever be valid.

func NewConsensusConflict added in v1.0.0

func NewConsensusConflict(s string) ConsensusConflict

NewConsensusConflict returns a consensus conflict, which implements the error interface.

func (ConsensusConflict) Error added in v1.0.0

func (cc ConsensusConflict) Error() string

Error implements the error interface, turning the consensus conflict into an acceptable error type.

type ConsensusSet added in v0.3.2

type ConsensusSet interface {
	// AcceptBlock adds a block to consensus. An error will be returned if the
	// block is invalid, has been seen before, is an orphan, or doesn't
	// contribute to the heaviest fork known to the consensus set. If the block
	// does not become the head of the heaviest known fork but is otherwise
	// valid, it will be remembered by the consensus set but an error will
	// still be returned.
	AcceptBlock(types.Block) error

	// BlockAtHeight returns the block found at the input height, with a
	// bool to indicate whether that block exists.
	BlockAtHeight(types.BlockHeight) (types.Block, bool)

	// ChildTarget returns the target required to extend the current heaviest
	// fork. This function is typically used by miners looking to extend the
	// heaviest fork.
	ChildTarget(types.BlockID) (types.Target, bool)

	// Close will shut down the consensus set, giving the module enough time to
	// run any required closing routines.
	Close() error

	// ConsensusSetPersistentSubscribe adds a subscriber to the list of
	// subscribers, and gives them every consensus change that has occured
	// since the change with the provided id.
	ConsensusSetPersistentSubscribe(ConsensusSetSubscriber, ConsensusChangeID) error

	// CurrentBlock returns the latest block in the heaviest known
	// blockchain.
	CurrentBlock() types.Block

	// Height returns the current height of consensus.
	Height() types.BlockHeight

	// Synced returns true if the consensus set is synced with the network.
	Synced() bool

	// InCurrentPath returns true if the block id presented is found in the
	// current path, false otherwise.
	InCurrentPath(types.BlockID) bool

	// MinimumValidChildTimestamp returns the earliest timestamp that is
	// valid on the current longest fork according to the consensus set. This is
	// a required piece of information for the miner, who could otherwise be at
	// risk of mining invalid blocks.
	MinimumValidChildTimestamp(types.BlockID) (types.Timestamp, bool)

	// StorageProofSegment returns the segment to be used in the storage proof for
	// a given file contract.
	StorageProofSegment(types.FileContractID) (uint64, error)

	// TryTransactionSet checks whether the transaction set would be valid if
	// it were added in the next block. A consensus change is returned
	// detailing the diffs that would result from the application of the
	// transaction.
	TryTransactionSet([]types.Transaction) (ConsensusChange, error)

	// Unsubscribe removes a subscriber from the list of subscribers,
	// allowing for garbage collection and rescanning. If the subscriber is
	// not found in the subscriber database, no action is taken.
	Unsubscribe(ConsensusSetSubscriber)
}

A ConsensusSet accepts blocks and builds an understanding of network consensus.

type ConsensusSetSubscriber added in v0.3.2

type ConsensusSetSubscriber interface {
	// ProcessConsensusChange sends a consensus update to a module through
	// a function call. Updates will always be sent in the correct order.
	// There may not be any reverted blocks, but there will always be
	// applied blocks.
	ProcessConsensusChange(ConsensusChange)
}

A ConsensusSetSubscriber is an object that receives updates to the consensus set every time there is a change in consensus.

type DelayedSiacoinOutputDiff added in v0.3.3

type DelayedSiacoinOutputDiff struct {
	Direction      DiffDirection
	ID             types.SiacoinOutputID
	SiacoinOutput  types.SiacoinOutput
	MaturityHeight types.BlockHeight
}

A DelayedSiacoinOutputDiff indicates the introduction of a siacoin output that cannot be spent until after maturing for 144 blocks. When the output has matured, a SiacoinOutputDiff will be provided.

type DiffDirection added in v0.3.1

type DiffDirection bool

A DiffDirection indicates the "direction" of a diff, either applied or reverted. A bool is used to restrict the value to these two possibilities.

const (
	// ConsensusDir is the name of the directory used for all of the consensus
	// persistence files.
	ConsensusDir = "consensus"

	// DiffApply indicates that a diff is being applied to the consensus set.
	DiffApply DiffDirection = true

	// DiffRevert indicates that a diff is being reverted from the consensus
	// set.
	DiffRevert DiffDirection = false
)

type DownloadInfo

type DownloadInfo struct {
	SiaPath     string    `json:"siapath"`
	Destination string    `json:"destination"`
	Filesize    uint64    `json:"filesize"`
	Received    uint64    `json:"received"`
	StartTime   time.Time `json:"starttime"`
}

DownloadInfo provides information about a file that has been requested for download.

type DownloadRequest

type DownloadRequest struct {
	Offset uint64
	Length uint64
}

A DownloadRequest is used to retrieve a particular segment of a file from a host.

type EncryptionManager added in v1.0.0

type EncryptionManager interface {
	// Encrypt will encrypt the wallet using the input key. Upon
	// encryption, a primary seed will be created for the wallet (no seed
	// exists prior to this point). If the key is blank, then the hash of
	// the seed that is generated will be used as the key.
	//
	// Encrypt can only be called once throughout the life of the wallet,
	// and will return an error on subsequent calls (even after restarting
	// the wallet). To reset the wallet, the wallet files must be moved to
	// a different directory or deleted.
	Encrypt(masterKey crypto.TwofishKey) (Seed, error)

	// Encrypted returns whether or not the wallet has been encrypted yet.
	// After being encrypted for the first time, the wallet can only be
	// unlocked using the encryption password.
	Encrypted() bool

	// Lock deletes all keys in memory and prevents the wallet from being
	// used to spend coins or extract keys until 'Unlock' is called.
	Lock() error

	// Unlock must be called before the wallet is usable. All wallets and
	// wallet seeds are encrypted by default, and the wallet will not know
	// which addresses to watch for on the blockchain until unlock has been
	// called.
	//
	// All items in the wallet are encrypted using different keys which are
	// derived from the master key.
	Unlock(masterKey crypto.TwofishKey) error

	// Unlocked returns true if the wallet is currently unlocked, false
	// otherwise.
	Unlocked() bool
}

EncryptionManager can encrypt, lock, unlock, and indicate the current status of the EncryptionManager.

type ErasureCoder added in v1.0.0

type ErasureCoder interface {
	// NumPieces is the number of pieces returned by Encode.
	NumPieces() int

	// MinPieces is the minimum number of pieces that must be present to
	// recover the original data.
	MinPieces() int

	// Encode splits data into equal-length pieces, with some pieces
	// containing parity data.
	Encode(data []byte) ([][]byte, error)

	// Recover recovers the original data from pieces (including parity) and
	// writes it to w. pieces should be identical to the slice returned by
	// Encode (length and order must be preserved), but with missing elements
	// set to nil. n is the number of bytes to be written to w; this is
	// necessary because pieces may have been padded with zeros during
	// encoding.
	Recover(pieces [][]byte, n uint64, w io.Writer) error
}

An ErasureCoder is an error-correcting encoder and decoder.

type Explorer added in v1.0.0

type Explorer interface {
	// Block returns the block that matches the input block id. The bool
	// indicates whether the block appears in the blockchain.
	Block(types.BlockID) (types.Block, types.BlockHeight, bool)

	// BlockFacts returns a set of statistics about the blockchain as they
	// appeared at a given block.
	BlockFacts(types.BlockHeight) (BlockFacts, bool)

	// Transaction returns the block that contains the input transaction
	// id. The transaction itself is either the block (indicating the miner
	// payouts are somehow involved), or it is a transaction inside of the
	// block. The bool indicates whether the transaction is found in the
	// consensus set.
	Transaction(types.TransactionID) (types.Block, types.BlockHeight, bool)

	// UnlockHash returns all of the transaction ids associated with the
	// provided unlock hash.
	UnlockHash(types.UnlockHash) []types.TransactionID

	// SiacoinOutput will return the siacoin output associated with the
	// input id.
	SiacoinOutput(types.SiacoinOutputID) (types.SiacoinOutput, bool)

	// SiacoinOutputID returns all of the transaction ids associated with
	// the provided siacoin output id.
	SiacoinOutputID(types.SiacoinOutputID) []types.TransactionID

	// FileContractHistory returns the history associated with a file
	// contract, which includes the file contract itself and all of the
	// revisions that have been submitted to the blockchain. The first bool
	// indicates whether the file contract exists, and the second bool
	// indicates whether a storage proof was successfully submitted for the
	// file contract.
	FileContractHistory(types.FileContractID) (fc types.FileContract, fcrs []types.FileContractRevision, fcExists bool, storageProofExists bool)

	// FileContractID returns all of the transaction ids associated with
	// the provided file contract id.
	FileContractID(types.FileContractID) []types.TransactionID

	// SiafundOutput will return the siafund output associated with the
	// input id.
	SiafundOutput(types.SiafundOutputID) (types.SiafundOutput, bool)

	// SiafundOutputID returns all of the transaction ids associated with
	// the provided siafund output id.
	SiafundOutputID(types.SiafundOutputID) []types.TransactionID

	Close() error
}

Explorer tracks the blockchain and provides tools for gathering statistics and finding objects or patterns within the blockchain.

type FileContractDiff added in v0.3.1

type FileContractDiff struct {
	Direction    DiffDirection
	ID           types.FileContractID
	FileContract types.FileContract
}

A FileContractDiff indicates the addition or removal of a FileContract in the consensus set.

type FileInfo

type FileInfo struct {
	SiaPath        string            `json:"siapath"`
	Filesize       uint64            `json:"filesize"`
	Available      bool              `json:"available"`
	Renewing       bool              `json:"renewing"`
	Redundancy     float64           `json:"redundancy"`
	UploadProgress float64           `json:"uploadprogress"`
	Expiration     types.BlockHeight `json:"expiration"`
}

FileInfo provides information about a file.

type FileUploadParams added in v0.3.1

type FileUploadParams struct {
	Source      string
	SiaPath     string
	Duration    types.BlockHeight
	Renew       bool
	ErasureCode ErasureCoder
	PieceSize   uint64
}

FileUploadParams contains the information used by the Renter to upload a file.

type Gateway

type Gateway interface {
	// Connect establishes a persistent connection to a peer.
	Connect(NetAddress) error

	// Disconnect terminates a connection to a peer.
	Disconnect(NetAddress) error

	// Address returns the Gateway's address.
	Address() NetAddress

	// Peers returns the addresses that the Gateway is currently connected to.
	Peers() []Peer

	// RegisterRPC registers a function to handle incoming connections that
	// supply the given RPC ID.
	RegisterRPC(string, RPCFunc)

	// RegisterConnectCall registers an RPC name and function to be called
	// upon connecting to a peer.
	RegisterConnectCall(string, RPCFunc)

	// RPC calls an RPC on the given address. RPC cannot be called on an
	// address that the Gateway is not connected to.
	RPC(NetAddress, string, RPCFunc) error

	// Broadcast transmits obj, prefaced by the RPC name, to all of the
	// given peers in parallel.
	Broadcast(name string, obj interface{}, peers []Peer)

	// Close safely stops the Gateway's listener process.
	Close() error
}

A Gateway facilitates the interactions between the local node and remote nodes (peers). It relays incoming blocks and transactions to local modules, and broadcasts outgoing blocks and transactions to peers. In a broad sense, it is responsible for ensuring that the local consensus set is consistent with the "network" consensus set.

type Host

type Host interface {
	// Announce submits a host announcement to the blockchain, returning an
	// error if its external IP address is unknown. After announcing, the
	// host will begin accepting contracts.
	Announce() error

	// AnnounceAddress behaves like Announce, but allows the caller to
	// specify the address announced. Like Announce, this will cause the
	// host to start accepting contracts.
	AnnounceAddress(NetAddress) error

	// Capacity returns the amount of storage still available on the
	// machine. The amount can be negative if the total capacity was
	// reduced to below the active capacity.
	Capacity() int64

	// Contracts returns the number of unresolved file contracts that the
	// host is responsible for.
	Contracts() uint64

	// DeleteContract deletes a file contract. The revenue and collateral
	// on the file contract will be lost, and the data will be removed.
	DeleteContract(types.FileContractID) error

	// NetAddress returns the host's network address
	NetAddress() NetAddress

	// Revenue returns the amount of revenue that the host has lined up,
	// the amount of revenue the host has successfully captured, and the
	// amount of revenue the host has lost.
	//
	// TODO: This function will eventually include two more numbers, one
	// representing current collateral at risk, and one representing total
	// collateral lost.
	Revenue() (unresolved, resolved, lost types.Currency)

	// RPCMetrics returns information on the types of RPC calls that have
	// been made to the host.
	RPCMetrics() HostRPCMetrics

	// SetConfig sets the hosting parameters of the host.
	SetSettings(HostSettings) error

	// Settings returns the host's settings.
	Settings() HostSettings

	// Close saves the state of the host and stops its listener process.
	Close() error
}

Host can take storage from disk and offer it to the network, managing things such as announcements, settings, and implementing all of the RPCs of the host protocol.

type HostAnnouncement

type HostAnnouncement struct {
	IPAddress NetAddress
}

HostAnnouncement declares a nodes intent to be a host, providing a net address that can be used to contact the host.

type HostRPCMetrics

type HostRPCMetrics struct {
	ErrorCalls        uint64 `json:"errorcalls"` // Calls that resulted in an error.
	UnrecognizedCalls uint64 `json:"unrecognizedcalls"`
	DownloadCalls     uint64 `json:"downloadcalls"`
	RenewCalls        uint64 `json:"renewcalls"`
	ReviseCalls       uint64 `json:"revisecalls"`
	SettingsCalls     uint64 `json:"settingscalls"`
	UploadCalls       uint64 `json:"uploadcalls"`
}

HostRPCMetrics reports the quantity of each type of RPC call that has been made to the host.

type HostSettings

type HostSettings struct {
	AcceptingContracts bool              `json:"acceptingcontracts"`
	NetAddress         NetAddress        `json:"netaddress"`
	TotalStorage       int64             `json:"totalstorage"`
	MinDuration        types.BlockHeight `json:"minduration"`
	MaxDuration        types.BlockHeight `json:"maxduration"`
	WindowSize         types.BlockHeight `json:"windowsize"`
	Price              types.Currency    `json:"price"`
	Collateral         types.Currency    `json:"collateral"`
	UnlockHash         types.UnlockHash  `json:"unlockhash"`
}

HostSettings are the parameters advertised by the host. These are the values that the renter will request from the host in order to build its database.

type KeyManager added in v1.0.0

type KeyManager interface {
	// AllAddresses returns all addresses that the wallet is able to spend
	// from, including unseeded addresses. Addresses are returned sorted in
	// byte-order.
	AllAddresses() []types.UnlockHash

	// AllSeeds returns all of the seeds that are being tracked by the
	// wallet, including the primary seed. Only the primary seed is used to
	// generate new addresses, but the wallet can spend funds sent to
	// public keys generated by any of the seeds returned.
	AllSeeds() ([]Seed, error)

	// PrimarySeed returns the current primary seed of the wallet,
	// unencrypted, with an int indicating how many addresses have been
	// consumed.
	PrimarySeed() (Seed, uint64, error)

	// NextAddress returns a new coin addresses generated from the
	// primary seed.
	NextAddress() (types.UnlockConditions, error)

	// CreateBackup will create a backup of the wallet at the provided
	// filepath. The backup will have all seeds and keys.
	CreateBackup(string) error

	// Load033xWallet will load a version 0.3.3.x wallet from disk and add all of
	// the keys in the wallet as unseeded keys.
	Load033xWallet(crypto.TwofishKey, string) error

	// LoadSeed will recreate a wallet file using the recovery phrase.
	// LoadSeed only needs to be called if the original seed file or
	// encryption password was lost. The master key is used encrypt the
	// recovery seed before saving it to disk.
	LoadSeed(crypto.TwofishKey, Seed) error

	// LoadSiagKeys will take a set of filepaths that point to a siag key
	// and will have the siag keys loaded into the wallet so that they will
	// become spendable.
	LoadSiagKeys(crypto.TwofishKey, []string) error
}

KeyManager manages wallet keys, including the use of seeds, creating and loading backups, and providing a layer of compatibility for older wallet files.

type Miner added in v0.3.1

type Miner interface {
	BlockManager
	CPUMiner
	io.Closer
}

The Miner interface provides access to mining features.

type NetAddress

type NetAddress string

A NetAddress contains the information needed to contact a peer.

func (NetAddress) Host

func (na NetAddress) Host() string

Host removes the port from a NetAddress, returning just the host. If the address is invalid, the empty string is returned.

func (NetAddress) IsLoopback added in v1.0.0

func (na NetAddress) IsLoopback() bool

IsLoopback returns true for ip addresses that are on the same machine.

func (NetAddress) IsValid added in v1.0.0

func (na NetAddress) IsValid() bool

IsValid does nothing. Please ignore it.

func (NetAddress) Port

func (na NetAddress) Port() string

Port returns the NetAddress object's port number. The empty string is returned if the NetAddress is invalid.

type Peer added in v1.0.0

type Peer struct {
	NetAddress NetAddress `json:"netaddress"`
	Version    string     `json:"version"`
	Inbound    bool       `json:"inbound"`
}

Peer contains all the info necessary to Broadcast to a peer.

type PeerConn added in v0.3.1

type PeerConn interface {
	net.Conn
}

A PeerConn is the connection type used when communicating with peers during an RPC. For now it is identical to a net.Conn.

type ProcessedInput added in v1.0.0

type ProcessedInput struct {
	FundType       types.Specifier  `json:"fundtype"`
	WalletAddress  bool             `json:"walletaddress"`
	RelatedAddress types.UnlockHash `json:"relatedaddress"`
	Value          types.Currency   `json:"value"`
}

A ProcessedInput represents funding to a transaction. The input is coming from an address and going to the outputs. The fund types are 'SiacoinInput', 'SiafundInput'.

type ProcessedOutput added in v1.0.0

type ProcessedOutput struct {
	FundType       types.Specifier   `json:"fundtype"`
	MaturityHeight types.BlockHeight `json:"maturityheight"`
	WalletAddress  bool              `json:"walletaddress"`
	RelatedAddress types.UnlockHash  `json:"relatedaddress"`
	Value          types.Currency    `json:"value"`
}

A ProcessedOutput is a siacoin output that appears in a transaction. Some outputs mature immediately, some are delayed, and some may never mature at all (in the event of storage proofs).

Fund type can either be 'SiacoinOutput', 'SiafundOutput', 'ClaimOutput', 'MinerPayout', or 'MinerFee'. All outputs except the miner fee create outputs accessible to an address. Miner fees are not spendable, and instead contribute to the block subsidy.

MaturityHeight indicates at what block height the output becomes available. SiacoinInputs and SiafundInputs become available immediately. ClaimInputs and MinerPayouts become available after 144 confirmations.

type ProcessedTransaction added in v1.0.0

type ProcessedTransaction struct {
	Transaction           types.Transaction   `json:"transaction"`
	TransactionID         types.TransactionID `json:"transactionid"`
	ConfirmationHeight    types.BlockHeight   `json:"confirmationheight"`
	ConfirmationTimestamp types.Timestamp     `json:"confirmationtimestamp"`

	Inputs  []ProcessedInput  `json:"inputs"`
	Outputs []ProcessedOutput `json:"outputs"`
}

A ProcessedTransaction is a transaction that has been processed into explicit inputs and outputs and tagged with some header data such as confirmation height + timestamp.

Because of the block subsidy, a block is considered as a transaction. Since there is technically no transaction id for the block subsidy, the block id is used instead.

type RPCFunc

type RPCFunc func(PeerConn) error

RPCFunc is the type signature of functions that handle RPCs. It is used for both the caller and the callee. RPCFuncs may perform locking. RPCFuncs may close the connection early, and it is recommended that they do so to avoid keeping the connection open after all necessary I/O has been performed.

type Renter

type Renter interface {
	// ActiveHosts returns the list of hosts that are actively being selected
	// from.
	ActiveHosts() []HostSettings

	// AllHosts returns the full list of hosts known to the renter.
	AllHosts() []HostSettings

	// DeleteFile deletes a file entry from the renter.
	DeleteFile(path string) error

	// Download downloads a file to the given destination.
	Download(path, destination string) error

	// DownloadQueue lists all the files that have been scheduled for download.
	DownloadQueue() []DownloadInfo

	// FileList returns information on all of the files stored by the renter.
	FileList() []FileInfo

	// LoadSharedFiles loads a '.sia' file into the renter. A .sia file may
	// contain multiple files. The paths of the added files are returned.
	LoadSharedFiles(source string) ([]string, error)

	// LoadSharedFilesAscii loads an ASCII-encoded '.sia' file into the
	// renter.
	LoadSharedFilesAscii(asciiSia string) ([]string, error)

	// Rename changes the path of a file.
	RenameFile(path, newPath string) error

	// ShareFiles creates a '.sia' file that can be shared with others.
	ShareFiles(paths []string, shareDest string) error

	// ShareFilesAscii creates an ASCII-encoded '.sia' file.
	ShareFilesAscii(paths []string) (asciiSia string, err error)

	// Upload uploads a file using the input parameters.
	Upload(FileUploadParams) error
}

A Renter uploads, tracks, repairs, and downloads a set of files for the user.

type Seed added in v1.0.0

type Seed [crypto.EntropySize]byte

Seed is cryptographic entropy that is used to derive spendable wallet addresses.

func StringToSeed added in v1.0.0

func StringToSeed(str string, did mnemonics.DictionaryID) (Seed, error)

StringToSeed converts a string to a wallet seed.

type SiacoinOutputDiff added in v0.3.1

type SiacoinOutputDiff struct {
	Direction     DiffDirection
	ID            types.SiacoinOutputID
	SiacoinOutput types.SiacoinOutput
}

A SiacoinOutputDiff indicates the addition or removal of a SiacoinOutput in the consensus set.

type SiafundOutputDiff added in v0.3.1

type SiafundOutputDiff struct {
	Direction     DiffDirection
	ID            types.SiafundOutputID
	SiafundOutput types.SiafundOutput
}

A SiafundOutputDiff indicates the addition or removal of a SiafundOutput in the consensus set.

type SiafundPoolDiff added in v0.3.1

type SiafundPoolDiff struct {
	Direction DiffDirection
	Previous  types.Currency
	Adjusted  types.Currency
}

A SiafundPoolDiff contains the value of the siafundPool before the block was applied, and after the block was applied. When applying the diff, set siafundPool to 'Adjusted'. When reverting the diff, set siafundPool to 'Previous'.

type TestMiner added in v1.0.0

type TestMiner interface {
	// AddBlock is an extension of FindBlock - AddBlock will submit the block
	// after finding it.
	AddBlock() (types.Block, error)

	// BlockForWork returns a block that is ready for nonce grinding. All
	// blocks returned by BlockForWork have a unique merkle root, meaning that
	// each can safely start from nonce 0.
	BlockForWork() (types.Block, types.Target, error)

	// FindBlock will have the miner make 1 attempt to find a solved block that
	// builds on the current consensus set. It will give up after a few
	// seconds, returning the block and a bool indicating whether the block is
	// sovled.
	FindBlock() (types.Block, error)

	// SolveBlock will have the miner make 1 attempt to solve the input block,
	// which amounts to trying a few thousand different nonces. SolveBlock is
	// primarily used for testing.
	SolveBlock(types.Block, types.Target) (types.Block, bool)
}

TestMiner provides direct acesss to block fetching, solving, and manipulation. The primary use of this interface is integration testing.

type TransactionBuilder added in v1.0.0

type TransactionBuilder interface {
	// FundSiacoins will add a siacoin input of exaclty 'amount' to the
	// transaction. A parent transaction may be needed to achieve an input
	// with the correct value. The siacoin input will not be signed until
	// 'Sign' is called on the transaction builder. The expectation is that
	// the transaction will be completed and broadcast within a few hours.
	// Longer risks double-spends, as the wallet will assume that the
	// transaction failed.
	FundSiacoins(amount types.Currency) error

	// FundSiafunds will add a siafund input of exaclty 'amount' to the
	// transaction. A parent transaction may be needed to achieve an input
	// with the correct value. The siafund input will not be signed until
	// 'Sign' is called on the transaction builder. Any siacoins that are
	// released by spending the siafund outputs will be sent to another
	// address owned by the wallet. The expectation is that the transaction
	// will be completed and broadcast within a few hours. Longer risks
	// double-spends, because the wallet will assume the transcation
	// failed.
	FundSiafunds(amount types.Currency) error

	// AddMinerFee adds a miner fee to the transaction, returning the index
	// of the miner fee within the transaction.
	AddMinerFee(fee types.Currency) uint64

	// AddSiacoinInput adds a siacoin input to the transaction, returning
	// the index of the siacoin input within the transaction. When 'Sign'
	// gets called, this input will be left unsigned.
	AddSiacoinInput(types.SiacoinInput) uint64

	// AddSiacoinOutput adds a siacoin output to the transaction, returning
	// the index of the siacoin output within the transaction.
	AddSiacoinOutput(types.SiacoinOutput) uint64

	// AddFileContract adds a file contract to the transaction, returning
	// the index of the file contract within the transaction.
	AddFileContract(types.FileContract) uint64

	// AddFileContractRevision adds a file contract revision to the
	// transaction, returning the index of the file contract revision
	// within the transaction. When 'Sign' gets called, this revision will
	// be left unsigned.
	AddFileContractRevision(types.FileContractRevision) uint64

	// AddStorageProof adds a storage proof to the transaction, returning
	// the index of the storage proof within the transaction.
	AddStorageProof(types.StorageProof) uint64

	// AddSiafundInput adds a siafund input to the transaction, returning
	// the index of the siafund input within the transaction. When 'Sign'
	// is called, this input will be left unsigned.
	AddSiafundInput(types.SiafundInput) uint64

	// AddSiafundOutput adds a siafund output to the transaction, returning
	// the index of the siafund output within the transaction.
	AddSiafundOutput(types.SiafundOutput) uint64

	// AddArbitraryData adds arbitrary data to the transaction, returning
	// the index of the data within the transaction.
	AddArbitraryData(arb []byte) uint64

	// AddTransactionSignature adds a transaction signature to the
	// transaction, returning the index of the signature within the
	// transaction. The signature should already be valid, and shouldn't
	// sign any of the inputs that were added by calling 'FundSiacoins' or
	// 'FundSiafunds'.
	AddTransactionSignature(types.TransactionSignature) uint64

	// Sign will sign any inputs added by 'FundSiacoins' or 'FundSiafunds'
	// and return a transaction set that contains all parents prepended to
	// the transaction. If more fields need to be added, a new transaction
	// builder will need to be created.
	//
	// If the whole transaction flag is set to true, then the whole
	// transaction flag will be set in the covered fields object. If the
	// whole transaction flag is set to false, then the covered fields
	// object will cover all fields that have already been added to the
	// transaction, but will also leave room for more fields to be added.
	Sign(wholeTransaction bool) ([]types.Transaction, error)

	// View returns the incomplete transaction along with all of its
	// parents.
	View() (txn types.Transaction, parents []types.Transaction)

	// Drop indicates that a transaction is no longer useful, will not be
	// broadcast, and that all of the outputs can be reclaimed. 'Drop'
	// should only be used before signatures are added.
	Drop()
}

TransactionBuilder is used to construct custom transactions. A transaction builder is intialized via 'RegisterTransaction' and then can be modified by adding funds or other fields. The transaction is completed by calling 'Sign', which will sign all inputs added via the 'FundSiacoins' or 'FundSiafunds' call. All modifications are additive.

Parents of the transaction are kept in the transaction builder. A parent is any unconfirmed transaction that is required for the child to be valid.

Transaction builders are not thread safe.

type TransactionPool

type TransactionPool interface {
	// AcceptTransactionSet accepts a set of potentially interdependent
	// transactions.
	AcceptTransactionSet([]types.Transaction) error

	// IsStandardTransaction returns `err = nil` if the transaction is
	// standard, otherwise it returns an error explaining what is not standard.
	IsStandardTransaction(types.Transaction) error

	// PurgeTransactionPool is a temporary function available to the miner. In
	// the event that a miner mines an unacceptable block, the transaction pool
	// will be purged to clear out the transaction pool and get rid of the
	// illegal transaction. This should never happen, however there are bugs
	// that make this condition necessary.
	PurgeTransactionPool()

	// TransactionList returns a list of all transactions in the transaction
	// pool. The transactions are provided in an order that can acceptably be
	// put into a block.
	TransactionList() []types.Transaction

	// TransactionPoolSubscribe adds a subscriber to the transaction pool.
	// Subscribers will receive all consensus set changes as well as
	// transaction pool changes, and should not subscribe to both.
	TransactionPoolSubscribe(TransactionPoolSubscriber)
}

A TransactionPool manages unconfirmed transactions.

type TransactionPoolSubscriber added in v0.3.1

type TransactionPoolSubscriber interface {
	// ReceiveTransactionPoolUpdate notifies subscribers of a change to the
	// consensus set and/or unconfirmed set, and includes the consensus change
	// that would result if all of the transactions made it into a block.
	ReceiveUpdatedUnconfirmedTransactions([]types.Transaction, ConsensusChange)
}

A TransactionPoolSubscriber receives updates about the confirmed and unconfirmed set from the transaction pool. Generally, there is no need to subscribe to both the consensus set and the transaction pool.

type Wallet

type Wallet interface {
	EncryptionManager
	KeyManager

	// ConfirmedBalance returns the confirmed balance of the wallet, minus
	// any outgoing transactions. ConfirmedBalance will include unconfirmed
	// refund transacitons.
	ConfirmedBalance() (siacoinBalance types.Currency, siafundBalance types.Currency, siacoinClaimBalance types.Currency)

	// UnconfirmedBalance returns the unconfirmed balance of the wallet.
	// Outgoing funds and incoming funds are reported separately. Refund
	// outputs are included, meaning that a sending a single coin to
	// someone could result in 'outgoing: 12, incoming: 11'. Siafunds are
	// not considered in the unconfirmed balance.
	UnconfirmedBalance() (outgoingSiacoins types.Currency, incomingSiacoins types.Currency)

	// AddressTransactions returns all of the transactions that are related
	// to a given address.
	AddressTransactions(types.UnlockHash) []ProcessedTransaction

	// AddressUnconfirmedHistory returns all of the unconfirmed
	// transactions related to a given address.
	AddressUnconfirmedTransactions(types.UnlockHash) []ProcessedTransaction

	// Transaction returns the transaction with the given id. The bool
	// indicates whether the transaction is in the wallet database. The
	// wallet only stores transactions that are related to the wallet.
	Transaction(types.TransactionID) (ProcessedTransaction, bool)

	// Transactions returns all of the transactions that were confirmed at
	// heights [startHeight, endHeight]. Unconfirmed transactions are not
	// included.
	Transactions(startHeight types.BlockHeight, endHeight types.BlockHeight) ([]ProcessedTransaction, error)

	// UnconfirmedTransactions returns all unconfirmed transactions
	// relative to the wallet.
	UnconfirmedTransactions() []ProcessedTransaction

	// RegisterTransaction takes a transaction and its parents and returns
	// a TransactionBuilder which can be used to expand the transaction.
	// The most typical call is 'RegisterTransaction(types.Transaction{},
	// nil)', which registers a new transaction without parents.
	RegisterTransaction(t types.Transaction, parents []types.Transaction) TransactionBuilder

	// StartTransaction is a convenience method that calls
	// RegisterTransaction(types.Transaction{}, nil)
	StartTransaction() TransactionBuilder

	// SendSiacoins is a tool for sending siacoins from the wallet to an
	// address. Sending money usually results in multiple transactions. The
	// transactions are automatically given to the transaction pool, and
	// are also returned to the caller.
	SendSiacoins(amount types.Currency, dest types.UnlockHash) ([]types.Transaction, error)

	// SendSiafunds is a tool for sending siafunds from the wallet to an
	// address. Sending money usually results in multiple transactions. The
	// transactions are automatically given to the transaction pool, and
	// are also returned to the caller.
	SendSiafunds(amount types.Currency, dest types.UnlockHash) ([]types.Transaction, error)
}

Wallet stores and manages siacoins and siafunds. The wallet file is encrypted using a user-specified password. Common addresses are all dervied from a single address seed.

type WalletTransactionID added in v1.0.0

type WalletTransactionID crypto.Hash

WalletTransactionID is a unique identifier for a wallet transaction.

func CalculateWalletTransactionID added in v1.0.0

func CalculateWalletTransactionID(tid types.TransactionID, oid types.OutputID) WalletTransactionID

CalculateWalletTransactionID is a helper function for determining the id of a wallet transaction.

Directories

Path Synopsis
The explorer module provides a glimpse into what the Sia network currently looks like.
The explorer module provides a glimpse into what the Sia network currently looks like.
Package host is an implementation of the host module, and is responsible for storing data and advertising available storage to the network.
Package host is an implementation of the host module, and is responsible for storing data and advertising available storage to the network.
hostdb
Package hostdb provides a HostDB object that implements the renter.hostDB interface.
Package hostdb provides a HostDB object that implements the renter.hostDB interface.

Jump to

Keyboard shortcuts

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